Breif note and answers to a Python beginning lesson by Charles Severance.
Preface
I had a required Course of Python in my sophomore year but it’s pretty straightforward or shallow, even when it comes to so-called machine learning. We did the homework almost by copying the codes or algorithm from the Internet, and had little understanding of the principle about how it runs, and finally got a very average score. In fact, I’m quite interested in programing and there’s a chance to use it in my graduation project, which means it’s important to learn Python in depth.
There is a course called Python for Everybody which is highly recommended by many people to be the first step of programming. That’s why I picked this course to learn Python once again, and also could practice my English no matter the skill of listening, reading or pronunciations, it’s all good for them. The course provides a free e-book with a lot of exercises per chapter, so I make this note to write my answers.
Chapter 1 : Why Program
CPU
The Central Processing Unit (or CPU) is the part of the computer that is built to be obsessed with “what is next?” If your computer is rated at 3.0 Gigahertz, it means that the CPU will ask “What next?” three billion times per second. You are going to have to learn how to talk fast to keep up with the CPU.
The Main Memory is used to store information that the CPU needs in a hurry. The main memory is nearly as fast as the CPU. But the information stored in the main memory vanishes when the computer is turned off.
The Secondary Memory
The Secondary Memory is also used to store information, but it is much slower than the main memory. The advantage of the secondary memory is that it can store information even when there is no power to the computer. Examples of secondary memory are disk drives or flash memory (typically found in USB sticks and portable music players).
Input and Output Devices
The Input and Output Devices are simply our screen, keyboard, mouse, microphone, speaker, touchpad, etc. They are all of the ways we interact with the computer.
Network Connection
These days, most computers also have a Network Connection to retrieve information over a network. We can think of the network as a very slow place to store and retrieve data that might not always be “up”. So in a sense, the network is a slower and at times unreliable form of Secondary Memory.
Reserved word
Python reserves 33 keywords:
and, del, from, None, True, as, elif, global, nonlocal, try, assert, else, if, not, while, break, except, import, or, with, class, False, in, pass, yield, continue, finally, is, raise, def, for, lambda, return.
Chapter 2 : Variables, expressions, and statements
Exercise 2.2
Write a program that uses input to prompt a user for their name and then welcomes them.
1 2
Enter your name: Chuck Hello Chuck
1 2
name = input('Enter your name: ') print('Hello', name)
Exercise 2.3
Write a program to prompt the user for hours and rate per hour to compute gross pay.
1 2 3
Enter Hours: 35 Enter Rate: 2.75 Pay: 96.25
1 2 3 4 5
hrs = input('Enter Hours: ') rate = input('Enter Rate: ') h = float(hrs) r = float(rate) print("Pay: ", h*r)
Exercise 2.4
Assume that we execute the following assignment statements:
1 2
width = 17 height = 12.0
For each of the following expressions, write the value of the expression and the type (of the value of the expression).
1 2 3 4
1. width//2 2. width/2.0 3. height/3 4.1 + 2 * 5
Use the Python interpreter to check your answers.
1 2 3 4
8 8.5 4.0 11
Exercise 2.5
Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, and print out the converted temperature.
1 2 3 4
Celsius = input('Enter Celsius temperature: ') C = float(Celsius) F = 32 + C*1.8 print('The converted Fahrenheit temperature is: ', F, '°F')
Chapter 3 : Conditional execution
Exercise 3.1
Rewrite your pay computation to give the employee 1.5 times the hourly rate for hours worked above 40 hours.
1 2 3
Enter Hours: 45 Enter Rate: 10 Pay: 475.0
1 2 3 4 5 6 7 8 9
hrs = input('Enter Hours: ') rate = input('Enter Rate: ') h = float(hrs) r = float(rate) if h <= 40: pay = h*r else: pay = 40*r + (h-40)*1.5*r print("Pay: ", pay)
Exercise 3.2
Rewrite your pay program using try and except so that your program handles non-numeric input gracefully by printing a message and exiting the program. The following shows two executions of the program:
1 2 3 4 5
Enter Hours: 20 Enter Rate: nine Error, please enter numeric input Enter Hours: forty Error, please enter numeric input
1 2 3 4 5 6 7 8 9 10 11 12
hrs = input('Enter Hours: ') rate = input('Enter Rate: ') try: h = float(hrs) r = float(rate) if h <= 40: pay = h*r else: pay = 40*r + (h-40)*1.5*r print("Pay: ", pay) except: print('Error, Please enter numeric input')
Exercise 3.3
Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error message. If the score is between 0.0 and 1.0, print a grade using the following table:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Score Grade >= 0.9 A >= 0.8 B >= 0.7 C >= 0.6 D < 0.6 F
Enter score: 0.95 A Enter score: perfect Bad score Enter score: 10.0 Bad score Enter score: 0.75 C Enter score: 0.5 F
Run the program repeatedly as shown above to test the various different values for input.
score = input("Enter Score: ") try: s = float(score) if s <= 1: if s >= 0.9: print("A") elif s >= 0.8: print("B") elif s >= 0.7: print("C") elif s >= 0.6: print("D") elif s >=0 : print("F") else: print("Bad score") else: print('Bad score') except: print('Bad score')
Chapter 4 : Functions
Exercise 4.1
Run the program on your system and see what numbers you get. Run the program more than once and see what numbers you get.
1 2 3 4
import random print(random.randint(5, 10)) t = [1, 2, 3] print(random.choice(t))
Exercise 4.6
Rewrite your pay computation with time-and-a-half for overtime and create a function called computepay which takes two parameters(hours and rate).
1 2 3
Enter Hours: 45 Enter Rate: 10 Pay: 475.0
1 2 3 4 5 6 7 8 9 10 11 12 13
defcomputepay(): hrs = input('Enter Hours: ') rate = input('Enter Rate: ') try: h = float(hrs) r = float(rate) if h <= 40: pay = h*r else: pay = 40*r + (h-40)*1.5*r print("Pay: ", pay) except: print('Error, Please enter numeric input')
Exercise 4.7
Rewrite the grade program from the previous chapter using a function called computegrade that takes a score as its parameter and returns a grade as a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Score Grade >= 0.9 A >= 0.8 B >= 0.7 C >= 0.6 D < 0.6 F Enter score: 0.95 A Enter score: perfect Bad score Enter score: 10.0 Bad score Enter score: 0.75 C Enter score: 0.5 F
Run the program repeatedly to test the various different values for input.
defcomputegrade(): score = input("Enter Score: ") try: s = float(score) if s <= 1: if s >= 0.9: print("A") elif s >= 0.8: print("B") elif s >= 0.7: print("C") elif s >= 0.6: print("D") elif s >=0 : print("F") else: print("Bad score") else: print('Bad score') except: print('Bad score')
Chapter 5 : Iteration
Exercise 5.1
Write a program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.
1 2 3 4 5 6 7
Enter a number: 4 Enter a number: 5 Enter a number: bad data Invalid input Enter a number: 7 Enter a number: done 1635.333333333333333
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
num = 0 count = 0 s = 0 whileTrue: num = input('Enter a number: ') if num == 'done': break try: n = float(num) count = count + 1 s = s + n average = s/count except: print('Invalid input') print(s, count, average)
Exercise 5.2
Write another program that prompts for a list of numbers as above and at the end prints out both the maximum and minimum of the numbers instead of the average.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
largest = None smallest = None whileTrue: num = input("Enter a number: ") if num == "done": break else: try: inum = int(num) if largest isNoneor inum > largest: largest = inum elif smallest isNoneor inum < smallest: smallest = inum except: print('Invalid input') continue print("Maximum is", largest) print("Minimum is", smallest)
Chapter 6 : Strings
Exercise 6.5
Take the following Python code that stores a string: str = ‘X-DSPAM-Confidence: 0.8475’
Use find and string slicing to extract the portion of the string after the colon character and then use the float function to convert the extracted string into a floating point number.
1 2 3 4 5
text = "X-DSPAM-Confidence: 0.8475" index = text.find(' ') x = text[index+4 : ] y = float(x) print(y)
Chapter 7 : Files
Exercise 7.1
Write a program to read through a file and print the contents of the file (line by line) all in upper case. Executing the program will look as follows:
1 2 3 4 5 6 7
python shout.py Enter a file name: mbox-short.txt FROM STEPHEN.MARQUARD@UCT.AC.ZA SAT JAN 5 09:14:162008 RETURN-PATH: <POSTMASTER@COLLAB.SAKAIPROJECT.ORG> RECEIVED: FROM MURDER (MAIL.UMICH.EDU [141.211.14.90]) BY FRANKENSTEIN.MAIL.UMICH.EDU (CYRUS V2.3.8) WITH LMTPA; SAT, 05 JAN 2008 09:14:16 -0500
fn = input('Enter a file name: ') fh = open(fn) for line in fh: ly = line.rstrip() #delete the space of each line ly = ly.upper() print(ly)
Exercise 7.2
Write a program to prompt for a file name, and then read through the file and look for lines of the form:
1
X-DSPAM-Confidence: 0.8475
When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart the line to extract the floating-point number on the line. Count these lines and then compute the total of the spam confidence values from these lines. When you reach the end of the file, print out the average spam confidence.
1 2
Enter the file name: mbox-short.txt Average spam confidence: 0.750718518519
1 2 3 4 5 6 7 8 9 10 11 12 13
i = 0 s = 0 fname = input("Enter file name: ") fh = open(fname) for line in fh: ifnot line.startswith("X-DSPAM-Confidence:"): continue else: i = i+1 index = line.find(' ') f = line[index+1:] s = s + float(f) print('Average spam confidence:', s/i)
Exercise 7.3
Sometimes when programmers get bored or want to have a bit of fun, they add a harmless Easter Egg to their program Modify the program that prompts the user for the file name so that it prints a funny message when the user types in the exact file name “na na boo boo”. The program should behave normally for all other files which exist and don’t exist. Here is a sample execution of the program:
1 2 3 4 5 6 7 8 9
python egg.py Enter the file name: mbox.txt There were 1797 subject lines in mbox.txt python egg.py Enter the file name: missing.tyxt File cannot be opened: missing.tyxt python egg.py Enter the file name: na na boo boo NA NA BOO BOO TO YOU - You have been punk'd!
1 2 3 4 5 6 7 8 9 10 11 12
i=0 fname = input("Enter file name: ") try: fh = open(fname) for line in fh: i = i+1 print('There were', i, 'subject lines in', fname) except: if fname == 'na na boo boo': print('NA NA BOO BOO TO YOU - You have been punk\'d!') else: print('File cannot be opened: ', fname)
Chapter 8 : Lists
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.
fname = input("Enter file name: ") fh = open(fname) lst=list() for line in fh: ly = line.rstrip() words = ly.split() for word in words: if word notin lst: lst.append(word) lst.sort() print(lst)
Exercise 8.5
Write a program to read through the mail box data and when you find 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 the second word on the From line.
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:
1 2 3 4 5 6 7 8 9 10 11
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
1 2 3 4 5 6 7 8 9 10 11
fname = input("Enter file name: ") iflen(fname) < 1: fname = "mbox-short.txt" fh = open(fname) count = 0 for line in fh: if line.startswith("From "): count = count+1 line = line.split() print(line[1]) print("There were", count, "lines in the file with From as the first word")
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.
1 2 3 4 5 6 7 8
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
1 2 3 4 5 6 7 8 9
k = list() whileTrue: n = input("Enter a number: ") if n == "done": break k.append(n) # print(k) print('Maximum: ', max(k)) print('Minimum: ', min(k))
Chapter 9 : Dictionaries
Exercise 9.2
Write a program that categorizes each mail message by which day of the week the commit was done. To do this look for lines that start with “From”, then look for the third word and keep a running count of each of the days of the week. At the end of the program print out the contents of your dictionary (order does not matter). Sample Line:
1
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:162008
Sample Execution:
1 2 3
python dow.py Enter a file name: mbox-short.txt {'Fri': 20, 'Thu': 6, 'Sat': 1}
1 2 3 4 5 6 7 8 9 10
d = {} fname = input("Enter file name: ") fh = open(fname) for line in fh: ifnot line.startswith("From "): continue else: line = line.split() d[line[2]] = d.get(line[2],0) + 1 print(d)
Exercise 9.3
Write a program to read through a mail log, build a histogram using a dictionary to count how many messages have come from each email address, and print the dictionary.
d = {} fname = input("Enter file name: ") fh = open(fname) for line in fh: ifnot line.startswith("From "): continue else: line = line.split() d[line[1]] = d.get(line[1],0) + 1 print(d)
Exercise 9.4
Add code to the above program to figure out who has the most messages in the file. After all the data has been read and the dictionary has been created, look through the dictionary using a maximum loop (see Chapter 5: Maximum and minimum loops) to find who has the most messages and print how many messages the person has.
1 2
Enter a file name: mbox-short.txt cwen@iupui.edu 5
1 2 3 4 5 6 7 8 9 10 11 12 13
d = {} fname = input("Enter file name: ") fh = open(fname) for line in fh: ifnot line.startswith("From "): continue else: line = line.split() d[line[1]] = d.get(line[1],0) + 1 t = max(d.values()) for key,value in d.items(): if value == t: print(key,value)
Exercise 9.5
This program records the domain name (instead of the address) where the message was sent from instead of who the mail came from (i.e., the whole email address). At the end of the program, print out the contents of your dictionary.
1 2 3 4
python schoolcount.py Enter a file name: mbox-short.txt {'media.berkeley.edu': 4, 'uct.ac.za': 6, 'umich.edu': 7, 'gmail.com': 1, 'caret.cam.ac.uk': 1, 'iupui.edu': 8}
1 2 3 4 5 6 7 8 9 10 11 12
d = {} fname = input("Enter file name: ") fh = open(fname) for line in fh: ifnot line.startswith("From "): continue else: line = line.split() index = line[1].find('@') line[1] = line[1][index+1:] d[line[1]] = d.get(line[1],0) + 1 print(d)
Chapter 10 : Tuples
Exercise 10.1
Revise a previous program as follows: Read and parse the “From” lines and pull out the addresses from the line. Count the number of messages from each person using a dictionary.
After all the data has been read, print the person with the most commits by creating a list of (count, email) tuples from the dictionary. Then sort the list in reverse order and print out the person who has the most commits.
1 2 3 4
Sample Line: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:162008 Enter a file name: mbox-short.txt cwen@iupui.edu 5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
d = {} ko = list() fname = "mbox-short.txt" fh = open(fname) for line in fh: ifnot line.startswith("From "): continue else: line = line.split() d[line[1]] = d.get(line[1],0) + 1 for k, v in d.items(): s = (v, k) ko.append(s) ki = sorted(ko, reverse=True) for k,v in ki[:1]: print(v,k)
Exercise 10.2
This program counts the distribution of the hour of the day for each of the messages. You can pull the hour from the “From” line by finding the time string and then splitting that string into parts using the colon character. Once you have accumulated the counts for each hour, print out the counts, one per line, sorted by hour as shown below.
d = {} fname = "mbox-short.txt" fh = open(fname) for line in fh: ifnot line.startswith("From "): continue else: line = line.split() index = line[5].find(':') line[5] = line[5][:index] d[line[5]] = d.get(line[5],0) + 1 k = sorted(d.items()) for k,v in k: print(k,v)
Exercise 10.3
Write a program that reads a file and prints the letters in decreasing order of frequency. Your program should convert all the input to lower case and only count the letters a-z. Your program should not count spaces, digits, punctuation, or anything other than the letters a-z. Find text samples from several different languages and see how letter frequency varies between languages.
for line in fhand: line = line.translate(str.maketrans('', '', string.digits)) line = line.translate(str.maketrans('', '', string.punctuation)) line = line.lower()
# Removes numbers and punctuation then sets all letters to lower case words = line.split() for word in words: for letter in word: # Count each letter for relative frequencies counts += 1 if letter notin dictionary_counts: dictionary_counts[letter] = 1 else: dictionary_counts[letter] += 1
for key, val inlist(dictionary_counts.items()): relative_lst.append((val / counts, key)) # Computes the relative frequency
relative_lst.sort(reverse=True) # Sorts from highest rel freq
for key, val in relative_lst: print(key, val)
Chapter 11 : Regular Expressions
Exercise 11.1
Write a program to sum all the numbers happened in the file.
import re s = 0 fname = "regex_sum_1678990.txt" fh = open(fname) for line in fh: x = re.findall('[0-9]+', line) iflen(x) > 0: i = 0 while i < len(x): x[i] = int(x[i]) i = i+1 s = s + sum(x) print(s)
Exercise 11.2
Write a program to look for lines of the form:
1
New Revision: 39772
Extract the number from each of the lines using a regular expression and the findall() method. Compute the average of the numbers and print out the average.
1 2
Enter file:mbox-short.txt 39756.9259259
1 2 3 4 5 6 7 8 9 10 11
import re fname = "mbox-short.txt" fh = open(fname) count = 0 s = 0 for line in fh: x = re.findall('^New Revision: ([0-9.]+)',line) iflen(x) > 0: count = count + 1 s = s + float(x[0]) print(s/count)