Introduction to Python
davidbpython.com
In-Class Exercises, 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. Therefore 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 operations below. |
|
# initialize your list of 5 strings
mylist = ['hello', 'there', 'fine', 'Python', 'friends']
# access and print the 2nd item (use list subscript)
# access and print the last item (use negative subscript)
# slice and print the first 3 items from the list (use list slice)
# slice and print the last 3 items from the list (leave off the 'upper bound')
# look for the value 'Python' within the list
|
|
Expected Output:
there friends ['hello', 'there', 'fine'] ['fine', 'Python', 'friends'] |
|
| Ex. 5.2 | List with summary functions. |
x = [3.3, 1.1, 4.4, 2.2]
# in one statement, show count of items in a list (use len())
# sum up values in the list without looping (use sum())
# show maximum value in the list (use max())
# show minimum value in the list (use min())
# show list items sorted lowest to highest (use sorted())
# show list items sorted highest to lowest (add reverse=True)
|
|
Expected Output:
4 11.0 4.4 1.1 [1.1, 2.2, 3.3, 4.4] [4.4, 3.3, 2.2, 1.1] |
|
|
LAB 1 |
|
| Ex. 5.3 | Show the first 3 values in this list. |
x = [8, 1, 0, 2, 23, 4, 5, 11]
|
|
Expected Output:
[8, 1, 0] |
|
| Ex. 5.4 | Show the last 3 values in this list. Use a negative slice. |
x = [8, 1, 0, 2, 23, 4, 5, 11]
|
|
Expected Output:
[4, 5, 11] |
|
| Ex. 5.5 | Show the average of the values in this list. |
x = [8, 1, 0, 2, 23, 4, 5, 11]
|
|
Expected Output:
6.75 |
|
| Ex. 5.6 | Find highest and lowest values in a list. |
|
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]
|
|
Expected Output:
23 0 |
|
| Ex. 5.7 | Show the highest 3 values in this list, sorted high-to-low. |
x = [8, 1, 0, 2, 23, 4, 5, 11]
|
|
Expected Output:
[23, 11, 8] |
|
| Ex. 5.8 | Show the lowest 3 values in this list, sorted low-to-high. |
x = [8, 1, 0, 2, 23, 4, 5, 11]
|
|
Expected Output:
[0, 1, 2] |
|
| Ex. 5.9 | Show the 3rd highest value in this list. |
x = [8, 1, 0, 2, 23, 4, 5, 11]
|
|
Expected Output:
8 |
|
| Ex. 5.10 | Show the average of the highest 50% of values in this list. |
x = [8, 1, 0, 2, 23, 4, 5, 11]
|
|
Expected Output:
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. |
|
Expected Output:
[5.5, 6.6] |
|
|
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]
print(f'the sequence: { myseq }')
print(f'last item: { myseq[-1] }')
print(f'first 3 items: { myseq[0:3] }')
print(f'last 3 items: { myseq[-3:] }')
print(f'# of items: { len(myseq) }')
print(f'maximum value: { max(myseq) }')
print(f'minimum value: { min(myseq) }')
print('each item in sequence:')
for item in myseq:
print(item)
print()
print(f'sorted: { sorted(myseq) }')
print('appending to sequence: ')
myseq.append(99)
print(myseq)
|
|
|
SETS |
|
| 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]
print(f'the sequence: { myseq }')
print(f'last item: { myseq[-1] }')
print(f'first 3 items: { myseq[0:3] }')
print(f'last 3 items: { myseq[-3:] }')
print(f'# of items: { len(myseq) }')
print(f'maximum value: { max(myseq) }')
print(f'minimum value: { min(myseq) }')
print('each item in sequence:')
for item in myseq:
print(item)
print()
print(f'sorted: { sorted(myseq) }')
print('appending to sequence: ')
myseq.append(99)
|
|
|
LISTS - BUILDING FROM FILE |
|
| Ex. 5.14 | Review: loop through a list. |
x = [3.3, 1.1, 4.4, 2.2]
# loop through the list and print each item individually (use 'for')
|
|
Expected Output:
3.3 1.1 4.4 2.2 |
|
| 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')
fvals = []
for line in fh:
line = line.rstrip()
items = line.split(',')
print(items)
fh.close()
|
|
Expected Output:
[239.5, 53.9, 211.5, 11.98, 5.98, 23.95, 115.2] |
|
|
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'
# open file
# skip the first line of the file (use next())
# loop through file line-by-line
# strip each line
# print each line
|
|
Expected Output:
jk43:23 Marfield Lane:Plainview:NY:10024 axe99:315 W. 115th Street, Apt. 11B:New York:NY:10027 jab44:23 Rivington Street, Apt. 3R:New York:NY:10002 ak9:234 Main Street:Philadelphia:PA:08990 ap172:19 Boxer Rd.:New York:NY:10005 jb23:115 Karas Dr.:Jersey City:NJ:07127 jb29:119 Xylon Dr.:Jersey City:NJ:07127 |
|
|
Note that the header (id:address:city:state:zip) has been skipped with next(). |
|
| 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'
fh = open(filename)
next(fh) # skip the first line of the file (use next())
for line in fh:
line = line.rstrip()
# your code here -- remember that this file is colon-separated
|
|
Expected Output:
['jk43', '23 Marfield Lane', 'Plainview', 'NY', '10024'] ['axe99', '315 W. 115th Street, Apt. 11B', 'New York', 'NY', '10027'] ['jab44', '23 Rivington Street, Apt. 3R', 'New York', 'NY', '10002'] ['ak9', '234 Main Street', 'Philadelphia', 'PA', '08990'] ['ap172', '19 Boxer Rd.', 'New York', 'NY', '10005'] ['jb23', '115 Karas Dr.', 'Jersey City', 'NJ', '07127'] ['jb29', '119 Xylon Dr.', 'Jersey City', 'NJ', '07127'] |
|
| Ex. 5.18 | Compile a list of values from file lines. |
|
Build a list of student ids (first field) from student_db.txt. See 'next()' below, which shows how to skip the header |
|
filename = 'student_db.txt'
fh = open(filename)
next(fh) # skip the first line of the file
for line in fh:
line = line.rstrip()
items = line.split(':')
|
|
Expected Output:
['jk43', 'axe99', 'jab44', 'ak9', 'ap172', 'jb23', 'jb29'] |
|
| Ex. 5.19 | Calculate an average of values from a file. |
|
Show the average value from a list of the float values in file revenue.csv. |
|
Expected Output:
94.57285714285716 |
|
| Ex. 5.20 | Show the highest 3 values from the last column in dated_file.csv, sorted from highest to lowest. |
Expected Output:
[28.3, 23.85, 19.09] |
|
| Ex. 5.21 | Show the average of the highest 25% of values in dated_file.csv. |
Expected Output:
26.075000000000003 |
|
|
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. |
|
|
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 than as shown below.) |
|
fh = open('revenue.csv')
states = set() # the only way to initialize an empty set
for line in fh:
items = line.split(',')
fh.close()
print(states)
|
|
Expected Output:
{'PA', 'NY', 'NJ'} # your set order may be different
|
|
|
Note: your set may display in any order. |
|
|
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'
fh = open(filename)
next(fh)
for line in fh:
items = line.split(':')
print(items)
|
|
Expected Output:
{'Plainview', 'Philadelphia', 'New York', 'Jersey City'}
|
|
|
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'}
|
|
Expected Output:
Haddad's,PA,239.50 Westfield,NJ,53.90 The Store,NJ,211.50 Awful's,PA,23.95 |
|
| 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 = {'NY', 'PA'}
|
|
Expected Output:
[239.5, 53.9, 211.5, 23.95] |
|
|
"WHOLE FILE" PARSING AND RANGE |
|
| Ex. 5.27 | Split 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"""
print()
# read file 'pyku.txt' as a single string using .read()
# split the string into a list of strings lines as in previous
filename = 'pyku.txt'
fh = open(filename)
|
|
Expected Output:
['this is a line', 'this is another line', 'this is another line'] ["We're out of gouda.", 'This parrot has ceased to be.', 'Spam, spam, spam, spam, spam.'] |
|
| 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'
fh = open(filename)
|
|
Expected Output:
["We're", 'out', 'of', 'gouda.', 'This', 'parrot', 'has', 'ceased', 'to', 'be.', 'Spam,', 'spam,', 'spam,', 'spam,', 'spam.'] |
|
| 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'
fh = open(filename)
|
|
Expected Output:
["Haddad's,PA,239.50\n", 'Westfield,NJ,53.90\n', 'The Store,NJ,211.50\n', "Hipster's,NY,11.98\n", 'Dothraki Fashions,NY,5.98\n', "Awful's,PA,23.95\n", 'The Clothiers,NY,115.20\n'] ['Westfield,NJ,53.90\n', 'The Store,NJ,211.50\n', "Hipster's,NY,11.98\n", 'Dothraki Fashions,NY,5.98\n', "Awful's,PA,23.95\n", 'The Clothiers,NY,115.20\n'] |
|
|
LAB 4 |
|
| Ex. 5.30 | Without looping, print the first and also the last line of pyku.txt. |
Expected Output:
We're out of gouda. Spam, spam, spam, spam, spam. |
|
| Ex. 5.31 | Without looping, print the first word and also the last word of pyku.txt. |
Expected Output:
We're spam. |
|
| Ex. 5.32 | Without looping, print a slice of the 5th through 10th words of pyku.txt. |
Expected Output:
['This', 'parrot', 'has', 'ceased', 'to', 'be.'] |
|
| Ex. 5.33 | Without looping, show how many words are in the first line of pyku.txt. |
Expected Output:
4 |
|
| Ex. 5.34 | Without looping, show how many characters are in the first line of pyku.txt. |
Expected Output:
20 |
|
| Ex. 5.35 | Without looping, show how many lines are in pyku.txt. |
Expected Output:
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. |
|
Expected Output:
0 1 2 3 4 5 |
|
| Ex. 5.37 | Use range() to create a list. |
|
In a single statement, build a list of integers from 3 to 5. |
|
Expected Output:
[3, 4, 5] |
|
| 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']
|
|
Expected Output:
0 Sunday 1 Monday 2 Tuesday |
|