这是用于查找数字因子之和的代码。在查找因子函数中返回的列表我认为sum函数无法访问,因为当我打印列表时,它给出了正确的列表。
我收到的错误是:TypeError:类型' NoneType'的对象没有len()
def perfect_number(n):
def sum(list,counter,value):
if counter==len(list):
print (value)
else:
sum(list,counter+1,value+list[counter])
def find_factors(n,a,list):
if (a==n):
print (list,len(list))
return (list)
elif (n%a )== 0:
list.append(a)
find_factors(n,a+1,list)
elif (n%a) !=0:
find_factors(n,a+1,list)
xyz = find_factors(n,1,[])
return sum(xyz,0,0)
perfect_number(6)
答案 0 :(得分:2)
你遗漏了一些回复陈述:
def is_perfect_number(n):
def sum_recursive(factors,counter,value):
if counter==len(factors):
return value
else:
return sum_recursive(factors, counter+1, value+factors[counter])
def find_factors(n,a,factors):
if (a==n):
return
elif (n%a) == 0:
factors.append(a)
find_factors(n,a+1,factors)
elif (n%a) !=0:
find_factors(n,a+1,factors)
xyz = []
find_factors(n, 1, xyz)
return sum_recursive(xyz,0,0)==n
print is_perfect_number(6)
print is_perfect_number(28)
print is_perfect_number(228)