Unclear how to use takewhile python

Pradeep Kumar

I'm trying to get the divisor length of n (which is a list) if it divides the len(n) with no remainder.

i = takewhile(lambda d: len(n) % d == 0 for d in range(3, 6), n)

I have received following syntactical error

Generator expression must be parenthesized if a not sole argument

So instead I modified my code to the following:

i = takewhile((lambda d: len(n) % d == 0 for d in range(3, 6)), n)

itertools.takewhile at 0xa7075c8>

What am I going wrong?

Willem Van Onsem

The reason it outputs <itertools.takewhile at 0xa7075c8> is because itertools produces generators, not lists. So the result is not materialized until you really need it (or wrap a list(..) around it).

Well as the compiler says, the generator should have parentesis, not the entire lambda expression. So:

i = takewhile(lambda d: (len(n) % d == 0 for d in range(3, 6)), n)

But we are not there yet: you define d both in the head of your lambda and in the generator, indeed:

i = takewhile(lambda d: (len(n) % d == 0 for d in range(3, 6)), n)

Finally you use takewhile the wrong way I think. As far as I know you want the first element that succeeds, you can simply call .next() on your constructed generator, so you probably want:

i = (d for d in range(3, 6) if len(n) % d == 0).next()

in Python-2, or:

i = next(d for d in range(3, 6) if len(n) % d == 0)

in Python-3.

Running this in an interpreter gives:

$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> n=[1,2,3,4,5,6,7,8,9]
>>> i = next(d for d in range(3, 6) if len(n) % d == 0)
>>> i
3
>>> n=[1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5]
>>> i = next(d for d in range(3, 6) if len(n) % d == 0)
>>> i
5

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related