Python - 阶乘的总和

时间:2013-06-19 00:27:58

标签: python

我试图创建一个程序来检查每个数字,看它是否等于各个数字的阶乘的总和。由于某种原因,我无法在列表中添加任何值,如果我要在每个实例后打印求和变量,它将显示总和等于0.任何人都可以帮忙吗?

import math

x = 2
y = 0
summed = 0
listed = []

while x < 10000000:
        x += 1
        summed = 0
        xString = str(x)
        xLength = len(xString)
        while y < xLength:
                summed += math.factorial(int(xString[y]))
                y += 1
        if (x == summed):
                listed.append(x)

y = 0
summed = 0

listLength = len(listed)

while y < listLength:
        summed += listed[y]
        y += 1

print(listed)
print(summed)

5 个答案:

答案 0 :(得分:2)

没关系,我注意到我没有在每个实例结束时重置y值。

y = 0

这就是全部。

答案 1 :(得分:2)

您需要在while循环中设置y = 0

答案 2 :(得分:2)

循环字符串的更好方法是这样的:

xString = str(x)
for c in xString:
    summed += math.factorial(int(c))

在最终名单上:

for item in listed:
    summed += item

然后你根本不需要y

答案 3 :(得分:1)

稍微简化的版本:

import math

listed = []
for x in xrange(2, 10000000):
    summed = sum(math.factorial(int(d)) for d in str(x))
    if (x == summed): listed.append(x)
summed = sum(y for y in listed)

print(listed)
print(summed)

和一些更快的版本:

import math

facts  = dict()
def ffact(sn):
    if len(sn) == 1: return math.factorial(int(sn))
    if sn not in facts:
        facts[sn] = ffact(sn[0])
        if len(sn) > 1: facts[sn] += ffact(sn[1:])
    return facts[sn]

listed = list()
for x in xrange(2, 1000000):
    if ffact(str(x)) == x: listed.append(x)
summed = sum(y for y in listed)

print(listed)
print(summed)

答案 4 :(得分:1)

(这不是一个答案,但因为很难将代码格式化为评论。)

from math import factorial as fact

def digits(n):
    return [int(d) for d in str(n)]

def isSumOfOwnDigitsFactorialed(n):
    return n==sum(fact(d) for d in digits(n))

演示:

>>> digits(152)
[1, 5, 2]

>>> [i for i in range(10**6) if isSumOfOwnDigitsFactorialed(i)]
[1, 2, 145, 40585]