【问题标题】:I'm trying to find sum of first n palindromes using python我正在尝试使用 python 查找前 n 个回文数的总和
【发布时间】: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 True num 是来自global 范围的变量num = int(input("Enter a number: "))。例如,您确定要与num 进行比较,而不是p
  • 嗯,是的,我的意思是把它和 p 比较 谢谢@ForceBru
  • 要检查它是否是回文,将其反转为字符串更容易。您的函数可以替换为 return str(p) == str(p)[::-1]

标签: python while-loop palindrome


【解决方案1】:

我相信问题出在您的 ispalindrom 函数上,它返回 200 作为回文数

def ispalindrome(p):
    rev = int(str(p)[::-1])
    if p == rev:
        return True
    else:
        return False

num = int(input("Enter a number: "))
i = 1
count = 0
sum = 0
while (count <= num - 1):
    if (ispalindrome(i) == True):
        print(i)
        sum = sum + i
        count = count + 1
    i = i + 1
print("Sum of first", num, "palindromes is", sum)

【讨论】:

    【解决方案2】:
    def is_palindrome(number):
        return str(number) == str(number)[::-1]
    
    num = int(input("Enter a number: "))
    palindromes = [i for i in range(1, num) if is_palindrome(i)]
    print(f"Sum of the {len(palindromes)} palindromes in range {num} is {sum(palindromes)}")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-28
      • 2015-06-19
      • 2020-08-08
      • 1970-01-01
      相关资源
      最近更新 更多