Docsity

EECS12 Homework #3: Python Function Assignment, Assignments of Electrical and Electronics Engineering

Toggle sidebar
bg1
EECS12 Homework #3 Due: 11:59 PM, Friday, January 28, 2005
For this assignment you are to create and submit a single Python module named ā€œhw3.pyā€ containing
definitions for the following functions (with precisely these spellings):
1. IsPalindrome
2. MakeDictionary
3. CountWords
You will also need the function GetTokens from the previous assignment, which you must include
in this file. (As always, you may also include any other functions that you deem necessary.) You
may either use your own version of GetTokens, or the version that will be posted for you on the
downloads page. If you use your own version, make sure it works correctly–you would not want
to lose points twice for the same mistake! This assignment has two objectives: To familiarize you
with reading and writing to files, and to give you some practice in writing programs that catch and
handle errors. Here is what you need to do:
1. Read chapters 9 and 11 of How to Think Like a Computer Scientist. Be sure to understand
how to read from and write to files, and how to check for exceptions. You may also find chapter
6ofDive into Python to be useful.
2. Write a function called IsPalindrome that accepts a single argument, which must be a string
(of any length). The function is to return True if the string is a pal in dro me and False otherwise.
A palindrome is a word, or more generally any string of symbols, that is the same when spelled
forwards and backwards. For example, the words ā€œradar,ā€ and the name of a once-popular
programming language, ā€œAda,ā€ are both palindromes. Note that ā€œAdaā€ literally spelled back-
wards is ā€œadA,ā€ which is not the same as the original, because of capitalization. You need to
account for this. (Hint: See the function ā€œupcaseā€intheSamples2.py file.) For example,
IsPalindrome( "aabb12 @!!@ 21bbaa" ) and IsPalindrome( "Ada" ) should both return
True, while IsPalindrome( "Mumble" ) and IsPalindrome( "Not quite! etiuq toN" )
should both return False.
Your function should check that the argument that it is passed is a string; if not, the function
should raise an exception (using the raise command) and return False.
3. Write a function called MakeDictionary that accepts a single argument, which must be a
string. (Raise an exception if the argument is not a string.) The function is to attempt to
open a file of the name given in the string. If the open fails, print an error message (using print,
not raise) and return None as the function value. You must use a try:-except: construct
for this. If the file is successfully opened, read successive lines from the file and break each line
into a sequence of tokens using GetTokens.BeforeusingGetTokens you should chop off the
ā€œnewlineā€ character readline returns at the end of each string using the ā€œ[:-1]ā€construct;
that is, if Sis a string, then S[:-1] returns the entire string, minus the last character. Add
each token (including ā€œpunctuationā€) to a dictionary in which you maintain a count of every
token that is used.
When the end of the file is reached, return the dictionary as the function value. The dictionary
is to associate each word with an integer representing the number of times that word appeared
in the file. For example if MakeDictionary is run on a file containing only the string "Bat,
cat, bat, cat!", it should return
{’Bat’: 1,’,’: 3,’cat’: 2,’bat’: 1,’!’: 1}(1)
Note that ’Bat’ and ’bat’ are distinct due to capitalization. Recall that you can test whether
a key is already in a dictionary using the ā€œinā€ operator, and you can increment an integer
1
pf2

Partial preview of the text

Download EECS12 Homework #3: Python Function Assignment and more Assignments Electrical and Electronics Engineering in PDF only on Docsity!

EECS12 Homework #3 Due: 11:59 PM, Friday, January 28, 2005

For this assignment you are to create and submit a single Python module named ā€œhw3.pyā€ containing definitions for the following functions (with precisely these spellings):

  1. IsPalindrome
  2. MakeDictionary
  3. CountWords

