kuskmen
kuskmen

Reputation: 3775

Having trouble with generator in list comprehension

I am trying to do one liner of one challenge in codefights , but I seem to be stuck with:

SyntaxError: Generator expression must be parenthesized if not sole argument

when I execute

def magicNumber(n):
    return [i for i in itertools.takewhile
                       (lambda x: x % d for d in [3,5,7] == 0, range(0,n))]

The challenge is: Consider the numbers the only prime factors of which are 3, 5 and 7. Write a program to find the nth largest among them.

Example output :

I know I am far from solving it with this I just want to know what's the problem here.

Upvotes: 0

Views: 5771

Answers (2)

Kasravnd
Kasravnd

Reputation: 107287

You need to put your generator expression in lambda function in a parenthesis, also I think you need to check the equality of the result of x % d with zero:

lambda x: (x % d==0 for d in [3,5,7])

Upvotes: 3

Bakuriu
Bakuriu

Reputation: 101919

You need to add the parenthesis:

takewhile(lambda x: (x % d for d in [3,5,7] == 0), range(0,n))

Note that your original code was parsed as:

takewhile((lambda x: x % d) for d in [3,5,7] == 0, range(0,n))

i.e. the parser thought you was creating a generator yielding lambdas as first argument to takewhile. And you are doing a function call to takewhile with two arguments, which requires parenthesis around the generator, so if you really wanted to do that you had to write:

takewhile(((lambda x: x % d) for d in [3,5,7] == 0), range(0,n))

Upvotes: 4

Related Questions