Python @ DjangoSpin

PyPro #7 String Palindrome

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

String Palindrome in Python

String Palindrome in Python

Python script to determine whether a given string is a palindrome or not.

## A string is a palindrome if it is spelt the same way backwards as it is spelt forwards e.g. 'malayalam', 'step on no pets', 'level'.

## THOUGHT PROCESS: Prompt the user for a string -> assign it to a variable, cast if necessary -> set a flag with a default value ->  iterate over first half of word and set the flag to False if any pair of corresponding characters from the beginning and from the end are not the same(keep in mind that first and last character indexes are 0 and ( length - 1 ), respectively) -> Break from the loop if any mismatch occurs -> output the conclusion

## INPUT
enteredString = input("Please enter a string to be tested: ")
isPalindrome = True ## starting with a True flag, will switch it to False if any mismatch in corresponding positions occurs.
 
## LOGIC
# Comparing characters from the first half of the word with those in the second half, and if any pair of characters in corresponding positions from the beginning and from the end do NOT match, set the flag to False.
## PSEUDO CODE / ALGORITHM
# With a for loop, iterate over each character in the first half of the word using indexes
#     Check if character at position x is NOT equal to character at position (length of word - x - 1)
#         Set flag to False as soon as the above condition is satisfied
#         Break from the loop
for characterPosition in range(0,  len(enteredString) // 2):
    if enteredString[characterPosition] != enteredString[len(enteredString) - characterPosition - 1]:
        isPalindrome = False
        break
 
## Outputting Conclusion
if isPalindrome:
    print("'" + enteredString + "' is a palindrome.")
else:
    print("'" + enteredString + "' is not a palindrome.")
Try it here.

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply