Chapter 8

Sections 8.1 - 8.4

\(\boxdot\) Iteration Revisited
  • machines do repetitive tasks quickly and accurately (usually better than humans)

  • Uses of the for loop:

    • looping on item in a list:

      for l_color in ['red', 'green', 'yellow']:  
          t.color(l_color)  
          t.up()  
          t.goto(x_loc, y_loc)  
          draw_square(s_length) 
    • looping on an index through a range:

      for i in range(10):  
          interval_number = find_interval(random.randrange[1,101])  
    • in both cases, the number of items or iterations desired, or required, is known and “definite”

  • The while loop can be used for an iteration case when the total number of required iterations is not known. This is called an indefinite loop.

  • The Python structure is for a while loop is:

    while BOOLEAN_EXPRESSION:  
        STATEMENTS  

*Activity 1: Write a program that includes a function called sum_random(limit) that sums randomly selected integers from the interval [-5, 10] until the sum of the integers reaches or exceeds the limit, where limit is a positive number. The function returns the sum and the number of iterations required.

\(\boxdot\) A Random (turtle) Walk

*Activity 2: Turtle Race. Write a program that uses the turtle and random modules to simulate a race of two or more turtles that start at the origin and move in a random fashion described below. The first turtle to cross the 15-foot radius circle, centered at the origin wins. Consequently, your program will employ a while loop (an indefinite loop) to allow the turtles to move until at least one of them crosses the finish circle.

Copy and paste the code shown below into the active code window for the Chapter 8 Activity 2.

Turtle t1’s path is characterized by a random direction given by t1.left(random.randrange(-60, 61)) and a random path length given by t1.forward(random.random()*1.0) for each “step” in it’s overall path. Modify the code by adding a for loop of range(10) and track t1.

The for loop will be replaced by while loop based on the distance t1 is from the origin. Therefore, you need to write a function called t_distance(x, y) that returns the distance t1 is from the origin. The parameters \(x\) and \(y\), the current coordinates of t1, can be determined using the turtle.position() method. It returns the turtle’s coordinates as an ordered pair, called a “tuple,” with structure (x, y). You can “extract” the \(x\) coordinate using t1.position()[0] and the \(y\) coordinate using t1.position()[1].

Make the modifications so that the while will terminate when t1’s distance is greater than or equal to 15 feet.

Once that works, add another turtle, with a different color, and allow the while loop to run until at least one of the turtles crosses the 15-foot finish circle. Give your second turtle different path-determining features for its direction and step length.

Next, consider what to do in case the turtles are about to, or do, collide. It is likely that the paths of one or both turtles will be influenced be a collision or near collision. Include some appropriate selection code predicated on the distance between the two turtles.

import turtle
import random
import sys


def draw_x_axis(t, x_min, x_max):
    t.up()
    t.goto(x_min, 0.0)
    t.down()
    t.goto(x_max, 0.0)
    t.up()


def draw_y_axis(t, y_min, y_max):
    t.up()
    t.goto(0.0,y_min)
    t.down()
    t.goto(0.0,y_max)
    t.up()
    
    
def draw_circle(t, rad):
    t.home()
    t.goto(0,-rad)
    t.down()
    t.circle(rad, steps = 50)
    t.up()
    
    
def main():
    sys.setExecutionLimit(50000)
    wn = turtle.Screen()
    t1 = turtle.Turtle()
    x_min = -20
    x_max = 20
    y_min = -20
    y_max = 20
    wn.setworldcoordinates(x_min, y_min, x_max, y_max)
    draw_x_axis(t1, x_min, x_max)
    draw_y_axis(t1, x_min, x_max)
    for radius in [5, 10, 15]:  
        draw_circle(t1, radius)
    t1.home()
    t1.shape('turtle')
    t1.color('blue')
    # start the turtle path loop here  
    
    # at the end
    wn.exitonclick()       
        
           
main()  
\(\boxdot\) Homework Problem - “Bubble Sort”
  • The code for quickly switching the order of two consecutive list elements is:

    list_in[i], list_in[i+1] = list_in[i+1], list_in[i]  
  • Here is a Wikipedia link to the bubble sort algorithm : Bubble Sort

