Python for Everybody
Chapter 8
Exercise 8.1
"""
Exercise 8.1: Write a function called chop that takes a list and modifies it,
removing the first and last elements, and returns None.
Then write a function called middle that takes a list and returns a new list
that contains all but the first and last e lements.
Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance
Solution by Jamison Lahman, May 31, 2017
"""
def chop(lst):
"""
Takes a list, modifies it, removing the first and last elements, and
returns None.
Input: lst -- a list
Output: None
"""
del lst[0] # Removes the first element
del lst[-1] # Removes the last element
def middle(lst):
"""
Takes a list and returns a new list that contains all but the first and
last elements.
Input: lst -- a list
Output: new -- new list with first and last elements removed
"""
new = lst[1:] # Stores all but the first element
del new[-1] # Deletes the last element
return new
my_list = [1, 2, 3, 4]
my_list2 = [1, 2, 3, 4]
chop_list = chop(my_list)
print(my_list) # Should be [2,3]
print(chop_list) # Should be None
middle_list = middle(my_list2)
print(my_list2) # Should be unchanged
print(middle_list) # Should be [2,3]
Exercise 8.2
"""
Exercise 8.2: Figure out which line of the above program is still not properly
guarded. See if you can construct a text file which causes the program to fail
and then modify the program so that the line is properly guarded and test it to
make sure it handles your new text file.
Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance
Solution by Jamison Lahman, May 31, 2017
"""
fhand = open('exercise8_2.txt')
for line in fhand:
words = line.split()
if len(words) < 3:
continue
if words[0] != 'From':
continue
print(words[2])
Exercise 8.3
"""
Exercise 8.3: Rewrite the guardian code in the above example without two if
statements. Instead, use a compound logical expression using the and logical
operator with a single if statement.
Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance
Solution by Jamison Lahman, May 31, 2017
"""
fhand = open('exercise8_2.txt')
for line in fhand:
words = line.split()
if len(words) < 3 or words[0] != 'From':
continue
print(words[2])
Exercise 8.4
"""
Exercise 8.4: Download a copy of the file from www.py4e.com/code3/romeo.txt
Write a program to open the file romeo.txt and read it line by line. For each
line, split the line into a list of words using the split function.
For each word, check to see if the word is already in a list. If the word is
not in the list, add it to the list.
When the program completes, sort and print the resulting words in alphabetical
order.
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east',
'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick',
'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']
Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance
Solution by Jamison Lahman, May 31, 2017
"""
my_list = []
fhand = open('romeo.txt')
for line in fhand:
words = line.split() # Splits line into array of words
for word in words:
if word in my_list:
continue # Discards duplicates
my_list.append(word) # Updates the list
print(sorted(my_list)) # Alphabetical order
Exercise 8.5
"""
Exercise 8.5: Write a program to read through the mail box data and when you
find the line that starts with "From", you will split the line into words
using the split function. We are interested in who sent the message, which is
second word on the From line.
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
You will parse the From line and print out the second word for each From line,
then you will also count the number of From (not From:) lines and print out a
count at the end.
This is a good sample output with a few lines removed:
python fromcount.py
Enter a file name: mbox-short.txt
stephen.marquard@uct.ac.za
louis@media.berkeley.edu
zqian@umich.edu
[... some output removed...]
ray@media.berkeley.edu
cwen@iupui.edu
cwen@iupui.edu
cwen@iupui.edu
There were 27 lines in the file with From as the first word
Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance
Solution by Jamison Lahman, May 31, 2017
"""
fhand = open('mbox-short.txt')
count = 0
for line in fhand:
words = line.split()
if len(words) < 3 or words[0] != 'From':
continue
print(words[1])
count += 1
print('There were %d lines in the file with From as the first word' % count)
Exercise 8.6
"""
Exercise 8.6: Rewrite the program that prompts the user for a list of numbers
and prints out the maximum and minimum of the numbers at the end when the user
enters "done". Write the program to store the numbers the user enters in a list
and use the max() and min() functions to compute the maximum and minimum
numbers after the loop completes.
Enter a number: 6
Enter a number: 2
Enter a number: 9
Enter a number: 3
Enter a number: 5
Enter a number: done
Maximum: 9.0
Minimum: 2.0
Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance
Solution by Jamison Lahman, May 31, 2017
"""
my_list = [] # Initialize array
while True:
number = 0.0
input_number = input('Enter a number: ')
if input_number == 'done':
break
try:
number = float(input_number)
except ValueError:
print('Invalid input')
quit()
my_list.append(input_number)
print('Maximum: ', max(my_list))
print('Minimum: ', min(my_list))