CS 110X Feb 21 2014
ABC. A, Always, B, Be, C, Closing. Always be closing.
Glengarry Glen Ross
1 Final Third Of Course
1.1 Lab 5
Note that Lab5 will be closed on Saturday afternoon, because of Academic Advising day. Please be sure you have completed the lab by that date.
1.2 Exam2 Review
Here are the question-by-question averages:
Q1 – 64%
Q2 – 81%
Q3 – 82%
Q4 – 66%
Q5 – 46%
I was pleased to see that students performed well on the programming questions Q2 and Q3.
However, this performance was offset by the results of Question 5. This question gave students the chance to demonstrate they could follow the execution of a function with a for loop that modified a list in place. We have covered each of these skills in the class, at different times. This question was a step-up from the last clicker question presented before the exam. However, it seems to have been too much.
Let’s review this question:
def update(values): for idx in range(1, len(values)): values[idx] += values[idx-1] print (values) values.append(len(values)) def main(): mylist = [2, 1, 3] update (mylist) print (mylist)
There were three questions to be answered:
a) [5 pts.] How many lines of output are printed?
b) [5 pts.] What is the first line of output printed?
c) [6 pts.] What is the last line of output printed?
I had broken this problem up into three parts; while there were dependencies, I had hoped the parts would be independent.
The key to this problem is to understand that the for loop executes twice using idx values of 1 and 2. This topic has been presented enough times that I felt I could depend on this concept being clearly understood. With this knowledge in hand, you can see that the print statement executes twice in the loop (because it is indented), and one final time at the end of main, which determines that there will be three lines of output.
The first printed line occurs immediately after values[idx] is updated. I had again hoped that most students would be able to get this far and receive ten points (or at least five points) on this question.
The final answer depends on the student’s ability to complete the execution of the code.
On this question, there really was no way to assign ’partial’ credit, which resulted in much lower scores on this question, with 52 students receiving zero points.
Note that I have posted a video solution for Exam2 on my.wpi.edu.
1.3 Getting pyserial for lab computers
Based on the results of student’s experience with downloading pyserial I will have to take a different approach. Note: this package/module is only needed for lab6 and lab7.
1.4 Moving Onwards
We are now ready to tackle the final issues remaining in your journey towards becoming a programmer.
The first part of the course focused on introducing the Python language. You learned about variables and basic python statements. You wrote functions that acted as whole programs. You learned how to read input from the user from the keyboard and print output to the console window. You learned about loops and lists. You saw logical conditions and conversions of values from ints, to floats, to strings.
In the second part of the course, I introduced the fundamental concept of writing functions that returned values, thus allowing you to write functions that participate in a computation. You then worked with functions that had parameters. Each parameter acts as a variable in the function which is initialized to the values passed in by argument. You learned how to process data found in a file.
From my perspective, there were two basic challenges in the second part of the course:
Passing arguments as values into functions
Working on more complicated problems
As we turn the corner to enter the third part of the course, we are going to work consistently on showing how to decompose problems into smaller, more manageable tasks which can be solved by functions that are composed together to solve the original problem.
The next three lectures will demonstrate the case study shown in the book. There are only a few times where I will have to modify the code from the book (because of the differences between Python 2.7.3 and Python 3.0). I am assuming that you will follow the reading and attempt to complete the same code examples. In many ways, until you follow, step by step, such a program design, you won’t be able to do it for yourself when faced with a blank page.
Once the case study has been discussed in detail, the remaining four lectures will be used to review and get more experience in tackling problems, sight unseen.
But first we have two skills to cover.
1.5 Random Numbers
One of the earliest uses of computing devices was to simulate random occurrences to statistically measure complicated behaviors and models.
Of course, these numbers are not truly random, but are rather pseudo-random numbers. For most practical purposes, you can generate on demand two kinds of random numbers:
A random number between [0 and 1)
A random integer between (and including) [a, b]
>>> import random >>> random.random() 0.24180835650788357 >>> random.randint(10,20) 15
Once you import the random module, you have access to these two functions.
You need to pay attention to random.random() which generates a random number in the range of [0, 1). That is, while 0 might be generated, 1 will never be generated.
What can you use these values for? Well, let’s say you wanted to simulate an unbiased flip of a coin. As you know each side of a coin has a 50% chance of occurring.
The following program tries 1000000 trials of a random coin flip.
import random def simulateCoinFlips(trial): """Return number of heads in toss of unbiased coin""" heads = 0 while trial > 0: # 0.0 through .499999... is heads # 0.5 through .999999... is tails if random.random() < .5: heads = heads + 1 trial = trial - 1 return heads def isFair(): """Simulate toss of a fair coin""" trials = input ("How many trials to run ") heads = simulateCoinFlips(trials) print (str(heads) + " in " + str(trials)) print (str(100.0*heads/trials) + " percent")
Is the random coin fair? You can read further.
1.6 Multiple Assignment Operator
The book makes extensive use of Python. Throughout this course, I have tried to only show the syntax that can easily translate to different programming languages.
However, the running case study starting on page 267 uses some capabilities that I have not yet covered.
Sometimes you might find yourself wanting to set two variables to the same initial value:
>>> a = 0 >>> b = 0
In Python (and many other programming languages), this can be shortened as follows:
>>> a = b = 0
But this is only part of the picture. What if you wanted to set two separate values to these variables: >>> a = 1 >>> b = 2
In Python (but not in other languages), you could say:
>>> a,b = 1,2
Thus you are simultaneously setting a to the value of 1, and b to the value of 2.
Now, if you ever find yourself reading lots of Python programs, you might come across this gem of a statement:
>>> x = 10 >>> y = 20 >>> x,y = y,x
After the above statements, what is the value of x and y? It turns out that in Python, the above is the recommended way to swap two variable values.
>>> print (str(x) + " " + str(y)) 20 10
That’s right, the above statement is the preferred Python way to swap variable values.
Other languages would do something like the following:
>>> x = 10 >>> y = 20 >>> >>> tmp = x >>> x = y >>> y = tmp
Thus the way to swap variable values is to introduce an intermediate temporary variable tmp used to hold onto the value of x just before x is assigned the value of y.
1.7 Python Functions Returning Multiple Values
Python functions can return multiple values without using lists. This new concept looks similar to the above multiple assignment operator. Consider the following function:
def randomPoint(): """Return a tuple representing a random point in unit square""" x = random.random() y = random.random() return (x,y)
This function computes two random values in the range [0,1) and returns a tuple containing these two values. The first value is considered to be the X coordinate, and the second the Y coordinate.
How would you invoke this function?
def main(): """demonstrate tuples in action""" pt = randomPoint() print (pt) xCoord = pt[0] yCoord = pt[1] print ("X = " + str(xCoord))
A tuple, then, is a convenient way to return multiple values from a function.
1.8 Simulating Racquetball games
Chapter 9 in the book contains an extended case study on how to write simple simulations.
In the specific example, the goal is to simulate the game of racquetball under very specific conditions.
To start the game, one player puts the ball into play by serving the ball. The players then alternate hitting the ball to keep it in play (called a rally). The rally ends when a player fails to hit a legal shot. That player is termed the loser of the rally. If the loser is the player who served initially, then the serve passes to the other player (and the score remains the same). If the server wins the rally, a point is awarded. Thus you can only gain points when you are serving.
The first player to reach 15 points wins the game.
There are many ways to simulate racquetball. The book bases the simulation on two probabilities.
Probability that Player A Wins when serving.
Probability that Player B Wins when serving.
Now assuming that Player A always serves first, what are the chances that Player A will win given the above probabilities?
As you see on page 275 of the book, the final program starts as follows:
def main(): """Simulate games of racquetball""" printIntro() probA, probB, n = getInputs() winsA, winsB = simNGames (n, probA, probB) printSummary(winsA, winsB)
That is, the program first prints out a useful introduction. Then a number of values are retrieved by the program: (a) probA is the probability that player A will win when serving; (b) probB is the probability that player B will win when serving; (c) the number of games to simulate.
The key function to implement is simNGames which simulates a number of games given these probabilities. We will tackle that function next week. To prepare for the function, be sure to read pages 275-279 for Monday and pages 279-288 for Tuesday. I would recommend going further, that is, type in the code as found in the book and try to validate that it executes according to your expectations, and the conditions as described in the book.
Be sure to pay attention to how I have used input in all cases to retrieve user input (rather than the eval(input(...)) code used by the book author, which is allowed in Python 3.0.
1.9 Homework 6 and Homework 7
There are two final Tuesdays this term, and that means two more homeworks. Now, homework7 is due Mar 04 2014 at 5:00 PM, which leaves us a final review day before Exam3. While Exam1 and Exam2 were each worth 15% of your grade, Exam3 is a cumulative 20% of your grade. You can prepare a single "cheat sheet" as before to bring with you to the exam.
The regular HW6 and HW7 homeworks will remain 5% (each) of the grade and will focus on giving students the opportunity to reinforce their knowledge of the programming skills covered in this class.
1.10 In-Class Performance
There will be four more clicker graded activities (see Syllabus for the dates). We will also begin to allocate more in-class time to solve problems "from scratch" of increasing difficulty. The goal is to be able to break a problem down into subtasks, each of which can be easily represented as functions.
As you may imagine, we will start with the basic four questions I have been promoting for weeks now: (a) what is the input; (b) what is the output; (c) what is the overall structure of the program; (d) what variables are needed for the program. With your increased maturity in programming, you can now expand these questions to investigate (e) what additional functions are needed to solve the overall problem.
1.11 Version : 2014/02/23
(c) 2014, George Heineman