Sections 8.5 - 8.8

  • Newton’s Method is one application of the while loop

    def newton_sqrt(x, tol):  
        approx = 0.5 * x 
        better = 0.5 * (approx + x/approx) 
        while abs(better - approx) > tol: 
            approx = better
            better = 0.5 * (approx + x/approx)    
        return better  
    
    
    def main():  
        x = 10  
        sr_of_x = newton_sqrt(x, 0.0001)  
        print(x, sr_of_x, sr_of_x**2)  
    
    
    main()  
  • Activity 3: Copy and paste the Newton’s method code shown above into the active code window for activity 3.

  • This example offers another way to gage exactness and terminate the while loop

  • Perhaps … may want to include a limit just in case using the iteration accumulator … at least until you are confident the indefinite loop will never and up being an infinite loop

    • Use the fact that the exactness of the approximate value of \(\sqrt{x} = better\) can be tested by comparing \(better^2\) to \(x\) in the while loop.

    • Modify the while loop so that it will not go on infinitely by incorporating an iteration accumulator.

  • Sentinal Values and validating input - two more ways for which while loops are useful.

  • Activity 4: Write a program that includes the function prompt_and_sum() that prompts the user for input of a floating point number from the interval [1, 10]. The program sums the inputs. The program terminates if a 0 is input. If any other number outside the interval is input, the program gently reminds the user of the to input a valid number or 0 if the user wants the process to terminate.

\(\boxdot\) Homework Problem - “Bisection Method”
  • Root-finding technique

  • \(x_r\) is called a root of the function \(f(x)\) if \(f(x_r) = 0\).

  • If \(f\) has a continuous (unbroken) graph and \(f(a) * f(b) < 0\), then \(f\) has at least one root \(x_r\) within the interval \([a, b]\).

  • To gerneralize this concept and place it within a while loop:

    while abs(f(x_new)) > tol:
        x_new = 0.5*(a + b)
        if f(x_new) == 0.0:
            return x_new
        if f(x_new) * f(a) < 0:    # then x_r is in [a, x_new], set b = x_new and continue the "while loop"
            .
            .
    
        else:                      # then x_r is in [x_new, b], set a = x_new and continue the "while loop"
            .
            .
    
    return x_new
  • Here is a Wikipedia link to the bisection algorithm : Bisection Method

Sections 8.9 - 8.12

\(\boxdot\) Printing Simple Lists
  • Using the tab feature : '\t'

    print("(something)", '\t', "(something else)")
  • Activity 5: Write a program that includes the function called sum_of_n(n) where \(n\) is a positive integer, and the function sums the integers \(1, 2, 3, ..., n-1, n\). The function prints the results in a simple list using the tab feature. The first column is the number in the sequence and the second number is the partial sum to that value.

\(\boxdot\) The image module
  • Python’s image module has two classes (types of objects): Image and Pixel

    • an Image is an \(m\) x \(n\) grid, or array, of locations.

      • \(m\) = number of columns (the vertical dimension of the array)

      • \(n\) = number of rows (the horizontal dimension of the array)

      • NOTE: most mathematicians prefer the row dimension be given first

    • create an Image object in two ways:

      • my_image = image.Image(file_name), where “file_name” is some appropriately formatted image file

      • my_image = image.EmptyImage(ncols, nrows), a new all-white pixel image is created with ncols columns and nrows rows

    • Each location has an assigned Pixel

      • a Pixel can be created a couple of ways:

        • p = img.getPixel(col, row) - pixel p is created by accessing a pixel from the Image object img

        • p = image.Pixel(R, G, B) - where R, G, B are int objects used to assign a color to the pixel

      • Pixel locations are referenced by their column number (first) and row number (second), each indexed beginning with 0.

      • locations, or pixels, are systematically accessed by using nested loops

        for c in range(cols):  
            for r in range(rows):  
                Python STATEMENTS
      • the color of a pixel in an image is determined by using the RGB Color Model

      • (R, G, B) is an ordered triple of integers between 0 and 255

        • R = red

        • G = green

        • B = blue

      • the larger the number, the greater the intensity of the color

        • Pixel(255, 0, 0) is a bright red color (the intensities for G and B are zero)

        • Pixel(0, 0, 0) = black

        • Pixel(255, 255, 255) = white

  • refer to the text for the basic methods associated with each of these classes

  • Activity 6: Write a program that loads the image of the Luther Bell and uses a function called switch_colors() that systematically switches the RGB Color Model for each pixel so that new Red = old Green, new Green = old Blue and new Blue = old Red. The function returns the new image to be drawn in the main routine. Use the ActiveCode window for Exercise 8.10 of the text.

    import image
    import sys
    
    
    def switch_colors(image_in):
        .
        .
        .
    
        return image_in
    
    
    def main():
        sys.setExecutionLimit(80000)
        bell_img = image.Image("luther.jpg")
        win = image.ImageWin(bell_img.getWidth(), bell_img.getHeight())
        bell_img.draw(win)
        # new_image = switch_colors(bell_img)
        # new_image.draw(win)
        win.exitonclick()
    
    
    main()
  • Activity 7: Modify the image processing code so that it swaps rows of pixels for columns of pixels. That is, column 0 of the new image is row 0 of the original image, etc. This is sometimes referred to as the transpose of an array. Does it work like you expected? If not, how would you change it to make it correct?