Basic Iteration


CS 1109


July 6th, 2023

Administrative

  • Assignment 2 is due Monday, July 10th at 9PM
  • Fill out Celeste's OH survey
  • Reading for Friday:
    • Think Python: 7.1-2, 8.3, 8.6-7, 10.3, 10.7

Iteration

What is iteration?

Doing something repeatedly.

Examples

  1. Do something \(n\) times
    • Run an experiment 1,000,000 times
    • Draw 6 random numbers for the lottery
  2. Process each item in a sequence
    • Compute aggregate statstics (e.g., mean, median, std. dev.) on test scores
    • Send an email to everyone in a group
  3. Do something an unknown number of times
    • Move robot forward 1ft. until it hits a wall
    • Ask for password until password is correct

Definite Iteration

Repeat doing something a known number of times.

Examples:

  1. Do something \(n\) times
    • Run an experiment 1,000,000 times
    • Draw 6 random numbers for the lottery
  2. Process each item in a sequence
    • Compute aggregate statstics (e.g., mean, median, std. dev.) on test scores
    • Send an email to everyone in a group

Indefinite Iteration

Keep doing something until something happens.

  • Examples
    • Move robot forward 1ft. until it hits a wall
    • Ask for password until password is correct

Definite Iteration

Motivating Example: Estimating \(\pi\)

dart.jpg

Throw darts!

Motivating Example: Estimating \(\pi\)

dart.jpg

  • Red if inside circle

Motivating Example: Estimating \(\pi\)

dart.jpg

  • Red if inside circle
  • Green if outside circle

Motivating Example: Estimating \(\pi\)

Area of Square: \(2 \times 2 = 4\)

Area of Circle: \(\pi \times 1^2 = \pi\)

\[ \frac{\text{Area of Circle}}{\text{Area of Square}} = \frac{\pi}{4} \]

Motivating Example: Estimating \(\pi\)

\[ \frac{\text{Area of Circle}}{\text{Area of Square}} = \frac{\pi}{4} \]

If we throw \(N\) darts: \[ \pi \approx \frac{4 \times {\color{red}{\text{# darts in circle}}}}{{\color{green}{\text{# darts in square}}}} \]

Motivating Example: Estimating \(\pi\)

Algorithm in English:

  • For each of \(N\) trials
    • Throw a dart
    • If the dart lands in the circle
      • Add 1 to the total number of hits
  • \(\pi\) is approximately \(4 \times (\color{red}{\text{hits}} / N)\)

Motivating Example: Estimating \(\pi\)


n = 1000 # number of darts to throw
hits = 0 # number of darts that land inside circle







pi_est = 4.0 * hits / n
print("pi is approximately:", pi_est)

Motivating Example: Estimating \(\pi\)


n = 1000 # number of darts to throw
hits = 0 # number of darts that land inside circle
for k in range(n):






pi_est = 4.0 * hits / n
print("pi is approximately:", pi_est)

Motivating Example: Estimating \(\pi\)


n = 1000 # number of darts to throw
hits = 0 # number of darts that land inside circle
for k in range(n):
		# Throw kth dart


		# Did the dart land in the circle?


pi_est = 4.0 * hits / n
print("pi is approximately:", pi_est)

Motivating Example: Estimating \(\pi\)

from random import uniform
n = 1000 # number of darts to throw
hits = 0 # number of darts that land inside circle
for k in range(n):
		# Throw kth dart
		x = uniform(-1, 1) 
		y = uniform(-1, 1) 
		# Did the dart land in the circle?


pi_est = 4.0 * hits / n
print("pi is approximately:", pi_est)

Motivating Example: Estimating \(\pi\)

from random import uniform
n = 1000 # number of darts to throw
hits = 0 # number of darts that land inside circle
for k in range(n):
		# Throw kth dart
		x = uniform(-1, 1) 
		y = uniform(-1, 1) 
		# Did the dart land in the circle?
		if x**2 + y**2 <= 1:
				hits = hits + 1
pi_est = 4.0 * hits / n
print("pi is approximately:", pi_est)

Motivating Example: Estimating \(\pi\)

from random import uniform
n = 1000 # number of darts to throw
hits = 0 # number of darts that land inside circle
for k in range(n):
		# Throw kth dart
		x = uniform(-1, 1) 
		y = uniform(-1, 1) 
		# Did the dart land in the circle?
		if x**2 + y**2 <= 1:
				hits = hits + 1
pi_est = 4.0 * hits / n
print("pi is approximately:", pi_est)

Let's try it out!

for-loops

Syntax

for <variable> in <sequence>:
		<statement>
		...
		<statement>

Key Concepts

  1. Loop Sequence: a set of values (e.g., range, a list, a string)
  2. Loop Variable: takes on one value of sequence at a time
  3. Loop Body: statements which are executed every time loop variable takes on one value from the sequence

Execution of for-loops

for x in seq:
		print(x)

Python Tutor

https://cs1110.cs.cornell.edu/tutor

Repeating something \(n\) times

range()

  • range gives you an int sequence
  • Syntax similar to slices

General Usage

range(n)     # 0, 1, ..., n-1
range(a,b)   # a, a+1, ..., b-1
range(a,b,s) # a, a + s, a + 2s, ..., <= b-1

range() Examples

range(4)        --> 
range(-3, 2)    --> 
range(3, 4)     --> 
range(3, 3)     --> 
range(1, 6, 2)  --> 
range(6, 0, -2) --> 
range(6, 0, 2)  --> 

range() Examples

range(4)        --> 0, 1, 2, 3
range(-3, 2)    --> -3, -2, -1, 0, 1
range(3, 4)     --> 3
range(3, 3)     --> # empty sequence, not error!
range(1, 6, 2)  --> 1, 3, 5
range(6, 0, -2) --> 6, 4, 2
range(6, 0, 2)  --> # empty sequence, not error!

Pattern: Doing something \(n\) times

n = _______
for k in range(n):
		# Code that does "something" here...

Example: Print first 10 powers of 2

n = 10
for k in range(n):
		print(2**k)

Let's try it out on Python Tutor!

for-loops and empty sequences

Program A

for k in range(3,4):
		print(k)
print('Out of loop')

Output

3
Out of loop

Program B

for k in range(3,3):
		print(k)
print('Out of loop')

Output

Out of loop

Repeating something for every element of a sequence

for-loops & Strings

Recall the structure for for-loops:

for x in seq:
		print(x)

seq can be any sequence!

for-loops & Strings

Program:

for letter in 'ABCDE':
		print(letter + '!')

Output:

A!
B!
C!
D!
E!

for-loops & lists

Program:

names = ['Alice', 'Bob', 'Eve']
for name in names:
		print('Hi, ' + name + '!')

Output:

Hi, Alice!
Hi, Bob!
Hi, Eve!

Loop Patterns

Pattern: Counting

Write a for-loop to count the number of letters in s:

s = 'pneumonoultramicroscopicsilicovolcanoconiosis'




Pattern: Counting

Write a for-loop to count the number of letters in s:

s = 'pneumonoultramicroscopicsilicovolcanoconiosis'
count = 0 # Number of letters


print('There are', count, 'letters in s.')

Pattern: Counting

Write a for-loop to count the number of letters in s:

s = 'pneumonoultramicroscopicsilicovolcanoconiosis'
count = 0 # Number of letters
for letter in s:
		count = count + 1 # Add 1 to the count
print('There are', count, 'letters in s.')

Pattern: Counting

General Pattern

count = 0 # Variable to store count in outside of loop
# Loop over each element in sequence:
for k in seq_to_count: 
		# Increment count by 1 for each element
		count = count + 1  

Pattern: Accumulator

Write a for-loop to compute the sum of a list:

nums = [3, 17, -2, 42, 101, -21]





Pattern: Accumulator

Write a for-loop to compute the sum of a list:

nums = [3, 17, -2, 42, 101, -21]
sum_so_far = 0 # Current sum



print('The sum is', sum_so_far)

Pattern: Accumulator

Write a for-loop to compute the sum of a list:

nums = [3, 17, -2, 42, 101, -21]
sum_so_far = 0 # Current sum
for n in nums:
		# Add n to sum
		sum_so_far = sum_so_far + n
print('The sum is', sum_so_far)

Pattern: Accumulator

General Form

accum = 0 # Variable to store result
# Loop over each element in sequence:
for x in seq:
		# Modify accumulated value using <OP> (e.g., +, *, -)
		accum = accum <OP> x

Called the accumulator pattern as you "accumulate" your result inside of a loop

Review

  • for-loops are a form of definite iteration
    • Repeat something a known number of times
  • range() gives you an int sequence

    range(3)       --> 0, 1, 2
    range(1, 5)    --> 1, 2, 3, 4
    range(0, 4, 2) --> 0, 2
    
  • Use for-loop to do something to every element of a string or list

    # Prints each element of list
    for x in [3, 42, -2, 5]:
    		print(x)
    
  • Two looping patterns: counting and accumulator