Computer Science 15-110, Fall 2010
Class Notes: Recitation 3
- Quiz 2
- Practice Tracing
- Practice Mystery Methods
- Practice Problems using While Loops
Recitation 3
- Quiz 2
Quiz 2 will be administered at the start of recitation.
- Practice Tracing
a)
# trace this code by hand, then run it to confirm your prediction
x = 12
y = 2
while (y <= x):
print x,y
x -= 2
y += 3
print x,y
b)
# trace this code by hand, then run it to confirm your prediction
s = "abcde"
while (len(s) < 15):
print s
s += "-" + str(len(s))
print "Done, and s =",s
- Practice Mystery Methods
a)
def mysteryA(x):
return (((x % 2) > 0) != (x > 0))
b)
def mysteryB(x, y, z):
return x + y + z - max(x,y,z) - min(x,y,z)
c)
def mysteryC(x, y):
a = min(x,y)
b = max(x,y)
c = 0
while (a <= b):
d = int(round(a**0.5))
if (d*d == a):
# print a # uncomment-out this line for debugging help!
c += 1
a += 1
return c
d)
# If there’s time at the end of recitation, come back to this problem:
def mysteryD():
c = 0
input = "!" # why do this?
s = ""
while (s.find(str(input)) < 0):
s += str(input)
c += 1
input = "-" + raw_input("Enter an integer: ") + "-"
return c
- Practice Problems Using While Loops
In each of the following problems, use "while" loops even if a "for" loop may be more intuitive.
- functionsRace
Study the functionsRace function in the notes. Q: by inspection, determine the value of finishLine that produces a tie.
def functionsRace(finishLine):
print "Functions race!"
print "Function 1: y1 = 10 * x + 50"
print "Function 2: y2 = x * x - 100"
print "x\ty1\ty2"
x = 0
y1 = 0
y2 = 0
# while loop with conjunct condition
while (y1 < finishLine and y2 < finishLine):
y1 = 10 * x + 50
y2 = x * x - 100
print "%d\t%d\t%d" % (x, y1, y2)
x += 1
if (y1 > y2):
print "Function 1 wins!"
elif (y1 < y2):
print "Function 2 wins!"
else:
print "It's a tie!"
- largestInput()
Write the function largestInput(): this takes
no parameters, repeatedly reads integers from the user (stopping when
the user enters -1), and returns the largest value input.
- kthLetter(string, k)
Write
the function kthLetter(string, k): this returns the kth letter in
the given string, and returns None if there are not k letters in the string. Note that this function only counts letters (A-Z,a-z) and not any other characters
(digits, punctuation, spaces, etc). So, kthLetter("abc",1)
returns "b", as you'd expect (it's 0-based, after all), but
kthLetter("a-1, b-2, c-3", 1) also returns "b".
- vowelCount(string)
Write the function vowelCount(string): this returns the number of vowels in the string
- kthDigit(n, k)
Write
the function kthDigit(n, k): this returns the kth digit in the
integer n. returns -1 if k >= # of digits in n.
- isPrime(n) and nthPrime(n)
Only if time is permitting, write the functions isPrime(n) and nthPrime(n).
carpe diem -
carpe diem - carpe diem - carpe diem
- carpe diem - carpe diem -
carpe diem - carpe diem - carpe
diem