import sys and string Make sure correct number of command-line args were entered
ID: 3635052 • Letter: I
Question
import sys and stringMake sure correct number of command-line args were entered, exiting if not
Open the file for reading
Read the lines in the file into a list of strings
(don't forget to strip the trailing whitespace)
Close the file
For each of the strings in the list of strings
Make a temporary string that holds only the letters of the string
all in upper case
The data file, strings.dat, contains many phrases, some of which are palindromes. Your program should accept the name of the data file as a command-line argument and read in the strings. It should determine whether a given word, phrase or sentence is a palindrome and print out the phrases that are.
Determine if the temporary string is a palindrome.
If it is, print its original string
OUTPUT
The palindromes in the file are:
Otto
Anna
Able was I ere I saw Elba
Madam, I'm Adam.
Was it a cat I saw?
A man, a plan, a cat, a canal: Panama?
Explanation / Answer
Palindrome Checking (Python) # check if a phrase is a palindrome # tested with Python24 vegaseat 10sep2006 def isPalindrome(phrase): """ take a phrase and convert to all lowercase letters and ignore punctuation marks and whitespaces, if it matches the reverse spelling then it is a palindrome """ phrase_letters = [c for c in phrase.lower() if c.isalpha()] print phrase_letters # test return (phrase_letters == phrase_letters[::-1]) phrase1 = "A man, a plan, a canal, Panama!" # example with punctuation marks if isPalindrome(phrase1): print '"%s" is a palindrome' % phrase1 else: print '"%s" is not a palindrome' % phrase1 print phrase2 = "Madam in Eden I'm Adam" if isPalindrome(phrase2): print '"%s" is a palindrome' % phrase2 else: print '"%s" is not a palindrome' % phrase2 helps you?-->http://www.csee.umbc.edu/courses/201/spring08/projects/p4/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.