【发布时间】:2020-07-17 10:53:23
【问题描述】:
这是我的代码:
def ispalindrome(p):
temp = p
rev = 0
while temp != 0:
rev = (rev * 10) + (temp % 10)
temp = temp // 10
if num == rev:
return True
else:
return False
num = int(input("Enter a number: "))
i = 1
count = 0
sum = 0
while (count <= num - 1):
if (palindrome(i) == True):
sum = sum + i
count = count + 1
i = i + 1
print("Sum of first", num, "palindromes is", sum)
我相信我的 ispalindrome() 函数有效。我试图找出我的 while 循环中有什么问题。 到目前为止,这是我的输出:
n = 1 答案 = 1,
n = 2 答案 = 22,
n = 3 答案 = 333 ...
我也认为这方面的运行时间真的很糟糕 请帮忙
【问题讨论】:
-
欢迎,将
palindrome替换为ispalindrome -
我刚做了,还是不行
-
在
if num == rev: return Truenum是来自global 范围的变量num = int(input("Enter a number: "))。例如,您确定要与num进行比较,而不是p? -
嗯,是的,我的意思是把它和 p 比较 谢谢@ForceBru
-
要检查它是否是回文,将其反转为字符串更容易。您的函数可以替换为 return str(p) == str(p)[::-1]
标签: python while-loop palindrome