1 Programming: A High Level View
1.1 in Python statement
1.2 Index function
1.3 Sort Function
1.4 Updating A List
1.5 Modulo (%) operator for integers
1.6 Repetition operator (*) for lists
1.7 In Class Exercise
1.8 Software Development Process
1.9 Exercise to tackle
1.10 Culmination
1.11 Version : 2014/ 02/ 05

CS 110X Jan 30 2014

Lecture Path: 08
Back Next

Expected reading: 66-73
Expected interaction: Type conversions Membership, identity ops
Clicker: Assessment

Homework 3 is now assigned

Emergence: the arising of novel and coherent structures, patterns and properties during the process of self-organization in complex systems.
Jeffrey Goldstein

1 Programming: A High Level View

1.1 in Python statement

There are two more list operators of which you must be aware.

Sometimes you want to see if a specific value exists (somewhere) within a list.

Python provides a really quick solution, e in list:

>>> x = [2, 4, 8, 2, 5] >>> 3 in x False >>> 2 in x True

It doesn’t matter how many times the value appears (or where), this statement will return True if the element e exists within the list.

This also works when the values are string literals.

>>> x = [’Yes’, ’No’] >>> ’Maybe’ in x False >>> ’No’ in x True

1.2 Index function

Once you know that a certain value exists within a list, it is useful to be able to determine its index location. Again, Python comes with a statement ready to go:

>>> x = [1, 2, 5, 9] >>> x.index(5) 2 >>> x.index(7) Traceback (most recent call last): File "<pyshell#64>", line 1, in <module> x.index(7) ValueError: 7 is not in list

The index function returns the index of the left-most occurrence of the given value. Should the value not exist in the list, then an error occurs.

If you believe that a value exists more than one time in a list, then you can supply an additional argument, as follows, index(value, startIndex)

>>> x = [1, 2, 3, 5, 1] >>> x.index(1) 0 >>> x.index(1, 1) 4

With two parameters, index(value, startIndex) will start looking for value from index positions startIndex and higher.

1.3 Sort Function

It is possible to actually update a list once it has been created. Given a list of values, the sort function permutes its elements to be in ascending order.

>>> x = [2, 10, 8, 5, 3] >>> x.sort() >>> x [2,3,5,8,10]

1.4 Updating A List

You have seen how to refer to an individual element in a list by its index location. Now you can use the same syntax to set the value of an individual index location in a list.

>>> x = [2, 4, 8, 5, 10] >>> x[0] 2 >>> x[0] = 13 >>> x [13, 4, 8, 5, 10]

As you can see above, if you place list[idx] on the left hand side of an assignment operator, you can change the value of the element stored in the list at the desired location.

This operation will be extremely useful to store and update values being stored at specific locations. For example, you could summarize sales for a company by month and use a list with twelve values to record the totals.

1.5 Modulo (%) operator for integers

You often need to determine whether an integer is even or odd. This is actually easy to do in a programming language because of integer division.

>>> x = 13 >>> x/2 6 >>> 2*(x/2) 12 >>> if x == 2*(x/2): print (str(x) + " is even.")

While this works, it is a bit unseemly, don’t you think? Fortunately there is a final operator that you can use in Python which is used extensively in C and other languages. The "%" operator (also called modulo) determines the remainder when dividing an integer by another integer.

>>> x = 13 >>> x % 2 1 >>> x = 24 >>> x % 2 0 >>> x % 8 0 >>> x % 9 6

Above, the remainder of dividing 13 by 2 is 1. Thus you know that 13 is not evenly divisible by 2, which means it is an odd number. You can put this into an if statement as follows:

>>> x = 13 >>> if x % 2 == 1: print (str(x) + " is an odd number")

1.6 Repetition operator (*) for lists

Often you want to start a computation by defining a variable to hold information. Sample programs have used a count variable set to 0, or a values list set to the empty list []. However, what if you wanted to create a list that contains n zero values?

If you know the number n in advance, simply write the proper number of zeros, as done below which keeps track of ten separate values, each zero.

>>> values = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >>> values [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Python offers a convenient way to do this for any initial number.

>>> values = [0] * 10 >>> values [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

You can read the above code as "create a list of ten 0 values".

1.7 In Class Exercise

We have covered a lot of ground in Python programming.

You have been introduced to variables, which store values using a variety of types, such as int, float, bool. You’ve heard me proclaim that the type of the value determines the type of the variable. You’ve used variables to store values entered by the user. Then you’ve performed mathematical computations with +, , *, and /. You’ve learned the danger of integer division and the need to work with floating point values when possible.

You have written functions that contain a body of Python statements. Each function in a module must have a unique name by which you refer to the function. Using functions in the Python shell window, the user can direct a sequence of actions as implemented in Python. A user can then load up a module of useful functions to tackle various tasks.

One of the hardest parts of programming is learning how to convert the "requirements for a program" into the actual program itself. Today we are going to make some small progress towards this goal.

Another challenge you will face is that until you learn specific Python statements and functions, there will remain problems that you won’t be able to solve. Addressing this skill is akin to uncovering the things that "you don’t know you don’t know".

1.8 Software Development Process

The text book has a brief description of the software development process on pages 27–28. The following are the key steps that you need to follow for every problem in this course:

This course will only give a light treatment to Design, because we are focused on learning about programming. Still, when you are trying to solve more complicated and advanced problems, you will need to carefully design the proper way to solve the problem. As you solve problems in this course, my goal is to show you how a program’s design is derived from (a) the nature of the variables (and types) used to store and process input; and (b) the nature and type of output to be generated.

1.9 Exercise to tackle

Let’s start by taking 10 minutes out of today’s lecture to tackle the following problem. Please sit with your programming partner, if you are able to, and work together (or in groups of 3)...

You have a sample set containing the results of rolling a die. You suspect the dice is "biased" in some way. How would you go about demonstrating this fact? Here is a sample of the values (you have about 5000 of them).

result = [4, 1, 2, 2, 5, 2, 4, 6, 6, 2, 1, 4, 5, 4, 2, 2, 6, 3, 4, ...]

So this is something more substantial than you have tackled yet! But let’s get started in solving this problem:

Your goal is to identify:

We’ll tackle each of the four in an "open session". Please take a stab at this now, and take out some paper (or your laptop) to make an initial draft of your program.

1.10 Culmination

Present the solution in class and go over it with everyone.

1.11 Version : 2014/02/05

(c) 2014, George Heineman