【发布时间】:2019-10-23 15:03:16
【问题描述】:
我是 Python 编程语言的初学者,我一直在使用一个网站来帮助我锻炼。如果给定的数字是narcissistic,那么它给了我一个挑战,如果程序返回true,否则返回false。
自恋数字示例:
153 (3 digits): 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
1634 (4 digits): 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634
但由于某种原因,当给定数字 371 时,函数返回 False 而不是 True。
代码:
def narcissistic(value):
logical = True
logical2 = True
i = 0
j = 0
notation = 10
sum = 0
#Calculating the number notation
while logical:
if 10 ** i <= value:
notation = 10 ** i
i = i + 1
else:
logical = False
#i from now on is also the qauntity of digits
while logical2:
if ( notation / 10 ** j ) >= 1:
sum = sum + ( value // ( notation / 10 ** j ) ) ** i
j = j + 1
else:
logical2 = False
if sum == value:
return True
else:
return False
【问题讨论】:
-
什么是自恋数字?
-
@Hippolippo 重新阅读问题 - 编辑使其更清晰。
-
顺便说一句,如果您将数字转换为字符串并使用数字进行计算,您的算法可能会更好。
-
这个 Wolfram 链接 mathworld.wolfram.com/NarcissisticNumber.html 开始谈论以 10 为基数的数字,就像 OP 一样。
-
不要将变量命名为 sum。