121k views
5 votes
Write a program named palindromefinder.py which takes two files as arguments. The first file is the input file which contains one word per line and the second file is the output file. The output file is created by finding and outputting all the palindromes in the input file. A palindrome is a sequence of characters which reads the same backwards and forwards. For example, the word 'racecar' is a palindrome because if you read it from left to right or right to left the word is the same. Let us further limit our definition of a palindrome to a sequence of characters greater than length 1. A sample input file is provided named words_shuffled. The file contains 235,885 words. You may want to create smaller sample input files before attempting to tackle the 235,885 word sample file. Your program should not take longer than 5 seconds to calculate the output

In Python 3,
MY CODE: palindromefinder.py
import sys
def is_Palindrome(s):
if len(s) > 1 and s == s[::-1]:
return true
else:
return false
def main():
if len(sys.argv) < 2:
print('Not enough arguments. Please provide a file')
exit(1)
file_name = sys.argv[1]
list_of_palindrome = []
with open(file_name, 'r') as file_handle:
for line in file_handle:
lowercase_string = string.lower()
if is_Palindrome(lowercase_string):
list_of_palindrome.append(string)
else:
print(list_of_palindrome)
If you can adjust my code to get program running that would be ideal, but if you need to start from scratch that is fine.

1 Answer

5 votes

Open your python-3 console and import the following .py file

#necessary to import file

import sys

#define function

def palindrome(s):

return len(s) > 1 and s == s[::-1]

def main():

if len(sys.argv) < 3:

print('Problem reading the file')

exit(1)

file_input = sys.argv[1]

file_output = sys.argv[2]

try:

with open(file_input, 'r') as file open(file_output, 'w') as w:

for raw in file:

raw = raw.strip()

#call function

if palindrome(raw.lower()):

w.write(raw + "\\")

except IOError:

print("error with ", file_input)

if __name__ == '__main__':

main()

User Alex McLean
by
4.1k points