如果各个数字的阶乘的总和等于数字本身,则数字是强数字。 例如:145 = 1! + 4! 5!
我在python中为此编写了以下代码:
import math
def strong_num():
return [x for x in range(1,1000) if x==int(reduce(lambda p,q:math.factorial(int(p))+math.factorial(int(q)),str(x)))]
print strong_num()
但是翻译永远不会回来? 这段代码有什么问题?
答案 0 :(得分:7)
您的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
答案 1 :(得分:0)
什么是强数?
强数是那些数字的阶乘之和等于原始数字的数字。 例如: 145是强数。从1开始! + 4! + 5! = 145
num = int(input("Enter any number"))
user_given_no=num
i = 0
fact = 1
fact_list = []
diff_no = []
while num != 0:
i = num % 10
num = num//10
diff_no.append(i)
for y in diff_no:
x = y
fact = 1
while x != 0:
fact *= x
x -= 1
fact_list.append(fact)
sum = 0
for x in fact_list:
sum += x
if sum == user_given_no:
print("Strong number")
else:
print("Not a Strong number")
答案 2 :(得分:0)
强数是那些数字的阶乘和等于原始数的数字。 因此,这里有一个简单的程序可以在python列表中找到强数。
def factorial(number):
if(number == 0 or number == 1):
fact = 1
else:
fact = number * factorial(number - 1)
return fact
def strong_number(list):
new_list=[]
for x in list:
temp = x
sum = 0
while(temp):
rem = temp % 10
sum += factorial(rem)
temp = temp // 10
if(sum == x):
new_list.append(x)
else:
pass
return new_list
# Example 1
val_list = [1,2,5,145,654,34]
strong_num_list = strong_number(val_list)
print(strong_num_list)
# Example 2 and this will return an empty list as there is no strong number found in
the list that is passed
val_list2 = [5,10,14,34,45]
strong_num_list = strong_number(val_list2)
print(strong_num_list)
现在,如果您不想传递列表,则只需从strong_number函数中删除for循环即可。 学习愉快!
答案 3 :(得分:0)
import math
x=(input("enter the number\n"))
y=[int(i) for i in x]
#print("digits of the entered number:\n",y)
z=list((math.factorial(i) for i in y))
#print("factorial of each digit of given number:\n",z)
z=sum(z)
#print("sum of factorials of each digit of the given number:\n",z)
if z==int(x): print(x,"is a Strong Number")
else: print(x,"is not a Strong Number ")
答案 4 :(得分:-1)
您没有正确地将数字分解为其组成数字。你需要reduce来在整数列表上运行lambda,而str(x)不会产生整数列表。