2014-12-16 2 views
-4

코드가 좀 복잡하지만 요점은 그것을 다른 기능으로 나누는 것입니다.Python palindrome programming

나는 당신이 회문을 테스트 할 수 있다는 것을 이해하지만 바로 인쇄 기능을 설명하는 대신 부울 변수를 사용하는 방법을 알고 있습니다.

def is_palindromic(s): 
    return s == s[::-1] 

그리고 :

def trial(): 
    palindrome = True 

    c = str(input("Hey: ")) 

    for i in range(len(c)): 
     a = c[i] 
     s = c[-(i+1)] 
    if (a == s):  
     return 
    break 
    else: 
     print ("No, its not a plaindrome") 
    break 

    return palindrom 

def output(): 
    print True 


trial() 
output() 
+1

들여 쓰기가 약간 벗어난 것처럼 보입니다.하지만 'return true'또는 'return False'를 사용할 수 있습니다. – user2097159

답변

4

당신은 여기

>>> output('hello') 
not a palindrome 

>>> output('abcba') 
it is a palindrome 
-1

이 회문을 확인하는 간단한 방법입니다 예를 들어 다른 기능

def isPalindrome(s): 
    return s == s[::-1] 

def output(s): 
    if isPalindrome(s):   # We use the return value of the above function 
     print('it is a palindrome') 
    else: 
     print('not a palindrome') 

return 값을 사용할 수 있습니다 그때 우리 e if 문의 리턴 값.

if is_palindromic(s): 
    print "Yay!" 
else: 
    print "Too bad" 
0

프로그래밍 아이디어에 약간의 배경 - 내가 (그리고 아마도 다른 사람뿐만 아니라)로 문의 증인. 무슨 뜻이에요? 그것은 우리가 잘못 될 때까지 somethnig이 True이라고 가정한다는 것을 의미합니다. 이것은 현대 법원에서도 유죄로 입증되지 않는 한 무죄 인 경우에도 마찬가지입니다.

# let's go on to the trial! 
def trial(): 
    # the string is a palindrome, or "innocent" (this is redundant in this case) 
    palindrome = True 
    c = str(input("Hey: ")) 

    # this iterates the string twice, you actually need half 
    # but that's only an optimization. 
    for i in range(len(c)): 
     a = c[i] 
     s = c[-(i+1)] 
     # if we found characters that are not mirrored - this is not a palindrome. 
     # these are our witnesses! 
     if (a != s):   
      return False # naive: palindrome = False 
    # we've gone over the string and found no witnesses to say it's "guilty" 
    return True # naive: return palindrome 

이 스타일을 사용하는 경우, 당신은 단지 "유죄"부분에 관심 기억하고 즉시 return 할 수 있습니다

지금의 코드를 보자.