简体   繁体   中英

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.

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

ie the parser thought you was creating a generator yielding lambda s 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))

您需要将生成器表达式放在带括号的lambda函数中,而且我认为您还需要检查x % d的结果是否等于零:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM