Iteration - Introduction Programing - Review Sheet | EECS 12, Assignments of Electrical and Electronics Engineering

Material Type: Assignment; Class: INTRO PROGRAMMING; Subject: Electrical Engineering & Computer Science; University: University of California - Irvine; Term: Unknown 1989;

Typology: Assignments

Pre 2010

Uploaded on 09/17/2009

koofers-user-9by
koofers-user-9by 🇺🇸

5

(1)

10 documents

1 / 12

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Chapter 6
Iteration
6.1 Multiple assignment
As you may have discovered, it is legal to make more than one assignment to
the same variable. A new assignment makes an existing variable refer to a new
value (and stop referring to the old value).
bruce = 5
print bruce,
bruce = 7
print bruce
The output of this program is 57, because the first time bruce is printed, his
valueis5,andthesecondtime,hisvalueis7. Thecommaattheendofthe
first print statement suppresses the newline after the output, which is why
both outputs appear on the same line.
Here is what multiple assignment looks like in a state diagram:
7
5
bruce
With multiple assignment it is especially important to distinguish between an
assignment operation and a statement of equality. Because Python uses the
equal sign (=) for assignment, it is tempting to interpret a statement like a=b
as a statement of equality. It is not!
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Iteration - Introduction Programing - Review Sheet | EECS 12 and more Assignments Electrical and Electronics Engineering in PDF only on Docsity!

Chapter 6

Iteration

6.1 Multiple assignment

As you may have discovered, it is legal to make more than one assignment to the same variable. A new assignment makes an existing variable refer to a new value (and stop referring to the old value).

bruce = 5 print bruce, bruce = 7 print bruce

The output of this program is 5 7, because the first time bruce is printed, his value is 5, and the second time, his value is 7. The comma at the end of the first print statement suppresses the newline after the output, which is why both outputs appear on the same line.

Here is what multiple assignment looks like in a state diagram:

bruce

With multiple assignment it is especially important to distinguish between an assignment operation and a statement of equality. Because Python uses the equal sign (=) for assignment, it is tempting to interpret a statement like a = b as a statement of equality. It is not!

60 Iteration

First, equality is commutative and assignment is not. For example, in mathe- matics, if a = 7 then 7 = a. But in Python, the statement a = 7 is legal and 7 = a is not.

Furthermore, in mathematics, a statement of equality is always true. If a = b now, then a will always equal b. In Python, an assignment statement can make two variables equal, but they don’t have to stay that way:

a = 5 b = a # a and b are now equal a = 3 # a and b are no longer equal

The third line changes the value of a but does not change the value of b, so they are no longer equal. (In some programming languages, a different symbol is used for assignment, such as <- or :=, to avoid confusion.)

Although multiple assignment is frequently helpful, you should use it with cau- tion. If the values of variables change frequently, it can make the code difficult to read and debug.

6.2 The while statement

Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly.

We have seen two programs, nLines and countdown, that use recursion to per- form repetition, which is also called iteration. Because iteration is so common, Python provides several language features to make it easier. The first feature we are going to look at is the while statement.

Here is what countdown looks like with a while statement:

def countdown(n): while n > 0: print n n = n- print "Blastoff!"

Since we removed the recursive call, this function is not recursive.

You can almost read the while statement as if it were English. It means, “While n is greater than 0, continue displaying the value of n and then reducing the value of n by 1. When you get to 0, display the word Blastoff!”

More formally, here is the flow of execution for a while statement:

62 Iteration

Particular values aside, the interesting question is whether we can prove that this program terminates for all values of n. So far, no one has been able to prove it or disprove it!

As an exercise, rewrite the function nLines from Section 4.9 using iteration instead of recursion.

6.3 Tables

One of the things loops are good for is generating tabular data. Before comput- ers were readily available, people had to calculate logarithms, sines and cosines, and other mathematical functions by hand. To make that easier, mathematics books contained long tables listing the values of these functions. Creating the tables was slow and boring, and they tended to be full of errors.

When computers appeared on the scene, one of the initial reactions was, “This is great! We can use the computers to generate the tables, so there will be no errors.” That turned out to be true (mostly) but shortsighted. Soon thereafter, computers and calculators were so pervasive that the tables became obsolete.

Well, almost. For some operations, computers use tables of values to get an approximate answer and then perform computations to improve the approxi- mation. In some cases, there have been errors in the underlying tables, most famously in the table the Intel Pentium used to perform floating-point division.

Although a log table is not as useful as it once was, it still makes a good example of iteration. The following program outputs a sequence of values in the left column and their logarithms in the right column:

x = 1. while x < 10.0: print x, ’\t’, math.log(x) x = x + 1.

The string ’\t’ represents a tab character.

As characters and strings are displayed on the screen, an invisible marker called the cursor keeps track of where the next character will go. After a print statement, the cursor normally goes to the beginning of the next line.

The tab character shifts the cursor to the right until it reaches one of the tab stops. Tabs are useful for making columns of text line up, as in the output of the previous program:

6.3 Tables 63

If these values seem odd, remember that the log function uses base e. Since powers of two are so important in computer science, we often want to find logarithms with respect to base 2. To do that, we can use the following formula:

log 2 x =

logex loge 2

Changing the output statement to:

print x, ’\t’, math.log(x)/math.log(2.0)

yields:

1.0 0. 2.0 1. 3.0 1. 4.0 2. 5.0 2. 6.0 2. 7.0 2. 8.0 3. 9.0 3.

We can see that 1, 2, 4, and 8 are powers of two because their logarithms base 2 are round numbers. If we wanted to find the logarithms of other powers of two, we could modify the program like this:

x = 1. while x < 100.0: print x, ’\t’, math.log(x)/math.log(2.0) x = x * 2.

Now instead of adding something to x each time through the loop, which yields an arithmetic sequence, we multiply x by something, yielding a geometric se- quence. The result is:

6.5 Encapsulation and generalization 65

The first line initializes a variable named i, which acts as a counter or loop variable. As the loop executes, the value of i increases from 1 to 6. When i is 7, the loop terminates. Each time through the loop, it displays the value of 2*i, followed by three spaces.

Again, the comma in the print statement suppresses the newline. After the loop completes, the second print statement starts a new line.

The output of the program is:

2 4 6 8 10 12

So far, so good. The next step is to encapsulate and generalize.

6.5 Encapsulation and generalization

Encapsulation is the process of wrapping a piece of code in a function, allowing you to take advantage of all the things functions are good for. You have seen two examples of encapsulation: printParity in Section 4.5; and isDivisible in Section 5.4.

Generalization means taking something specific, such as printing the multiples of 2, and making it more general, such as printing the multiples of any integer.

This function encapsulates the previous loop and generalizes it to print multiples of n:

def printMultiples(n): i = 1 while i <= 6: print n*i, ’\t’, i = i + 1 print

To encapsulate, all we had to do was add the first line, which declares the name of the function and the parameter list. To generalize, all we had to do was replace the value 2 with the parameter n.

If we call this function with the argument 2, we get the same output as before. With the argument 3, the output is:

3 6 9 12 15 18

With the argument 4, the output is:

4 8 12 16 20 24

66 Iteration

By now you can probably guess how to print a multiplication table—by call- ing printMultiples repeatedly with different arguments. In fact, we can use another loop:

i = 1 while i <= 6: printMultiples(i) i = i + 1

Notice how similar this loop is to the one inside printMultiples. All we did was replace the print statement with a function call.

The output of this program is a multiplication table:

1 2 3 4 5 6 2 4 6 8 10 12 3 6 9 12 15 18 4 8 12 16 20 24 5 10 15 20 25 30 6 12 18 24 30 36

6.6 More encapsulation

To demonstrate encapsulation again, let’s take the code from the end of Sec- tion 6.5 and wrap it up in a function:

def printMultTable(): i = 1 while i <= 6: printMultiples(i) i = i + 1

This process is a common development plan. We develop code by writing lines of code outside any function, or typing them in to the interpreter. When we get the code working, we extract it and wrap it up in a function.

This development plan is particularly useful if you don’t know, when you start writing, how to divide the program into functions. This approach lets you design as you go along.

68 Iteration

6.8 More generalization

As another example of generalization, imagine you wanted a program that would print a multiplication table of any size, not just the six-by-six table. You could add a parameter to printMultTable:

def printMultTable(high): i = 1 while i <= high: printMultiples(i) i = i + 1

We replaced the value 6 with the parameter high. If we call printMultTable with the argument 7, it displays:

1 2 3 4 5 6 2 4 6 8 10 12 3 6 9 12 15 18 4 8 12 16 20 24 5 10 15 20 25 30 6 12 18 24 30 36 7 14 21 28 35 42

This is fine, except that we probably want the table to be square—with the same number of rows and columns. To do that, we add another parameter to printMultiples to specify how many columns the table should have.

Just to be annoying, we call this parameter high, demonstrating that different functions can have parameters with the same name (just like local variables). Here’s the whole program:

def printMultiples(n, high): i = 1 while i <= high: print n*i, ’\t’, i = i + 1 print

def printMultTable(high): i = 1 while i <= high: printMultiples(i, high) i = i + 1

Notice that when we added a new parameter, we had to change the first line of the function (the function heading), and we also had to change the place where

6.9 Functions 69

the function is called in printMultTable.

As expected, this program generates a square seven-by-seven table:

1 2 3 4 5 6 7 2 4 6 8 10 12 14 3 6 9 12 15 18 21 4 8 12 16 20 24 28 5 10 15 20 25 30 35 6 12 18 24 30 36 42 7 14 21 28 35 42 49

When you generalize a function appropriately, you often get a program with capabilities you didn’t plan. For example, you might notice that, because ab = ba, all the entries in the table appear twice. You could save ink by printing only half the table. To do that, you only have to change one line of printMultTable. Change

printMultiples(i, high)

to

printMultiples(i, i)

and you get

1 2 4 3 6 9 4 8 12 16 5 10 15 20 25 6 12 18 24 30 36 7 14 21 28 35 42 49

As an exercise, trace the execution of this version of printMultTable and figure out how it works.

6.9 Functions

A few times now, we have mentioned “all the things functions are good for.” By now, you might be wondering what exactly those things are. Here are some of them:

  • Giving a name to a sequence of statements makes your program easier to read and debug.