简体   繁体   中英

Returning result of palindrome program using while-loop

n = str(input('Enter the string:'))
def palindrome(n):
    index = 0
    check = True
    while index<int(len(n)/2):
        if n[index]==n[-1-index]:
            index+=1
            return True
            break
        return False
if palindrome(n)==True:
    print('palindrome')
else:
    print('not palindrome')

I am not getting the correct answer for this palindrome program.

使用raw_input:

n = str(raw_input('Enter the string:'))
def palindrome(my_string):
    reverse_string = my_string[::-1]
    if list(my_string)==list(reverse_string):
       return True
    else:
       return False
my_string = input("ENTER THE STRING ")
if(palindrome(my_string)):
    print("Palindrome")
else:
    print("Not Palindrome")

The classic solution:

def palindrome(n):
    start = 0
    end = len(n) - 1
    while (start < end):
        if (n[start] != n[end]):
            return False
        start = start + 1
        end = end - 1
    return True
while index < int(len(n) / 2):
    if n[index] != n[len(n) - index - 1]:
        return False
    index+=1
return True

Your check is broken. Look at return True :

def palindrome(n):
    index = 0
    check = True
    while index<int(len(n)/2):
        if n[index]==n[-1-index]:
            index+=1  # only increment on match !!!
            return True  # return True on *first* match !!!
            break  # unnecessary, return exits the loop
        return False  # never reached, but would only trigger if there are no matches

Basically, you go through your string and on the first match you report True. So if first and last letter are the same, True is returned. Only if no pair of characters matches, you return False . This is the opposite of what want to check. It should be this instead:

def palindrome(n):
    index = 0
    check = True
    while index < len(n)/2:
        if n[index] != n[-1-index]:
            return False  # one didn't match, cannot be a palindrome
        index+=1
    return True  # all did match, is a palindrome

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM