2013-07-02 3 views
1

Python과 프로그래밍에 익숙하지 않은 사람.Palindrome 생성기

제한된 회문 수의 목록을 생성하는 함수를 만들려고합니다.

다음 코드를 실행하면 빈 목록 []이 반환됩니다. 이것이 확실한 이유는 확실하지 않습니다. n 여부

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 

답변

3

귀하의 if 명세서는 이 아니며이 수행한다고 생각하는대로 처리하십시오.

당신은 운영자 체인을 적용하면 2 가지를 테스트 : True가 아닌 False'0' is True 때문에

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

이것은 항상 될 것입니다. 데모 다음 comparisons documentation에서

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

:

비교는 (그러나 두 경우 모두 z가에서 평가되지 않는 한 번만 평가 될 수 y 제외하고는, 예를 들어, x < y <= zx < y and y <= z에 해당 임의로 체인 될 수있다 x < y이 거짓 일 때 모두).

현재 is True을 테스트하기 하지 필요성을; 파이썬의 if 문 자체에 대한 그 테스트를 완벽하게 할 수있다 :

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

당신의 다음 문제는 당신이 n을 변경하지 않을, 그래서 지금 당신은 당신의 목록 1000 '0' 문자열을 추가 할 것이라는 점이다.

당신은 xrange(1000) 통해 for 루프를 사용하고 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'] 
+0

훌륭한 답변, 응답 해 주셔서 감사합니다. – Chris

0

귀하의 if 블록 검사는 회문이며, n의 값은 변하지 않습니다. 한 번만 할당되었습니다.

또한 중복되므로 is True 부분을 제거 할 수 있습니다.

하지만 지금은 문제의 근원이 아닙니다. 실제로 if이 실패하는 이유는 연산자 우선 순위입니다. 지금 작성한 내용은 if n==(n[::-1] is True):if n==False:과 동일합니다. 이는 결코 발생하지 않습니다.

+0

그러나 그때 그것은 '0'1000 번을 추가 할 것입니다. –

+0

@MartijnPieters : True. 나는 is에 대한 설명을 덧붙였다. – recursive

1

모든 숫자를 통과하는 것은 매우 비효율적이다.다음과 같은 문장을 생성 할 수 있습니다.

#!/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 remarks.