1

对python和一般编程非常缺乏经验。

我正在尝试创建一个函数,该函数生成一个回文数列表,直到指定的限制。

当我运行以下代码时,它返回一个空列表 []。不知道为什么会这样。

def palin_generator():
    """Generates palindromic numbers."""

    palindromes=[]
    count=0
    n=str(count)

    while count<10000:
        if n==n[::-1] is True:
            palindromes.append(n)
            count+=1
        else:
            count+=1

    print palindromes  
4

3 回答 3

3

你的if陈述并没有像你认为的那样做。

您正在应用运算符链接,并且正在测试两件事:

(n == n[::-1]) and (n[::-1] is True)

这将永远False因为'0' is True不是True。演示:

>>> n = str(0)
>>> n[::-1] == n is True
False
>>> n[::-1] == n 
True

比较文档中:

比较可以任意链接,例如,x < y <= z等价于x < y and y <= z,除了y只评估一次(但在两种情况下,当发现为假z时根本不评估)。x < y

不需要在这里测试is True;Python 的if语句完全有能力为自己进行测试:

if n == n[::-1]:

你的下一个问题是你永远不会改变n,所以现在你将 1000 个'0'字符串附加到你的列表中。

你最好使用for循环xrange(1000)并设置n每次迭代:

def palin_generator():
    """Generates palindromic numbers."""

    palindromes=[]

    for count in xrange(10000):
        n = str(count)
        if n == n[::-1]:
            palindromes.append(n)

    print palindromes  

现在您的功能有效:

>>> palin_generator()
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '11', '22', '33', '44', '55', '66', '77', '88', '99', '101', '111', '121', '131', '141', '151', '161', '171', '181', '191', '202', '212', '222', '232', '242', '252', '262', '272', '282', '292', '303', '313', '323', '333', '343', '353', '363', '373', '383', '393', '404', '414', '424', '434', '444', '454', '464', '474', '484', '494', '505', '515', '525', '535', '545', '555', '565', '575', '585', '595', '606', '616', '626', '636', '646', '656', '666', '676', '686', '696', '707', '717', '727', '737', '747', '757', '767', '777', '787', '797', '808', '818', '828', '838', '848', '858', '868', '878', '888', '898', '909', '919', '929', '939', '949', '959', '969', '979', '989', '999', '1001', '1111', '1221', '1331', '1441', '1551', '1661', '1771', '1881', '1991', '2002', '2112', '2222', '2332', '2442', '2552', '2662', '2772', '2882', '2992', '3003', '3113', '3223', '3333', '3443', '3553', '3663', '3773', '3883', '3993', '4004', '4114', '4224', '4334', '4444', '4554', '4664', '4774', '4884', '4994', '5005', '5115', '5225', '5335', '5445', '5555', '5665', '5775', '5885', '5995', '6006', '6116', '6226', '6336', '6446', '6556', '6666', '6776', '6886', '6996', '7007', '7117', '7227', '7337', '7447', '7557', '7667', '7777', '7887', '7997', '8008', '8118', '8228', '8338', '8448', '8558', '8668', '8778', '8888', '8998', '9009', '9119', '9229', '9339', '9449', '9559', '9669', '9779', '9889', '9999']
于 2013-07-02T20:43:15.447 回答
3

遍历所有数字是非常低效的。你可以像这样生成回文:

#!/usr/bin/env python
from itertools import count

def getPalindrome():
    """
        Generator for palindromes.
        Generates palindromes, starting with 0.
        A palindrome is a number which reads the same in both directions.
    """
    yield 0
    for digits in count(1):
        first = 10 ** ((digits - 1) // 2)
        for s in map(str, range(first, 10 * first)):
            yield int(s + s[-(digits % 2)-1::-1])

def allPalindromes(minP, maxP):
    """Get a sorted list of all palindromes in intervall [minP, maxP]."""
    palindromGenerator = getPalindrome()
    palindromeList = []
    for palindrome in palindromGenerator:
        if palindrome > maxP:
            break
        if palindrome < minP:
            continue
        palindromeList.append(palindrome)
    return palindromeList

if __name__ == "__main__":
    print(allPalindromes(4456789, 5000000))

这段代码比上面的代码快得多。

另请参阅:Python 2.x 备注

于 2013-11-08T10:49:31.960 回答
0

您的if块检查是否n是回文,并且n永远不会改变的值。它只分配一次。

此外,您可以消除该is True部分,因为那是多余的。

但这不是你现在问题的根源。实际上,您if失败的原因是运算符优先级。你现在写的相当于if n==(n[::-1] is True):which is if n==False:,它永远不会发生。

于 2013-07-02T20:41:52.327 回答