You will also need the function GetTokens from the previous assignment, which you must include in this file. (As always, you may also include any other functions that you deem necessary.) You may either use your own version of GetTokens, or the version that will be posted for you on the downloads page. If you use your own version, make sure it works correctly–you would not want to lose points twice for the same mistake! This assignment has two objectives: To familiarize you with reading and writing to files, and to give you some practice in writing programs that catch and handle errors. Here is what you need to do:

  1. Read chapters 9 and 11 of How to Think Like a Computer Scientist. Be sure to understand how to read from and write to files, and how to check for exceptions. You may also find chapter 6 of Dive into Python to be useful.
  2. Write a function called IsPalindrome that accepts a single argument, which must be a string (of any length). The function is to return True if the string is a palindrome and False otherwise. A palindrome is a word, or more generally any string of symbols, that is the same when spelled forwards and backwards. For example, the words ā€œradar,ā€ and the name of a once-popular programming language, ā€œAda,ā€ are both palindromes. Note that ā€œAdaā€ literally spelled back- wards is ā€œadA,ā€ which is not the same as the original, because of capitalization. You need to account for this. (Hint: See the function ā€œupcaseā€ in the Samples2.py file.) For example, IsPalindrome( "aabb12 @!!@ 21bbaa" ) and IsPalindrome( "Ada" ) should both return True, while IsPalindrome( "Mumble" ) and IsPalindrome( "Not quite! etiuq toN" ) should both return False. Your function should check that the argument that it is passed is a string; if not, the function should raise an exception (using the raise command) and return False.
  3. Write a function called MakeDictionary that accepts a single argument, which must be a string. (Raise an exception if the argument is not a string.) The function is to attempt to open a file of the name given in the string. If the open fails, print an error message (using print, not raise) and return None as the function value. You must use a try:-except: construct for this. If the file is successfully opened, read successive lines from the file and break each line into a sequence of tokens using GetTokens. Before using GetTokens you should chop off the ā€œnewlineā€ character readline returns at the end of each string using the ā€œ[:-1]ā€ construct; that is, if S is a string, then S[:-1] returns the entire string, minus the last character. Add each token (including ā€œpunctuationā€) to a dictionary in which you maintain a count of every token that is used. When the end of the file is reached, return the dictionary as the function value. The dictionary is to associate each word with an integer representing the number of times that word appeared in the file. For example if MakeDictionary is run on a file containing only the string "Bat, cat, bat, cat!", it should return

{’Bat’: 1, ’,’: 3, ’cat’: 2, ’bat’: 1, ’ !’: 1} (1)

Note that ’Bat’ and ’bat’ are distinct due to capitalization. Recall that you can test whether a key is already in a dictionary using the ā€œinā€ operator, and you can increment an integer

associated with a key using the ā€œ+=ā€ operator; e.g. d["cat"] += 1 increments the count associated with the word ā€œcatā€ if it is already present in the dictionary.

  1. Write a function called CountWords that accepts two arguments, both of which are to be strings. (Raise an exception if either argument is not a string.) First, create a dictionary of the words in the input file (specified by the first string) using MakeDictionary, then write elements of the dictionary to the output file (specified by the second string) such that the words are listed in alphabetical order, and each line looks like this: ā€œword: 5ā€ That is, each line should list the word, followed by a colon, followed by the word count. (Note: simply writing the dictionary to the file directly will not yield this format.) To sort the elements of the dictionary you may use the following approach: Create a list of tuples from the dictionary using the items() method of dictionary, then sort the resulting list using the sort() method of lists. You can write to the file by looping through the elements of the sorted list. Return True if everything worked correctly, and False otherwise. (Be sure to check that both files opened correctly!) After writing the entire dictionary to the output file, also write a list of palindromes to the same output file; that is, write a list of palindromes that were found in the input file, and are now present in the sorted list (but you needn’t write out the word counts for the palindromes).

Test cases that you can use to check your functions will be posted for you on the downloads page. Be sure to test your functions thoroughly. Also, remember to document your functions so they are intelligible to the grader.

You will need to understand how to use open, readline, close, .keys(), .items(), .sort(), try, except, raise, and the ā€œ%ā€ operator for formatting strings (among other things) to do this assignment. You may use GetTokens, IsAlphabetic, and upcase from the posted solutions and samples if you wish.