Computer Science 15-110, Fall 2010
Class Notes: "for" Loops and Infinite Loops
- "for" loops
- "for" loop over a range
- Range from 0 to y: use range(y+1)
- Range from x to y: use range(x, y+1)
- Range from x to y with step z: use range(x, y+1, z)
- Range in reverse (use a negative step)
- "for" loop over a String
- Without an index
- With an index
- the old-fashioned way
- the newfangled way (with enumerate)
- Nested loops
- Infinite "while" loop with break
- Practice Problems
- Sum the numbers from 1 to N
- Sum the odd numbers from 1 to N
- Using "if"
- Using a different increment
- Sum the first N odd numbers
- Reverse a String
- isPrime
- fasterIsPrime
- nthPrime
"for" Loops and Infinite Loops
"for" loops
- "for" loop over a range
- Range from 0 to y: use range(y+1)
# print the numbers from 0 to 4 (not 5)
for x in range(5):
print x
- Range from x to y: use range(x, y+1)
# print the numbers from 10 to 14 (not 15)
for x in range(10, 15):
print x
- Range from x to y with step z: use range(x, y+1, z)
# print the even numbers from 10 to 14 (not 15)
for x in range(10, 15, 2):
print x
- Range in reverse (use a negative step):
# print the even numbers from 14 to 10 (not 9)
for x in range(14, 9, -2):
print x
- "for" loop over a String
- Without an index
# print each character in a String
for ch in "Wow!":
print ch
- With an index
- the old-fashioned way
# print every other character in a String
s = "Amazing!"
for i in range(len(s)):
if (i % 2 == 0):
print s[i]
- the newfangled way (with enumerate)
# print every other character in a String
s = "Amazing!"
for i, ch in enumerate(s):
if (i % 2 == 0):
print ch
-
Nested loops
n = int(raw_input("How many rows? "))
for row in range(n):
for col in range(row+1):
print "*",
print
- Infinite "while" loop with break
while (True):
response = raw_input("Enter a string (or 'done' to quit): ")
if (response == "done"):
break
print " You entered: ", response
print "Bye!"
- Practice Problems
- Sum the numbers from 1 to N
def sumFrom1ToN(n):
sum = 0
for i in range(n+1):
sum += i
return sum
# let's see it in action...
for n in range(-2,6):
print n, sumFrom1ToN(n)
- Sum the odd numbers from 1 to N
- Using "if"
def sumOddsFrom1ToN(n):
sum = 0
for i in range(n+1):
if (i % 2 == 1):
sum += i
return sum
# let's see it in action...
for n in range(-2,6):
print n, sumOddsFrom1ToN(n)
- Using a different increment
def sumOddsFrom1ToN(n):
sum = 0
for i in range(1, n+1, 2):
sum += i
return sum
# let's see it in action...
for n in range(-2,6):
print n, sumOddsFrom1ToN(n)
- Sum the first N odd numbers
def sumOfFirstNOdds(n):
sum = 0
for i in range(n):
sum += 2*i+1
return sum
# let's see it in action...
for n in range(6):
print n, sumOfFirstNOdds(n)
Or...
def sumOfFirstNOdds(n):
sum = 0
for i in range(1,2*n+1,2):
sum += i
return sum
Or...
def sumOfFirstNOdds(n):
sum = 0
nextOdd = 1
for i in range(n):
sum += nextOdd
nextOdd += 2
return sum
Once more, this time with a bug...
def sumOfFirstNOdds(n): # This version has a bug!
sum = 0
for i in range(n):
sum += 2*n+1
return sum
- Reverse a String
def reverse(s):
rev = ""
for ch in s:
rev = ch + rev
return rev
# let's see it in action...
print reverse("abcdefg")
print reverse("How do you know when it's time to tune your bagpipes?")
- isPrime
#Note: there are faster/better ways. We're just going for clarity and simplicity here.
def isPrime(n):
if (n < 2):
return False
for factor in range(2,n):
if (n % factor == 0):
return False
return True
# And take it for a spin
for n in range(500):
if isPrime(n):
print n,
- fasterIsPrime
#Note: this is still not the fastest way, but it's a nice improvement.
def fasterIsPrime(n):
if (n < 2):
return False
if (n == 2):
return True
if (n % 2 == 0):
return False
maxFactor = int(round(n**0.5))
for factor in range(2,maxFactor+1):
if (n % factor == 0):
return False
return True
# Verify these are the same
for n in range(1000):
if (isPrime(n) != fasterIsPrime(n)): print n
assert(isPrime(n) == fasterIsPrime(n))
print "They seem to work the same!"
# Now let's see if we really sped things up
import time
bigPrime = 499 # Try 1010809, or 10101023, or 102030407
print "Timing isPrime(",bigPrime,")",
time0 = time.time()
print ", returns ", isPrime(bigPrime),
time1 = time.time()
print ", time = ",(time1-time0)*1000,"ms"
print "Timing fasterIsPrime(",bigPrime,")",
time0 = time.time()
print ", returns ", fasterIsPrime(bigPrime),
time1 = time.time()
print ", time = ",(time1-time0)*1000,"ms"
- nthPrime
def nthPrime(n):
found = 0
guess = 0
while (found <= n):
guess += 1
if (isPrime(guess)):
found += 1
return guess
# and let's see a list of the primes
for n in range(10):
print n, nthPrime(n)
carpe diem -
carpe diem - carpe diem - carpe diem
- carpe diem - carpe diem -
carpe diem - carpe diem - carpe
diem