[英]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. 面临的挑战是: 考虑数字的唯一素数是3、5和7。编写一个程序以查找其中的第n个最大数。
Example output : 示例输出:
n = 1
the output should be: 1 (3^0 * 5^0 * 7^0)
. n = 1
,输出应为: 1 (3^0 * 5^0 * 7^0)
。 n = 2
the output should be: 3 (3^1 * 5^0 * 7^0)
. n = 2
,输出应为: 3 (3^1 * 5^0 * 7^0)
。 n = 6
the output should be: 15(3^1 * 5^1 * 7^0)
. n = 6
,输出应为: 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
. 即解析器认为您正在创建一个生成
lambda
的生成器作为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
进行函数调用,这需要在生成器周围加上括号,因此,如果您确实想这样做,则必须编写:
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.