Search code examples
pythonalgorithmpython-2.7list-comprehensiongenerator-expression

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 :

  • For n = 1 the output should be: 1 (3^0 * 5^0 * 7^0).
  • For n = 2 the output should be: 3 (3^1 * 5^0 * 7^0).
  • For n = 6 the output should be: 15(3^1 * 5^1 * 7^0).

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


Solution

  • 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))