【问题标题】:counting the number of palindromes in a range in python在python中计算一个范围内的回文数
【发布时间】:2013-03-24 03:33:41
【问题描述】:

我对 python 有点陌生。我试图通过一个特定的数字范围,让 python 计算其中的所有回文并将它们返回给我(总数,而不是它们的总和)。所以它会计算这个范围内的所有整数并将其作为一个数字返回给我。

我不断收到无效的语法错误,我不知道要更改什么。这是我到目前为止所拥有的:

import math

def ispal(n):
    return str(n) == str(n)[::-1]

但这基本上就是我们在课堂上所做的。

我的数字范围是从 171 到 115000,我想遍历这两个数字之间的整个范围,包括这两个数字,让 python 告诉我有多少数字是回文数。问题是我不知道如何适应 for 循环。

我开始:

def count_pal(n):  
   count = 0  
   for i in range(n):  
       if i = str(n) == str(n)[::-1]:
           return:  
           count =+ i   
   else:
       pass

但我不知道如何将两者放在一起。我有python 3.2。谁能帮帮我?谢谢!

【问题讨论】:

    标签: python for-loop python-3.x palindrome


    【解决方案1】:
    def num_palindromes(start, end):
        count = 0
        for i in range(start, end + 1):
            if str(i) == str(i)[::-1]:
                count += 1
        return count
    

    或者作为一个班轮

    def num_palindromes(start, end):
        return sum(str(i) == str(i)[::-1] for i in range(start, end + 1))
    

    【讨论】:

    • 首先谢谢您!你如何让它显示数字?当我写 print(count) 时,它说 count 没有定义。
    • @user2172079 计数仅在函数中定义,因此仅限于函数范围。该函数返回回文数,所以你会得到它:count = num_palindroms(1, 10)
    • 这是我写的,它仍然说计数未定义。我用错了什么?我可以用 print 告诉我计数器的结果吗?你是怎样做的? def num_palindromes(start, end): count = 0 for i in range(171, 115000 + 1): if str(i) == str(i)[::-1]: count += 1 count = num_palindroms(171 , 11500+1) 返回计数 print(count)
    • @user2172079 我无法在 cmets 中读取该代码。如果你愿意,你可以更新问题。
    • def num_palindromes(start, end): count = 0 for i in range(171, 115000 + 1): if str(i) == str(i)[::-1]: count += 1 count = num_palindroms(171, 11500+1) return count print(count)
    【解决方案2】:

    在您有机会增加计数器之前,您将返回到 for 循环中 你也不需要那个空的 'else: pass' 块,因为它什么都不做。

    循环终止后,正确的解决方案将在函数末尾返回计数器。

    这样的事情会起作用:

    count = 0
    for i in range(171, 115000):
        if str(i) == str(i)[::-1]:
            count += 1
    return count
    

    注意一些样式更改: - 4 空格缩进 - 没有多余的换行符 - 无需将 i 从“真/假”强制转换为数字(当您执行 i = str(i) == str(i)[::-1] 时,您会在代码中得到该数字)

    与您的问题没有直接关系,但遵循 python 常规样式将有助于使您的代码更具可读性,更易于他人理解和帮助您。

    最后,就像一个额外的花絮,你也可以通过列表理解来完成这个任务:

    sum([1 for i in range(171, 115000) if str(i) == str(i)[::-1]])
    

    我个人觉得它比循环计数器变体更简洁/更容易理解。

    【讨论】:

    • 非常感谢!一个班轮似乎工作。但是我如何获得函数来为我显示计数的最终值?因为 print(count) 不起作用。
    猜你喜欢
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多