你的reduce
输入是错误的,你不应该计算的阶乘p
。事实上,它更容易使用sum
:
return [x for x in range(1, 1000)
if x == sum(math.factorial(int(q)) for q in str(x))]
该functools.reduce
函数可以被认为是:
reduce(f, [a, b, c, d, ...]) == f(f(f(a, b), c), d) ...
因此,例如,如果 x == 145,那么您的reduce
部分将计算
int(reduce(lambda p, q: factorial(int(p)) + factorial(int(q)), str(x)))
== int(reduce(lambda p, q: factorial(int(p)) + factorial(int(q)), "145"))
== int(factorial(factorial(1) + factorial(4)) + factorial(5))
== int(factorial(1 + 24) + 120)
== int(15511210043330985984000000 + 120)
== 15511210043330985984000120
解释器可能无法完成,因为需要计算极大数的阶乘(考虑 (2 × 9!)!...)
如果您仍然需要保留reduce
,则应将其更改为:
reduce(lambda p,q: p + math.factorial(int(q)), str(x), 0)
# ^ ^
# No need to factorial Add initializer too