Exercises#
Q 1#
When talking about floating point, we discussed machine epsilon, \(\epsilon\)—this is the smallest number that when added to 1 is still different from 1.
We’ll compute \(\epsilon\) here:
Pick an initial guess for \(\epsilon\) of
eps = 1
.Create a loop that checks whether
1 + eps
is different from1
Each loop iteration, cut the value of
eps
in half
What value of \(\epsilon\) do you find?
Q 2#
To iterate over the tuples, where the i-th tuple contains the i-th elements of certain sequences, we can use zip(*sequences)
function.
We will iterate over two lists, names
and age
, and print out the resulting tuples.
Start by initializing lists
names = ["Mary", "John", "Sarah"]
andage = [21, 56, 98]
.Iterate over the tuples containing a name and an age, the
zip(list1, list2)
function might be useful here.Print out formatted strings of the type “NAME is AGE years old”.
Q 3#
The function enumerate(sequence)
returns tuples containing indices of objects in the sequence, and the objects.
The random
module provides tools for working with the random numbers. In particular, random.randint(start, end)
generates a random number not smaller than start
, and not bigger than end
.
Generate a list of 10 random numbers from 0 to 9.
Using the
enumerate(random_list)
function, iterate over the tuples of random numbers and their indices, and print out “Match: NUMBER and INDEX” if the random number and its index in the list match.
import random
random_number = random.randint(0,9)
print(random_number)
9
Q 4#
The Fibbonacci sequence is a numerical sequence where each number is the sum of the 2 preceding numbers, e.g., 1, 1, 2, 3, 5, 8, 13, …
Create a list where the elements are the terms in the Fibbonacci sequence:
Start with the list
fib = [1, 1]
Loop 25 times, compute the next term as the sum of the previous 2 terms and append to the list
After the loop is complete, print out the terms
You may find it useful to use fib[-1]
and fib[-2]
to access the last to items in the list
Q 5#
We can use the input()
function to ask for input from the prompt (note: in python 2 the function was called raw_input()
).
Create an empty list and use a while loop to ask the user for input and append their input to the list. Keep looping until 10 items are added to the list
Q 6#
Here is a list of book titles (from http://thegreatestbooks.org). Loop through the list and capitalize each word in each title. You might find the .capitalize()
method that works on strings useful.
titles = ["don quixote",
"in search of lost time",
"ulysses",
"the odyssey",
"war and piece",
"moby dick",
"the divine comedy",
"hamlet",
"the adventures of huckleberry finn",
"the great gatsby"]
Q 7#
Here’s some text (the Gettysburg Address). Our goal is to count how many times each word repeats. We’ll do a brute force method first, and then we’ll look a ways to do it more efficiently (and compactly).
gettysburg_address = """
Four score and seven years ago our fathers brought forth on this continent,
a new nation, conceived in Liberty, and dedicated to the proposition that
all men are created equal.
Now we are engaged in a great civil war, testing whether that nation, or
any nation so conceived and so dedicated, can long endure. We are met on
a great battle-field of that war. We have come to dedicate a portion of
that field, as a final resting place for those who here gave their lives
that that nation might live. It is altogether fitting and proper that we
should do this.
But, in a larger sense, we can not dedicate -- we can not consecrate -- we
can not hallow -- this ground. The brave men, living and dead, who struggled
here, have consecrated it, far above our poor power to add or detract. The
world will little note, nor long remember what we say here, but it can never
forget what they did here. It is for us the living, rather, to be dedicated
here to the unfinished work which they who fought here have thus far so nobly
advanced. It is rather for us to be here dedicated to the great task remaining
before us -- that from these honored dead we take increased devotion to that
cause for which they gave the last full measure of devotion -- that we here
highly resolve that these dead shall not have died in vain -- that this
nation, under God, shall have a new birth of freedom -- and that government
of the people, by the people, for the people, shall not perish from the earth.
"""
We’ve already seen the .split()
method will, by default, split by spaces, so it will split this into words, producing a list:
ga = gettysburg_address.split()
ga
['Four',
'score',
'and',
'seven',
'years',
'ago',
'our',
'fathers',
'brought',
'forth',
'on',
'this',
'continent,',
'a',
'new',
'nation,',
'conceived',
'in',
'Liberty,',
'and',
'dedicated',
'to',
'the',
'proposition',
'that',
'all',
'men',
'are',
'created',
'equal.',
'Now',
'we',
'are',
'engaged',
'in',
'a',
'great',
'civil',
'war,',
'testing',
'whether',
'that',
'nation,',
'or',
'any',
'nation',
'so',
'conceived',
'and',
'so',
'dedicated,',
'can',
'long',
'endure.',
'We',
'are',
'met',
'on',
'a',
'great',
'battle-field',
'of',
'that',
'war.',
'We',
'have',
'come',
'to',
'dedicate',
'a',
'portion',
'of',
'that',
'field,',
'as',
'a',
'final',
'resting',
'place',
'for',
'those',
'who',
'here',
'gave',
'their',
'lives',
'that',
'that',
'nation',
'might',
'live.',
'It',
'is',
'altogether',
'fitting',
'and',
'proper',
'that',
'we',
'should',
'do',
'this.',
'But,',
'in',
'a',
'larger',
'sense,',
'we',
'can',
'not',
'dedicate',
'--',
'we',
'can',
'not',
'consecrate',
'--',
'we',
'can',
'not',
'hallow',
'--',
'this',
'ground.',
'The',
'brave',
'men,',
'living',
'and',
'dead,',
'who',
'struggled',
'here,',
'have',
'consecrated',
'it,',
'far',
'above',
'our',
'poor',
'power',
'to',
'add',
'or',
'detract.',
'The',
'world',
'will',
'little',
'note,',
'nor',
'long',
'remember',
'what',
'we',
'say',
'here,',
'but',
'it',
'can',
'never',
'forget',
'what',
'they',
'did',
'here.',
'It',
'is',
'for',
'us',
'the',
'living,',
'rather,',
'to',
'be',
'dedicated',
'here',
'to',
'the',
'unfinished',
'work',
'which',
'they',
'who',
'fought',
'here',
'have',
'thus',
'far',
'so',
'nobly',
'advanced.',
'It',
'is',
'rather',
'for',
'us',
'to',
'be',
'here',
'dedicated',
'to',
'the',
'great',
'task',
'remaining',
'before',
'us',
'--',
'that',
'from',
'these',
'honored',
'dead',
'we',
'take',
'increased',
'devotion',
'to',
'that',
'cause',
'for',
'which',
'they',
'gave',
'the',
'last',
'full',
'measure',
'of',
'devotion',
'--',
'that',
'we',
'here',
'highly',
'resolve',
'that',
'these',
'dead',
'shall',
'not',
'have',
'died',
'in',
'vain',
'--',
'that',
'this',
'nation,',
'under',
'God,',
'shall',
'have',
'a',
'new',
'birth',
'of',
'freedom',
'--',
'and',
'that',
'government',
'of',
'the',
'people,',
'by',
'the',
'people,',
'for',
'the',
'people,',
'shall',
'not',
'perish',
'from',
'the',
'earth.']
Now, the next problem is that some of these still have punctuation. In particular, we see “.
”, “,
”, and “--
“.
When considering a word, we can get rid of these by using the replace()
method:
a = "end.,"
b = a.replace(".", "").replace(",", "")
b
'end'
Another problem is case—we want to count “but” and “But” as the same. Strings have a lower()
method that can be used to convert a string:
a = "But"
b = "but"
a == b
False
a.lower() == b.lower()
True
Recall that strings are immutable, so replace()
produces a new string on output.
your task#
Create a dictionary that uses the unique words as keys and has as a value the number of times that word appears.
Write a loop over the words in the string (using our split version) and do the following:
remove any punctuation
convert to lowercase
test if the word is already a key in the dictionary (using the
in
operator)if the key exists, increment the word count for that key
otherwise, add it to the dictionary with the appropriate count of
1
.
At the end, print out the words and a count of how many times they appear
# your code here
More compact way#
We can actually do this a lot more compactly by using another list comprehensions and another python datatype called a set. A set is a group of items, where each item is unique (e.g., no repetitions).
Here’s a list comprehension that removes all the punctuation and converts to lower case:
words = [q.lower().replace(".", "").replace(",", "") for q in ga]
and by using the set()
function, we turn the list into a set, removing any duplicates:
unique_words = set(words)
now we can loop over the unique words and use the count
method of a list to find how many there are
count = {}
for uw in unique_words:
count[uw] = words.count(uw)
count
{'dedicated': 4,
'before': 1,
'which': 2,
'thus': 1,
'a': 7,
'or': 2,
'equal': 1,
'can': 5,
'whether': 1,
'field': 1,
'shall': 3,
'honored': 1,
'remember': 1,
'unfinished': 1,
'these': 2,
'larger': 1,
'live': 1,
'should': 1,
'four': 1,
'government': 1,
'hallow': 1,
'so': 3,
'consecrated': 1,
'--': 7,
'final': 1,
'men': 2,
'but': 2,
'years': 1,
'from': 2,
'far': 2,
'they': 3,
'consecrate': 1,
'ground': 1,
'great': 3,
'power': 1,
'us': 3,
'perish': 1,
'forth': 1,
'who': 3,
'their': 1,
'cause': 1,
'on': 2,
'might': 1,
'portion': 1,
'died': 1,
'earth': 1,
'sense': 1,
'for': 5,
'above': 1,
'god': 1,
'endure': 1,
'remaining': 1,
'add': 1,
'poor': 1,
'last': 1,
'vain': 1,
'resting': 1,
'met': 1,
'it': 5,
'forget': 1,
'and': 6,
'highly': 1,
'that': 13,
'lives': 1,
'war': 2,
'be': 2,
'in': 4,
'fitting': 1,
'seven': 1,
'birth': 1,
'conceived': 2,
'brought': 1,
'to': 8,
'dedicate': 2,
'task': 1,
'note': 1,
'nobly': 1,
'take': 1,
'work': 1,
'world': 1,
'ago': 1,
'as': 1,
'freedom': 1,
'continent': 1,
'engaged': 1,
'detract': 1,
'proposition': 1,
'those': 1,
'fought': 1,
'score': 1,
'under': 1,
'testing': 1,
'say': 1,
'nation': 5,
'living': 2,
'what': 2,
'liberty': 1,
'battle-field': 1,
'never': 1,
'little': 1,
'people': 3,
'long': 2,
'is': 3,
'full': 1,
'now': 1,
'nor': 1,
'new': 2,
'any': 1,
'gave': 2,
'altogether': 1,
'civil': 1,
'advanced': 1,
'resolve': 1,
'did': 1,
'our': 2,
'are': 3,
'the': 11,
'here': 8,
'measure': 1,
'struggled': 1,
'fathers': 1,
'by': 1,
'not': 5,
'do': 1,
'this': 4,
'all': 1,
'of': 5,
'brave': 1,
'have': 5,
'rather': 2,
'created': 1,
'come': 1,
'we': 10,
'devotion': 2,
'proper': 1,
'dead': 3,
'will': 1,
'increased': 1,
'place': 1}
Even shorter – we can use a dictionary comprehension, like a list comprehension
c = {uw: count[uw] for uw in unique_words}
c
{'dedicated': 4,
'before': 1,
'which': 2,
'thus': 1,
'a': 7,
'or': 2,
'equal': 1,
'can': 5,
'whether': 1,
'field': 1,
'shall': 3,
'honored': 1,
'remember': 1,
'unfinished': 1,
'these': 2,
'larger': 1,
'live': 1,
'should': 1,
'four': 1,
'government': 1,
'hallow': 1,
'so': 3,
'consecrated': 1,
'--': 7,
'final': 1,
'men': 2,
'but': 2,
'years': 1,
'from': 2,
'far': 2,
'they': 3,
'consecrate': 1,
'ground': 1,
'great': 3,
'power': 1,
'us': 3,
'perish': 1,
'forth': 1,
'who': 3,
'their': 1,
'cause': 1,
'on': 2,
'might': 1,
'portion': 1,
'died': 1,
'earth': 1,
'sense': 1,
'for': 5,
'above': 1,
'god': 1,
'endure': 1,
'remaining': 1,
'add': 1,
'poor': 1,
'last': 1,
'vain': 1,
'resting': 1,
'met': 1,
'it': 5,
'forget': 1,
'and': 6,
'highly': 1,
'that': 13,
'lives': 1,
'war': 2,
'be': 2,
'in': 4,
'fitting': 1,
'seven': 1,
'birth': 1,
'conceived': 2,
'brought': 1,
'to': 8,
'dedicate': 2,
'task': 1,
'note': 1,
'nobly': 1,
'take': 1,
'work': 1,
'world': 1,
'ago': 1,
'as': 1,
'freedom': 1,
'continent': 1,
'engaged': 1,
'detract': 1,
'proposition': 1,
'those': 1,
'fought': 1,
'score': 1,
'under': 1,
'testing': 1,
'say': 1,
'nation': 5,
'living': 2,
'what': 2,
'liberty': 1,
'battle-field': 1,
'never': 1,
'little': 1,
'people': 3,
'long': 2,
'is': 3,
'full': 1,
'now': 1,
'nor': 1,
'new': 2,
'any': 1,
'gave': 2,
'altogether': 1,
'civil': 1,
'advanced': 1,
'resolve': 1,
'did': 1,
'our': 2,
'are': 3,
'the': 11,
'here': 8,
'measure': 1,
'struggled': 1,
'fathers': 1,
'by': 1,
'not': 5,
'do': 1,
'this': 4,
'all': 1,
'of': 5,
'brave': 1,
'have': 5,
'rather': 2,
'created': 1,
'come': 1,
'we': 10,
'devotion': 2,
'proper': 1,
'dead': 3,
'will': 1,
'increased': 1,
'place': 1}