
Nastiest Python list comprehension ever - cool-RR
http://blog.garlicsim.org/post/3504711416/nastiest-python-list-comprehension-ever
======
acangiano

        >>> def mystery(n):
    

It's a buggy implementation of primes_below(n) through a sieve.

"There should be one - and preferably only one - obvious way to do it." And
this ain't it.

------
StavrosK
> Does anyone have a suggestion on how to do it?

Yes, provide more details so I don't have to spend twenty minutes figuring out
what it does.

(Going by my three-second-look gut feeling: It's the Sieve of Eratosthenes)

~~~
srean
Yes, but I could not understand why one needs

    
    
      list(range(n)) as opposed to range(n)
    

and why the double indexing of a in

    
    
      i in a[:][2:] if a[i] == i].
    

Am I missing something ? I think it would work without those.

Edit: Yo La Tengo. Deviousness aside the code is quite nice. It would be fun
to optimize it but without breaking its spirit.

~~~
StavrosK
list(range(n)) is probably because the author was using Python 3, in which
range() returns an iterator (think xrange in 2.x). The double indexing is
probably because a[:] returns a copy of a and the author doesn't want to
iterate over the modified array, since he modifies it down the line (although
the [2:] would copy it too, so no idea).

An alternative to a[:][2:] would just be range(2, n), but the author clearly
doesn't want it to be readable.

------
ffffruit
Can somebody from the Perl community please but this guy in the right place by
supplying a one-liner Perl golf quadruple map call?

~~~
btilly
You mean like this implementation of the Sieve of Eratosthenes?

    
    
      sub sieve3 {
          grep{@_[map$a*$_,$_..@_/($a=$_)]=0if$_[$_]>1}@_=0..pop
      }
    

I shamelessly stole that from
<http://www.perlmonks.org/index.pl/?node_id=81769>. If you just want a short
solution, but don't care about the algorithm, then the following works:

    
    
      sub sieve {
          sub p{$_[0],@_>1?p(grep$_%$_[0],@_):1}p 2..pop
      }
    

See <http://www.perlmonks.org/index.pl/?node_id=81771> for the original.

~~~
StavrosK
Are you sure that's Perl? Are you sure it's not... nothing?

Seriously, I cannot fathom _why_ this would work, let alone how. The syntax is
completely alien to me.

~~~
jrockway
Add some spaces:

    
    
        sub sieve {
            sub p {
               $_[0] , @_>1 ? p(grep$_%$_[0],@_) : 1;
            }
            p(2..pop)
        }
    

And if you get rid of some terse syntax:

    
    
        sub p {
            my ($first, @rest) = @_;
            if (@rest > 1){
                return $first, p(grep { $_ % $first } @rest);
            }
            return 1;
        }
    
        sub sieve {
            my $arg = shift;
            return p(2..$arg)
        }
    
    

BTW, you can even have Perl do this automatically for you, by running:

    
    
        $ perl -MO=Deparse
        <paste in the code>
        sub p {
            $_[0], @_ > 1 ? p(grep(($_ % $_[0]), @_)) : 1;
        }
        sub sieve {
            p 2 .. pop @_;
        }
    

But honestly, the first program is not incomprehensible if you've ever
programmed in Perl. Sure, it ain't literate programming, but it also isn't
beyond understanding if you have three minutes to spend on it.

It's an amusement, not your payroll system, after all.

~~~
StavrosK
Thanks, I have indeed never programmed in perl and was feeling a bit
facetious.

------
lmkg
I think it's a testimony to the readability of Python that I've never even
programed in the language, nor am I familiar with the finer points of the list
syntax (a[::2]?!), and yet this mucked up piece of shit nonetheless gave me
the first impression of a prime number sieve. I actually still don't
understand how the sieve works, but it somehow just _looks like one_. Or is it
just the case that assuming every obfuscated loop is a prime number sieve is
disproportionately likely to be true?

------
agentultra
Does that even run? :)

Nested comprehensions are one of the things I hate about Python actually. The
functions in itertools are so much clearer. I can't really think of a good
reason to use nested comprehensions... they become unreadable really fast!

~~~
cool-RR
The nesting of list comprehension is just an aperitif in this function.

------
jakozaur
Corrected version:

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

------
stcredzero
Isn't the point of a list comprehension - comprehension?

(It's a paraphrase of something Feynman once said to Murray Gell-Mann.)

------
shangaslammi
Wow. I hadn't realized that syntax like "for a[::i] in" is valid Python.
Attribute assignment (for x.foo in) seem to work too. I'm not sure if there
will ever be any reason to use those in real code, but it's nice trivia to
know for Python golfing.

------
francoisdevlin
This is why moving away from higher order functions and towards list
comprehensions is a mistake.

Bad BDFL, bad!

~~~
RiderOfGiraffes
What, you mean because HOFs can't be tortured into unreadability?

Readability requires that the programmer conspires with both the language and
the reader. Unreadable code can be written in any style, any paradigm and any
language. Sometimes it doesn't even take effort, talent or skill.

------
saurik
My favorite to date is:

bps = [map(int, bps.split('/')) if isinstance(bps, str) else bps for bps in
bps if bps]

The clause "else bps for bps in bps if bps" made me incredibly incredibly
happy.

