Introduction to Python
davidbpython.com
In-Class Exercise Solutions, Session 5
|
PLEASE REFER to pythonreference.com for syntax to follow in coding these Exercises |
|
|
NOTE THAT the data files read from these exercises is located in the "parent" directory. Thus any filename in these exercises should be preceded with ../. (If you create a script in the same directory as the data file, this would not be necessary.) |
|
|
LISTS |
|
| Ex. 5.1 | List slicing and subscripting operations. |
|
Initialize a list of 5 strings. Then perform the below operations. |
|
# initialize your list of 5 strings
mylist = ['hello', 'there', 'fine', 'Python', 'friends'] # list
# access and print the 2nd item (use list subscript)
itemsecond = mylist[1] # str, 'there'
print(itemsecond)
# access and print the last item (use negative subscript)
itemlast = mylist[-1] # str, 'friends'
print(itemlast)
# slice and print the first 3 items from the list (use list slice)
first3 = mylist[0:3] # list, ['hello', 'there', 'fine']
print(first3)
# slice and print the last 3 items from the list (leave off the 'upper bound')
last3 = mylist[-3:] # list, ['fine', 'Python', 'friends']
print(last3)
# look for the value 'Python' within the list
if 'Python' in mylist:
print('found!')
|
|
| Ex. 5.2 | List with summary functions. |
x = [3.3, 1.1, 4.4, 2.2] # list, [3.3, 1.1, 4.4, 2.2]
# in one statement, show count of items in a list (use len())
count = len(x) # int, 4
print(count)
# sum up values in the list without looping (use sum())
itemsum = sum(x) # float, 10.1
print(itemsum)
# show maximum value in the list (use max())
maxval = max(x) # float, 4.4
print(maxval)
# show minimum value in the list (use min())
minval = min(x) # float, 1.1
print(minval)
# show list items sorted lowest to highest (use sorted())
slist = sorted(x) # list, [1.1, 2.2, 3.3, 4.4]
print(slist)
# show list items sorted highest to lowest (add reverse=True)
srevlist = sorted(x, reverse=True) # list, [4.4, 3.3., 2.2, 1.1]
print(srevlist)
print()
|
|
| Ex. 5.3 | Show the first 3 values in this list. |
x = [8, 1, 0, 2, 23, 4, 5, 11] # list, [8, 1, 0, 2, 23, 4, 5, 11 ]
first3 = x[0:3] # list, [8, 1, 0]
print(first3)
|
|
| Ex. 5.4 | Show the last 3 values in this list. Use a negative slice. |
x = [8, 1, 0, 2, 23, 4, 5, 11] # list, [8, 1, 0, 2, 23, 4, 5, 11 ]
last3 = x[-3:] # list, [4, 5, 11]
print(last3)
|
|
| Ex. 5.5 | Show the average of the values in this list. |
x = [8, 1, 0, 2, 23, 4, 5, 11] # list, [8, 1, 0, 2, 23, 4, 5, 11]
avg = sum(x) / len(x) # float, 6.75
print(avg)
|
|
| Ex. 5.6 | In two simple statements (not using subscripting or sorted()), find the highest value and lowest value in this list. Print each value. |
x = [8, 1, 0, 2, 23, 4, 5, 11] # list, [8, 1, 0, 2, 23, 4, 5, 11]
maxval = max(x) # int, 23
minval = min(x) # int, 0
print(maxval)
print(minval)
|
|
| Ex. 5.7 | Show the top 3 values in this list, sorted high-to-low. |
x = [8, 1, 0, 2, 23, 4, 5, 11] # list, [8, 1, 0, 2, 23, 4, 5, 11]
xs = sorted(x, reverse=True) # list, [11, 5, 4, 23, 2, 0, 1, 8]
print(xs[0:3])
|
|
| Ex. 5.8 | Show the bottom 3 values in this list, sorted low-to-high. |
x = [8, 1, 0, 2, 23, 4, 5, 11] # list, [8, 1, 0, 2, 23, 4, 5, 11]
sx = sorted(x) # list, [0, 1, 2, 4, 5, 8, 11, 23]
print(sx[0:3]) # [0, 1, 2]
|
|
| Ex. 5.9 | Show the 3rd highest value in this list. |
x = [8, 1, 0, 2, 23, 4, 5, 11] # list, [8, 1, 0, 2, 23, 4, 5, 11]
sx = sorted(x) # list, [0, 1, 2, 4, 5, 8, 11, 23]
print(sx[-3]) # [8, 11, 23]
# alternative
sx = sorted(x, reverse=True) # list, [23, 11, 8, 5, 4, 2, 1, 0]
print(sx[2]) # int, 8
|
|
| Ex. 5.10 | Show the average of the top 50% of values in this list. |
x = [8, 1, 0, 2, 23, 4, 5, 11] # list, [8, 1, 0, 2, 23, 4, 5, 11]
sx = sorted(x, reverse=True) # list, [23, 11, 8, 5, 4, 2, 1, 0]
lensx = len(sx) # int, 8
mid_idx = int(lensx/2) # int, 4
firsthalf = sx[0:mid_idx] # list, [23, 11, 8, 5]
print(sum(firsthalf) / len(firsthalf)) # float, 11.75
|
|
| Ex. 5.11 | Build a list with .append. |
|
Initialize a list. Then in two statements, append two float values 5.5 and 5.6 to your list, then print the entire list to show that the two items have been added. |
|
x = [] # list, []
x.append(5.5) # list, [5.5]
x.append(6.6) # list, [5.5, 6.6]
print(x)
|
|
|
TUPLES - LIKE A LIST, BUT READ-ONLY |
|
| Ex. 5.12 | Compare a tuple to a list. |
|
Given the below code which shows several operations that are possible with a list, change the list to a tuple (replace the square brackets with parentheses in the first line) and re-run the code to see what operations may be possible with a tuple. (Note: spaces inside {} are included for clarity.) |
|
myseq = (3, 1, 5, 9, 7, 11) # tuple, (3, 1, 5, 9, 7, 11)
print(f'the sequence: { myseq }') # tuple, (3, 1, 5, 9, 7, 11)
print(f'last item: { myseq[-1] }') # int, 11
print(f'first 3 items: { myseq[0:3] }') # tuple, (3, 1, 5)
print(f'last 3 items: { myseq[-3:] }') # tuplee, (9, 7, 11)
print(f'# of items: { len(myseq) }') # int, 6
print(f'maximum value: { max(myseq) }') # int, 11
print(f'minimum value: { min(myseq) }') # int, 1
print('each item in sequence:')
for item in myseq: # int, 3 (initial value)
print(item)
print()
print(f'sorted: { sorted(myseq) }') # list, [1, 3, 5, 7, 9, 11]
print('appending to sequence: ')
myseq.append(99) # AttributeError: 'tuple' object has no attribute 'append'
print(myseq)
|
|
|
SETS - BUILDING AND READING |
|
| Ex. 5.13 | Compare a set to a list. |
|
Given the below code which shows several operations that are possible with a list, change the list to a set (replace the square brackets with curly braces in the first line) and re-run the code to see what operations may be possible with a tuple. (Note: spaces inside {} are included for clarity.) |
|
myseq = {3, 1, 5, 9, 7, 11} # set, {3, 1, 5, 9, 7, 11}
print(f'the sequence: { myseq }') # set, {3, 1, 5, 9, 7, 11}
print(f'last item: { myseq[-1] }') # TypeError: 'set' object is not subscriptable
print(f'first 3 items: { myseq[0:3] }') # TypeError: 'set' object is not subscriptable
print(f'last 3 items: { myseq[-3:] }') # TypeError: 'set' object is not subscriptable
print(f'# of items: { len(myseq) }') # int, 6
print(f'maximum value: { max(myseq) }') # int, 11
print(f'minimum value: { min(myseq) }') # int, 1
print('each item in sequence:')
for item in myseq: # int, 5 (sample value)
print(item)
print()
print(f'sorted: { sorted(myseq) }') # list, [1, 3, 5, 7, 9, 11]
print('appending to sequence: ')
myseq.append(99) # AttributeError: 'set' object has no attribute 'append'
|
|
|
LISTS - BUILDING FROM FILE |
|
| Ex. 5.14 | Review: loop through a list. |
x = [3.3, 1.1, 4.4, 2.2] # list, [3.3, 1.1, 4.4, 2.2]
for item in x: # float, 3.3 (initial value)
print(item)
|
|
| Ex. 5.15 | Build a list of items from a CSV file. |
|
Begin by reviewing and running the below code. Taking a look at file revenue.csv, build up a list of the float values in that file. |
|
fh = open('revenue.csv') # 'file' object
fvals = [] # list, []
for line in fh: # str, "Haddad's,PA,239.50\n"
line = line.rstrip() # str, "Haddad's,PA,239.50"
items = line.split(',') # list, ["Haddad's", 'PA', '239.50\n']
val = items[-1] # str, '239.50\n'
fval = float(val) # float, 239.5
fvals.append(fval) # list, [239.5]
fh.close()
print(fvals)
|
|
|
LAB 2 |
|
| Ex. 5.16 | Review: loop through a file. |
|
Open the below file, then use the next() function with the file object to skip the first line of the file. Strip and print each line. |
|
filename = 'student_db.txt' # str, 'student_db.txt'
# open file
fh = open(filename) # 'file' object
# skip the first line of the file (use next())
next(fh) # str, 'id:address:city:state:zip\n'
# loop through file line-by-line
for line in fh: # str, 'jk43:23 Marfield Lane:Plainview:NY:10024\n'
# strip each line
line = line.rstrip() # str, 'jk43:23 Marfield Lane:Plainview:NY:10024'
# print each line
print(line)
|
|
| Ex. 5.17 | Review: loop through a file and split out values. |
|
Continuing the previous exercise, split each line and print the list split from each line. |
|
filename = 'student_db.txt' # str, 'student_db.txt'
fh = open(filename) # 'file' object
# skip the first line of the file (use next())
next(fh) # str, 'id:address:city:state:zip\n'
for line in fh: # str, 'jk43:23 Marfield Lane:Plainview:NY:10024\n'
line = line.rstrip() # str, 'jk43:23 Marfield Lane:Plainview:NY:10024'
items = line.split(':') # list, ['jk43', '23 Marfield Lane', ...]
print(items)
|
|
| Ex. 5.18 | Build a list of student ids (first field) from student_db.txt. |
|
(See below how to skip header.) |
|
filename = 'student_db.txt' # str, 'student_db.txt'
fh = open(filenamne) # 'file' object
# skip header to first data row
next(fh) # str, 'id:address:city:state:zip\n'
stuids = [] # list, []
for line in fh: # str, 'jk43:23 Marfield Lane:Plainview:NY:10024\n'
line = line.rstrip() # str, 'jk43:23 Marfield Lane:Plainview:NY:10024'
items = line.split(':') # list, ['jk43', '23 Marfield Lane', ...]
stuids.append(items[0]) # list, ['jk43']
print(stuids)
|
|
|
Note: don't forget that student_db.txt is colon-separated. |
|
| Ex. 5.19 | Show the average value from a list of the float values in file revenue.csv. |
fh = open('revenue.csv') # 'file' object
stuids = [] # list, []
for line in fh: # str, "Haddad's,PA,239.50\n"
items = line.split(',') # list, ["Haddad's", 'PA', '239.50\n']
fval = float(items[-1]) # float, 239.5
stuids.append(fval) # list, [239.5]
print(sum(stuids) / len(stuids))
|
|
| Ex. 5.20 | Show the top 3 values from the last column in dated_file.csv. |
fh = open('dated_file.csv') # 'file' object
values = [] # list, []
for line in fh: # str, '10/15/2018,A,B,28.3\n'
items = line.split(',') # list, ['10/15/2018', 'A', 'B' ...]
lval = float(items[-1]) # float, 28.3
values.append(lval) # list, [28.3]
svals = sorted(values, reverse=True) # list, [28.3, 23.85, 19.09, 18.2, ...]
print(svals[0:3]) # list, [28.3, 23.85, 19.09]
|
|
| Ex. 5.21 | Show the average of the top 25% of values in dated_file.csv. |
fh = open('dated_file.csv') # 'file' object
values = [] # list, []
for line in fh: # str, '10/15/2018,A,B,28.3'
items = line.split(',') # list, ['10/15/2018', 'A', 'B', '28.3']
lval = float(items[-1]) # float, 28.3
values.append(lval) # list, [28.3]
svals = sorted(values, reverse=True) # list, [28.3, 23.85, 19.09, 18.2, ...]
lensvals = len(svals) # int, 8
mid_idx = int(lensvals / 4) # int, 2
firstquarter = svals[0:mid_idx] # list, [28.3, 23.85]
print(sum(firstquarter) / len(firstquarter))
|
|
|
SETS - BUILDING FROM FILE |
|
| Ex. 5.22 | Initialize a set. |
|
Initialize a new set of 7-10 string and number values (make sure to include both). Use .add() to add one new, and one repeat value to the set. Print the set to see its contents. |
|
myset = {'a', 55, '100', 100, 'hello', 'ABC', 99.03, 3, 7, 0.0003} # set (any order, no duplicates)
myset.add('a') # set (any order, no duplicates)
myset.add('b') # set (any order, no duplicates)
print(myset)
|
|
|
After executing, execute several more times, making note if the output changes. |
|
| Ex. 5.23 | Build a set of items from a CSV file. |
|
Loop through the file revenue.csv and create a set of states drawn from the 2nd column of the file. (Note that your set order may be different.) |
|
fh = open('revenue.csv') # 'file' object
# the only way to initialize an empty set
states = set() # set (empty)
for line in fh: # str, "Haddad's,PA,239.50\n"
items = line.split(',') # list, ["Haddad's", 'PA', '239.50\n']
val = items[1] # str, 'PA'
states.add(val) # set, {'PA'}
fh.close()
print(states)
|
|
|
LAB 3 |
|
| Ex. 5.24 | Show a set of unique cities in student_db.txt. |
|
You can begin by running the below code, which opens the file, advances one line, then loops through each line and splits the line. |
|
filename = 'student_db.txt' # str, 'student_db.txt'
fh = open(filename) # 'file' object
next(fh) # # str, 'id:address:city:state:zip\n'
states = set() # set
for line in fh: # str, 'jk43:23 Marfield Lane:Plainview:NY:10024\n'
items = line.split(':') # list, ['jk43', '23 Marfield Lane', ...]
val = items[2] # str, 'NY'
states.add(val) # set, {'NY'}
print(states)
|
|
|
Note: don't forget that student_db.txt is colon-separated, and that you must use next(fh) (where fh is the file object) to skip the header row of this file. |
|
| Ex. 5.25 | Print only those lines of revenue.csv where the state can be found in the set of wanted states. |
wanted = {'NJ', 'PA'} # set, {'NJ', 'PA'}
fh = open('revenue.csv') # 'file' object
for line in fh: # str, "Haddad's,PA,239.50\n"
line = line.rstrip() # str, "Haddad's,PA,239.50"
items = line.split(',') # list, ["Haddad's", 'PA', '239.50\n']
state = items[1] # str, 'PA'
if state in wanted: # bool, True
print(line)
fh.close() #
|
|
| Ex. 5.26 | Collect a list of float values from revenue.csv from only those rows where the state can be found in the set of wanted states. |
wanted = {'NJ', 'PA'} # set, {'NJ', 'PA'}
fvals = [] # list, []
fh = open('revenue.csv') # 'file' object
for line in fh: # str, "Haddad's,PA,239.50\n"
line = line.rstrip() # str, "Haddad's,PA,239.50"
items = line.split(',') # list, ["Haddad's", 'PA', '239.50']
state = items[1] # str, 'PA'
fval = items[2] # str, '239.50'
if state in wanted: # bool, True
fvals.append(float(fval)) # list, [239.5]
fh.close()
print(fvals)
|
|
|
"WHOLE FILE" PARSING AND RANGE |
|
| Ex. 5.27 | Splitting a string into lines with .splitlines(). |
|
Perform the operations below. |
|
# split the below multi-line string into a list of string
# lines (use .splitlines()), and print the list of lines
text = """this is a line
this is another line
this is another line""" # str, 'this is a line\nthis is...'
lines = text.splitlines() # list, ['this is a line', 'this is ...']
print(lines)
print()
# read file 'pyku.txt' as a single string
# split the string into a list of strings lines as in previous
filename = 'pyku.txt' # str, 'pyku.txt'
fh = open(filename) # 'file' object
text = fh.read() # str, "We're out of gouda.This parrot has ceased..."
lines = text.splitlines() # list, ["We're out of gouda.", 'This parrot...']
print(lines)
|
|
| Ex. 5.28 | Split a file as a list of words. |
|
Read 'pyku.txt' as a single string; use .split() to split into words. Print the list of words. |
|
filename = 'pyku.txt' # str, 'pyku.txt'
fh = open(filename) # 'file' object
text = fh.read() # str, "We're out of gouda.\nThis parrot has ..."
words = text.split() # list, ["We're", 'out', 'of', 'gouda.', 'This' ...]
print(words)
|
|
| Ex. 5.29 | Read a file as a list of string lines. |
|
Read 'revenue.csv' as a list of strings (use .readlines()); print the list. Then use a list slice to select only the 2nd through last lines of the file - print these as well. |
|
filename = 'revenue.csv' # str, 'revenue.csv'
fh = open(filename) # 'file' object
lines = fh.readlines() # list, ["Haddad's,PA,239.50\n", "Westfield,NJ,53.90\n" ... ]
print(lines)
print()
print(lines[1:]) # list, ["Westfield,NJ,53.90\n", 'The Store,NJ,211.50\n' ...]
|
|
|
LAB 4 |
|
| Ex. 5.30 | Without looping, print the first and also the last line of pyku.txt. |
fh = open('pyku.txt') # str, 'pyku.txt'
lines = fh.readlines() # list, ["We're out of gouda.", 'This parrot ...']
print(lines[0]) # str, "We're out of gouda.\n"
print(lines[-1]) # str, 'Spam, spam, spam, spam, spam.\n'
|
|
| Ex. 5.31 | Without looping, print the first word and also the last word of pyku.txt. |
fh = open('pyku.txt') # str, 'pyku.txt'
text = fh.read() # str, "We're out of gouda.\nThis parrot ..."
words = text.split() # list, ["We're", 'out', 'of', 'gouda.', 'This', 'parrot'...]
print(words[0]) # str, "We're"
print(words[-1]) # str, 'spam.'
|
|
| Ex. 5.32 | Without looping, print a slice of the 5th through 10th words of pyku.txt. |
fh = open('pyku.txt') # str, 'pyku.txt'
text = fh.read() # str, "We're out of gouda.\nThis parrow ..."
words = text.split() # list, ["We're", 'out', 'of', 'gouda.', 'This', 'parrot'...]
print(words[4:11]) # list, ['This', 'parrot', 'has', 'ceased', 'to', 'be.']
|
|
| Ex. 5.33 | Without looping, show how many words are in the first line of pyku.txt. |
fh = open('pyku.txt') # 'file' object
lines = fh.readlines() # list, ["We're out of gouda.", 'This parrot ...']
first_line = lines[0] # str, "We're out of gouda.\n"
first_words = first_line.split() # list, ["We're", 'out', 'of', 'gouda.']
print(len(first_words)) # int, 4
|
|
| Ex. 5.34 | Without looping, show how many characters are in the first line of pyku.txt. |
fh = open('pyku.txt') # 'file' object
lines = fh.readlines() # list, ["We're out of gouda.", 'This parrot ...']
first_line = lines[0] # str, "We're out of gouda.\n"
print(len(first_line)) # int, 19
|
|
| Ex. 5.35 | Without looping, show how many lines are in pyku.txt. |
fh = open('pyku.txt') # 'file' object
lines = fh.readlines() # list, ["We're out of gouda.", 'This parrot ...']
print(len(lines)) # 3
|
|
|
range() AND enumerate() |
|
| Ex. 5.36 | Use range() to count. |
|
Without using a counter, create a for loop to iterate over each integer between 0 and 5. |
|
for num in range(0, 6): # int, 1 (initial value)
print(num)
|
|
| Ex. 5.37 | Use range() to create a list. |
|
In a single statement, build a list of integers from 3 to 5. |
|
numlist = list(range(3, 6)) # list, [3, 4, 5, 6]
print(numlist)
|
|
| Ex. 5.38 | Use enumerate() to count as you loop through list items. |
|
As you loop through this list of days, count each item starting at 0 using enumerate() (do not user a incrementing counter; you may put a comma between the number and item in your print statement.) |
|
days = ['Sunday', 'Monday', 'Tuesday']
for idx, item in enumerate(days):
print(idx, item)
|
|