15-112 Fall 2012 Optional Quiz B, Part 2 (non-autograded)
* 20 Minutes. No
calculators, no notes, no books, no computers.
* 50 pts [5/5=50, 4/5=45, 3/5=35, 2/5=25, 1/5=15, 0/5=0]
What will the following print?
def f1(a):
b = [ ]
for v in a:
x = a[v%len(a)]
if (x < v):
b += [(v,x)]
elif (x == v):
b.append("x=" + str(x))
return b
print f1([6,5,4,3])
def f2(a,b,c):
(d,e) = (c, b+[])
f = e + e
d[0] = 2
e[0] = 3
e.append(4)
f[1] = 5
print a, b, c, d, e, f
a = [1]
(b,c) = (a,[1])
f2(a,b,c)
def f3():
x = 0
while True:
a = [int(i) for i in ([str(x)*x]*x)]
if (sum(a) > 1000):
return x
x += 1
print f3()
For each of the following
functions, find values of the parameters so that the functions will return True.
def f4(a):
assert((type(a) == list) and (a[0] == len(a) == 4))
for x in a: assert((type(x) == int) and (100 > x > 0))
s = "".join([str(x) for x in a])
return ((len(s) == 6) and
([i%min(a) for i in a] == range(4)) and
(a[1] > 10) and
(int(s[0:2]) == a[3]))
import string
def f5(n):
# hint: ord("A") == 65, ord("a") == 97, ord("!") == 33
assert(1000 > n > 0)
p = ord('a')
for c in string.ascii_lowercase:
for d in str(ord(c)): p *= int(d)
if (p < ord('a')):
return (n == ord(c))
return False
Bonus / 5 pts: What will the following print?
def fbonus(s,b):
# hint: ord("A") == 65, ord("a") == 97, ord("!") == 33
if (b): s = s.lower()
t = sorted([ord(c) for c in list(s) if c.isalpha()])
t = [t[0]] + [t[i] for i in xrange(1,len(t)) if (t[i] != t[i-1])]
mc = chr(t[len(t)/2])
return "".join([c for c in s if ((c.isalpha()) and (c < mc))])
print fbonus("aceD FAB!",False)
print fbonus("acED FAB!",True)