A blog about the development and usage of GarlicSim, the open-source Pythonic framework for computer simulations.
Written by Ram Rachum, developer of GarlicSim.

GarlicSim Website

Twitter

GitHub Repository

Ram's Personal Website

25th February 2011

Text

Nastiest Python list comprehension ever

I just came up with the nastiest Python list comprehension ever.

Here it is in all its glory:

def mystery(n):
    a = list(range(n))
    return [[i for a[::i] in [a[::i][::-1]]][0] for
             i in a[2:] if a[i] == i] 

I apologize in advance to anyone who will try to understand what this function does and how it works. Hint: It returns a bunch of numbers which have a certain mathematical property.

Actually, its results are not perfect: It throws in a few false positives. I tried to fix it to remove the false positives; I can easily write code that will filter the false positives away, but I want any extra code to live up to the unidiomatism level of the list comprehension itself. That’s not an easy task :)

Does anyone have a suggestion on how to do it?

Comments
All content in this website is copyright © 1986-2011 Ram Rachum.
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License, with attribution to "Ram Rachum at ram.rachum.com" including link to ram.rachum.com.
To view a copy of this license, visit: http://creativecommons.org/licenses/by-sa/3.0/