2013-10-14 4 views
4

리스트가 회문인지 아닌지를 확인하는 코드는 다음과 같습니다. 그것은 983에 대한 정확한 출력을 제공하고 있습니다. 내가 어디로 잘못 가고 있습니까?회문 체크를위한 파이썬 함수

def palindrome(num): 
    flag=0 
    r=num[::-1] 
    for i in range (0, len(num)-1): 
     if(r[i]==num[i]): 
      flag=1 
     else: 
      flag=0 
    return flag 
+0

당신이 당신의 프로그램을 어떻게 실행이 발생하면? 오류가 있습니까? 그렇다면 오류는 무엇입니까? 그렇지 않다면 출력이 예상 한 것과 어떻게 다릅니 까? –

답변

21

불일치가 발생하는 즉시 반환해야합니다. 또한, 당신은 단지 절반 길이까지 반복해야합니다

def function(...): 
    ... 
    for i in range (0, (len(num) + 1)/2): 
     if r[i] != num[i]: 
      return False 
    return True 

이 BTW, 당신이 루프가 필요하지 않습니다. 당신은 간단하게 수행 할 수 있습니다

def palindrome(num): 
    return num == num[::-1] 
+0

이것이 무슨 뜻인지 설명 할 수 있습니까? num [:: - 1] –

+2

@ImtiazAhmad 그것은'num' 시퀀스를 뒤집습니다. 확장 된 슬라이스 표기법을 찾으십시오. –

4

이 쉬울 것 : 문자의

def palindrome(num): 
    if num[::-1] == num: 
     return True 
    else: 
     return False 
+5

왜 단 한 번의 라이너가 아닌가? def frontindrome (num) : return num [:: - 1] == num – Ishpeck

+6

만약 true라면 return true ...를 반환한다. –

+0

@JoranBeasley : 개인 코딩 스타일 일 뿐이므로이 방법이 더 분명하다고 생각한다. – Synthetica

0

귀하의 for 루프 검사 모든 쌍에 상관없이이 불일치를 발견 아닌지. 따라서 '38113'의 마지막 숫자와 그 역의 버전 '31183'(둘 다 3 인 경우)이 같음을 확인한 후에 이라는 변수가 변수가 True으로 설정되기 때문에 문자열 '38113'의 경우는 True을 반환합니다. 문자열은 회문이 아닙니다).
불일치를 발견 한 직후 False을 반환해야합니다. 모든 문자를 확인하고 그것을 발견하지 않은 경우 - 다음과 같이, True을 반환 : 누군가가 지적

def palindrome(num): 
    r = num[::-1] 
    for i in range (0, len(num)-1): 
     if(r[i] != num[i]): 
      return False 
    return True 

또한, 파이썬의 조각을 사용하는 것이 더있을거야 - documentation을 확인하십시오.

-2
def palindrome(a): 
    a=raw_input('Enter :') 
    b=a[::-1] 
    return a==b 
+2

이것이 왜 해결책인지에 대한 설명을 추가해야합니다 ... –

0
그냥 레코드에 대한

, 주어진 문자열이 회문 인 경우, 동일을 달성하기 위해 두 가지 방법을 검증하기 위해 더 알고리즘 방법을 찾고 사람을 위해 (whilefor 루프 사용) :

def is_palindrome(word): 

    letters = list(word)  
    is_palindrome = True 
    i = 0 

    while len(letters) > 0 and is_palindrome:  
     if letters[0] != letters[-1]: 
      is_palindrome = False 
     else: 
      letters.pop(0) 
      if len(letters) > 0: 
       letters.pop(-1) 

    return is_palindrome 

그리고 .... 두 번째 :

def is_palindrome(word): 

    letters = list(word) 
    is_palindrome = True 

    for letter in letters: 
     if letter == letters[-1]: 
      letters.pop(-1) 
     else: 
      is_palindrome = False 
      break 

    return is_palindrome 
0
str1=str(input('enter string:')) 
save=str1 
revstr=str1[::-1] 
if save==revstr: 
    print("string is pailandrom") 
else: 
    print("not pailadrom") 
+1

코드에 설명을 추가하십시오. OP 코드가 제대로 작동하지 않는 이유는 코드만으로는 도움이되지 않습니다. –

0
# We are taking input from the user. 
# Then in the function we are reversing the input i.e a using 
# slice  [::-1] and 
# storing in b 
# It is palindrome if both a and b are same. 

a = raw_input("Enter to check palindrome:") 
def palin(): 
    #Extended Slices to reverse order. 
    b = a[::-1] 
    if a == b: 
     print "%s is palindrome" %a 
    else: 
     print "%s is not palindrome" %a 
palin() 
0

이 훨씬 쉬울 것 :

def palindrome(num): 
    a=num[::-1] 
    if num==a: 
     print (num,"is palindrome") 
    else: 
     print (num,"is not palindrome") 

x=input("Enter to check palindrome:") 
palindrome(x) 
-1
a="mom" 
b='mom'[::-1] # reverse the string 
if a==b: # if original string equals to reversed 
    print ("palindrome ") 
else: 
    print ("not a palindrome ") 
+1

op의 문제를 어떻게 해결할 지에 대한 의견을 추가해야합니다. 코드에 대한 설명이 도움이 될 수도 있습니다. – stephenmuss