Computer Science 121: Introduction to Problem Solving with Computers | UMass麻省大学阿默斯特分校 | weekly exercise代写 | python代写

Week 6 Exercise 1
Dictionaries
Objectives
Playing around with Python dictionaries (so that in Exercise 2 we can incorporate dictionaries
into classes).
Preliminary Setup
Within your COMSC-121 directory, create a Week6 subdirectory. Within Week6, make an
Exercise1 directory.
Download translation.py from Moodle and save it in your Exercise1 directory. No need to
look at it yet. You’ll need it later.
Review
You may have already seen dictionaries, but a little review never hurts. When considering different
ways of storing data, we’ve seen
a simple variable that can hold a single value
a string which is an immutable collection of characters (“immutable” means that we cannot
change data within a string)
a list which is a mutable possibly heterogeneous collection of data (the data does not all have
to be the same type, and it can be changed).
Recall that we can iterate over strings and we can iterate over lists. In fact, we have two ways to do
the iteration. We can iterate by index value, or we can iterate by string character or by list element.
For example, these two for loops will generate the same output.
myString = “Lab 10”
for C in myString:
print(C)
for i in range(len(myString)):
print(myString[i])
And these two for loops will also generate the same output:
myList = [“Lab 1”, “Lab 2”, “Lab 3”]
for element in myList:
print(element)
for i in range(len(myList)):
print(myList[i])
The data stored in strings and in lists is ordered and we can reference each element by its position.
Now we can look at another way of storing data, the dictionary.
Dictionaries
The Python dictionary is another mechanism for grouping, storing, and retrieving data. Dictionaries
differ from strings and lists in several important ways:
the data items are not stored in any particular order. In fact, officially a Python dictionary is an
unordered mutable collection of key/value pairs.
data cannot be accessed through indices. In fact, we have no concept of an index in a
dictionary.
data is accessed via keys
each key can appear at most once in the dictionary. We cannot change a key, but we can
change the value associated with the key. We also can add and remove keys.
different keys can have the same value associated with them
A first dictionary
Consider the problem of birdwatching and trying to keep track of how many birds of each species
you saw. If we had only one or two species of birds then we could simply have a counter for each
species. If we have multiple species then it would be helpful to have a way to keep track that
directly associates the count with the species, and a dictionary will let us do this. Here’s an
example:
birds = {‘canada goose’:3, ‘robin’:4, ‘cardinal’:2, ‘mallard duck’:3, ‘sparrow’:25}
Syntax: a string is marked by quotation marks, a list is marked by [ ], and a dictionary is marked by
{ }. Each key-value pair in the dictionary takes the form
key : value
In my example, the key is a string, the associated value is an integer. That is, ‘canada goose’ is a
key, and 3 is the associated value. If I created this dictionary in Python, then I could retrieve the
value by asking for birds[‘canada goose’]. In the same way that “” is an empty string, and [ ]
is an empty list, {} is an empty dictionary.
Updating a dictionary (new items, changes to items)
Let’s build the above dictionary one item at a time. I can start with an empty dictionary
birds = {}
and then add the first key, value pair:
birds[‘canada goose’] = 3
and add the next pair
birds[‘robin’] = 4
and the next pair
birds[‘cardinal’] = 2
In fact, I can change the value associated with a key in the same way. Let’s say that all of the
sudden another robin flies by. I can update the value in the dictionary that is associated with the key
‘robin’
birds[‘robin’] = 5
or I could increment like this
birds[‘robin’] = birds[‘robin’] + 1
What if I want to get rid of a dictionary entry completely?
del birds[‘mallard duck’]
will completely remove the specified key and its associated value. How can we test to see if a key is
in the dictionary? You can probably guess that the in operator will work for that.
if ‘robin’ in birds:
print(‘the robins are here’)
Be careful!!!! You cannot use in to see if a particular value is in the dictionary, only to see if a
particular key is in the dictionary. Note that the len function also works for dictionaries, returning
the length of the dictionary (which is the number of key-value pairs).
len(birds)
Let’s say that we want to do something for every key-value pair in a dictionary. A simple task
would be to print out each key and its associated value. We can easily iterate over the keys, much in
the same way that we iterate over characters in a string or elements in a list:
for x in birds:
print(x, birds[x])
Some dictionary methods
There are some very useful dictionary methods in Python. Try out the following examples:
scientists = {‘Newton’:1642, ‘Darwin’:1809, ‘Turing’:1912}
print(‘keys example:’, scientists.keys()) # .keys() returns a list of the keys
print(‘values example: ‘, scientists.values()) # .values() returns a list of values
print(‘items example: ‘, scientists.items()) # .items() returns a list of items
print(‘get: ‘, scientists.get(‘Curie’, 1867))
The last method is an interesting one. What get does is look up the key provided. If it finds the key,
it returns the associated value. If it doesn’t find the key, it returns the default value. This is very
useful as we’ll see in a moment. But first, here’s another example of using a for loop, but this time
we’ll iterate over the list generated by the keys( ) method.
for name in scientists.keys():
print(name, ” was born in “, scientists[name])
Now what if we want to update our dictionary, maybe get some women scientists into it? We can do
that by building a second dictionary and using that to update the original. Run these three
statements (assuming you’ve already run the above statements to create the dictionary).
temp = {‘Curie’ : 1867, ‘Hopper’:1906, ‘Franklin’:1920}
scientists.update(temp)
print(‘after update: ‘, scientists)
Some uses of dictionaries
We can use dictionaries to simplify a number of tasks. For example:
find duplicates in a list — as you traverse the list, put an element into the dictionary if it isn’t
already there. When you are done, the dictionary will contain each unique element of the list
count occurrences of data elements in a list or file — Check the dictionary for an item — if it’s
there, increase its count by one; if it’s not there, put it in with a count of 1. We can do this
relatively easily by using the get method with a default value:
name = input(“Please give name of bird you saw”)
while userInput != ‘quit’:
count[name] = count.get(name, 0) + 1
name = input(“Please give name of bird you saw”)
Here we use get to get the old value if there is one, increment it by 1, and save it as the new
value. If the name isn’t in the dictionary already, then the default value returned by get is 0, as
specified in the second argument to the get, and we add 1 to that in order to show that 1 bird
of that type was seen.
Step 1:
After reviewing the above, including running the examples, you are ready to dive into this week’s
work.
Prepare a text file containing English words and their translation into another language. Each pair
should be on a separate line, with a colon between the words. Choose enough words that you can
use them to form a few sentences. For example, a file translating English words to German words
could be as follows:
the:der
dog:hund
barks:bellt
cat:katze
is:ist
sleeping:schlafend
growls:knurrt
at:an
If you don’t know a language other than English, use the German words or use Google translate to
translate a few words into another language. Don’t spend more than 5 minutes building this file. To
create the file, use Atom to create a new file with the translation text and save the file as a .txt file
(translation.txt for example). Put this file in your Week6/Exercise1 directory.
Step 2
In the Exercise1 directory, open up the translation.py file that you downloaded. You will see
that it has a number of function definitions that have pass in place of the function body. There is
also a main function.
Write the body of the buildDict function. Its job is to read in a word file (file name is passed to the
function) and create a dictionary that maps English words to the corresponding words in the other
language. That is, each dictionary entry will have an English word as its key, and the translation of
that word as the associated value. When done, this function should return the dictionary. For
example, in main( ):
translationDict = buildDict (“eng-ger.txt”)
print(translationDict)
would output
{‘growls’: ‘knurrt’, ‘is’: ‘ist’, ‘barks’: ‘bellt’, ‘dog’: ‘hund’, ‘sleeping’: ‘schlafend’, ‘at’: ‘an’, ‘the’: ‘der’, ‘cat’: ‘katze’}
As a reminder of how to open and read from a file, here are the key steps:
# first open the file in read mode
myDataFile = open(filename, ‘r’)
# read it one line at a time, using a for loop
for line in myDataFile:
dataChunk = line.strip() # remove blanks from end of the line
# now I can do something with the dataChunk, like build
# a dictionary. Remember that you can use the string split method to
# break up a string, or you can use the find method to locate
# the :
# all done reading the file, so close it
myDataFile.close()
Step 3
Next write the body of the printDict function so that it prints a nice display of the dictionary. For
example:
translationDict = buildDict(“eng-ger.txt”)
printDict(translation_dict)
would generate this output:
growls………knurrt
is………….ist
barks……….bellt
dog…………hund
sleeping…….schlafend
at………….an
the…………der
cat…………katze
Step 4
Write the body of the translate function. It has as parameters an English sentence (represented as a
string) and a dictionary, and returns a string containing a word-by-word translation of the sentence
into the other language. For example:
translate(“the dog barks”, translation_dict)
generates the result
der hund bellt
The command
translate(“the cat is sleeping”, translation_dict)
will return
der katze ist schlafend
and the command
translate(“the dog growls at the cat”, translation_dict)
will return
der hund knurrt an der katze
We know the translation won’t be perfect, but it’s a starting point……
Turning in this Exercise:
By now the provided main() function should generate the correct results. After any final debugging,
check that your code is understandable and readable. Consider the neatness, presentation,
documentation, and style of your program code.
Finally, make a zip file of all the files in your Exercise1 directory, and submit that on Moodle.
Ask for help if you’re having problems!