# practp1_sol.py # spring 2016 CS 1110 profs # Mar 2016 # Answers and "proofs of correctness" for the practice exam. # Answers are in this file, sometimes presented as comments. # You can also run this file in order to verify that the solutions are correct, # but not all answers are printed. So, don't depend on the results of # running this file; READ this file! # This file is non-standardly organized, with interleaved function definitions a # and statements to execute. # However, the advantage for students is that the code and comments are organized in # the same linear order as the questions in the practice exam. ### print 'Running Q1a' def Q1(s): """ Returns True if the first half of s is exactly same as the second half of s. PreCondition: s is a non-empty string with even length. """ m = len(s)/2 return (s[:m] == s[m:]) # We make use of *lists* to test code. You haven't learned about lists yet, # but boy are they convenient. # Think of a list as indexable like a string is, but instead of having # a character in each position, you can have anything you want in each # position. print 'testing Q1a' # Each item in the list starts with a sample input and ends with the # output that *should* be given. for answer in [ ['aa', True], ['ab', False], ['aaab', False], ['abcabc', True]]: response = Q1(answer[0]) right = answer[1] if response != right: print ('test: ' + str(answer[0]) + ' response was' + str(response)) print 'done testing Q1a\n' ## print 'running Q1b' for s in ['aa', 'ab', 'abaa']: print '\t', s, s.count(s[0]) == len(s) - 1 print 'ANSWER: everything but one position in the string is the same as s[0]\n' ## print 'running Q1c: should get True if s is correct' s='xaxx' result = s.find('xx') > s.find('x') and s.find('x') >= 0 print '\t', 's is', s, 'and result is', result, '\n' ### print 'running Q2a' for N in [4]: N=4 print '\tN is', N s1=0 s2=0 for k in range(1,N+1): print '\tk is', k if (k % 2) == 0: s1 = s1+k # sum of evens else: s2 = s2+k # sum of odds print '\ts1 is', s1, 's2 is', s2 print '\t Answer is', s2-s1, '\n' # 1 2 3 4 5 6 ... N # 1 - 2 + 3 - 4 + 5 - 6 print '\t general solution: -1*(N/2) if N even; -1*(N/2) + N if N odd\n' ## print 'running Q2b, should get True' sfor1 = '' # accumulate for-loop string to check sfor2 = '' swhile = '' # accumulate while-loop string to check against k = 0 while k<=100: swhile+=str(k) k=k+5 # one possible solution for k in range(0, 101, 5): sfor1+= str(k) for k in range(21): # k's last value will be 20 sfor2+= str(k*5) print '\tsame result? ' + str(sfor1==swhile and sfor2==swhile) + '\n' ## print 'Running Q2c, should not see any warnings' # It returns the "singleton" characters in s, in order of appearance # ("singleton" means "occurs exactly once") def F(s): """ PreCondition: s is a non empty string """ t = '' # Empty string for c in s: if s.count(c)==1: t = t+c return t for answer in [ ['aa', ''], ['ab', 'ab'], ['aaab', 'b'], ['dababc', 'dc']]: response = F(answer[0]) right = answer[1] if response != right: print ('test: ' + str(answer[0]) + ' response was' + str(response)) print ### print 'running Q3a, should get no warnings' # solution with a loop def FarAway1(T,r,k): """Returns true if and only if the robot's distance to (0,0) is greater than r just after it takes step k. PreC: T is a travel string, k is an int that satisfies 0<=k r # solution without a loop def FarAway2(T, r, k): """same spec as FarAway1.""" from math import sqrt substr = T[:k+1] x = substr.count('E') - substr.count('W') y = substr.count('N') - substr.count('S') return r < sqrt(x**2 + y**2) def FarAway3(T,r,k): """same spec as FarAway1.""" from math import sqrt xj = 0; yj = 0 j = 0 # j represents the step just taken. # update the coordinates while j <= k: if T[j] == 'N': yj+=1 elif T[j] == 'E': xj+=1 elif T[j] == 'S': yj-=1 elif T[j] == 'W': xj -= 1 j+=1 #when here, j = k+1, but xj and yj aren't the k+1 positions. return sqrt(xj**2 + yj**2) > r def FarAway4(T,r,k): """same spec as FarAway1.""" from math import sqrt j = 0 # j represents the step just taken. if T[j] == 'N': xj=0; yj=1 elif T[j] == 'E': xj=1; yj=0 elif T[j] == 'S': xj=0; yj= -1 elif T[j] == 'W': xj = -1; yj = 0 # take the next step while j < k: j+=1 if T[j] == 'N': yj+=1 elif T[j] == 'E': xj+=1 elif T[j] == 'S': yj-=1 elif T[j] == 'W': xj -= 1 #@ debug: print "in FarAway4: k is", k, "j is", j #when here, j = k+1, but xj and yj aren't the k+1 positions. return sqrt(xj**2 + yj**2) > r for answer in [ ['NSNE', 1, 3, True], ['NSNE', .5, 2, True], ['NSNE', 1, 1, False], ['NSNE', 1, 0, False], ['NSNE', .5, 0, True], ['NSNW', 1, 3, True]]: for fn in [FarAway1, FarAway2, FarAway3, FarAway4]: response = fn(answer[0], answer[1], answer[2]) right = answer[3] if response != right: print '\tWarning:', fn, 'wrong on', answer[0], answer[1], answer[2] print '' ## print 'running Q3b, should get no warnings' # common solution def NotFarAway1(T,r): """ Returns an int that is the total number of good steps. PreC: T is a travel string.""" goodsteps = 0 for step in range(len(T)): if FarAway2(T,r,step): goodsteps += 1 return goodsteps # more compact solution def NotFarAway2(T,r): """ Returns an int that is the total number of good steps. PreC: T is a travel string.""" goodsteps = 0 for step in range(len(T)): goodsteps += FarAway2(T,r,step) # this uses a trick return goodsteps for answer in [['NSNE', .5, 3], ['NSNE', 1, 1]]: for fn in [NotFarAway1, NotFarAway2]: response = fn(answer[0], answer[1]) right = answer[2] if response != right: print '\tWarning:', fn, 'wrong on', answer[0], answer[1] print '' ### print 'running Q4a. Assume d has been defined and set to an int.' d = 3 # for this problem, doesn't matter what d is, as long as defined x = 7.0 print '\t7.0 works?', x == x-(x/d)*d+7 x = 7 print '\tBut 7 doesn\'t work?', x != x-(x/d)*d+7, '\n' ## print 'running Q4b' # the idea is to have (y/z) somehow be weird b/c of int arithmetic. x = 2; y = 3; z = 2 print '\tSuppose x,y,z are', x, y, z print '\t(x*y)/z is', (x*y)/z, 'but x*(y/z) is', x*(y/z) print '\t if we convert everything to float, here\'s what happens:' x = float(x); y = float(y); z = float(z) print '\t(x*y)/z is', (x*y)/z, 'and x*(y/z) is', x*(y/z),'\n' ## print 'Running Q4c' # Note that F returns 1st argument. def F(x,y): u = x+2*y print x,y,u return x x = 1 y = 10 u = 0 print x,y,u y = F(y,x)+F(2*x,y) print x,y,u # Consider using the Online Python Tutor, http://www.pythontutor.com # Application Script: x: 1 y: 10, u: 0 # ---------> prints out 1 10 0 # First call to F: # In F, x gets AS's y = 10; y gets AE's x=1 # So, in F, x:10 y:1 # So, in F, u: 12 # So, in F, ---------> prints out 10 1 12 # F returns its x which is 10 # So in application script, first term in sum is 10 # Second call to F: # In F, x gets 2*AS's x, which is 1; y gets AE's y, which is 10 # So, in F, x: 2 y:10 # So, in F, u: 22 # So, F -------------> prints out 2 10 22 # F returns its x which is 2 # So in application script, second term in sum is 2 # So now, in application script, x:1 y:12 u:0 # ----------------> prints out 1 12 0 print '' ## # Q4d: F has parameters x, y and local variable u. These are manipulated # in the indented portion of the reasoning comments above. ### import SimpleGraphics print 'running Q5' SimpleGraphics.MakeWindow(8) x = -5 y=0 r=2 alfa = .75 # we didn't need alpha in this question SimpleGraphics.DrawDisk(x,y,r) for k in range(7): ################################################## x += (1.75)*r r = .75*r ################################################## SimpleGraphics.DrawDisk(x,y,r) SimpleGraphics.ShowWindow() ### print 'running Q6' def ThreeDigit(n): """Returns a length-three string that encodes the integer n. Leading zeros are included if necessary, e.g., '000', '001', '012'. Precondition: n is an integer that satisfies 0<=n<=999. """ if n > 99: # don't need to pad with zeroes return str(n) elif n > 9: # pad with a single zero return '0' + str(n) else: return '00' + str(n) print 'testing Q6' for answer in [ [0,'000'], [1,'001'], [8,'008'], [9,'009'], [10,'010'], [11,'011'], [29,'029'], [89, '089'], [99, '099'], [100,'100'], [101,'101']]: response = ThreeDigit(answer[0]) right = answer[1] if response != right: print '\tWarning: ThreeDigit', 'wrong on', answer[0], 'said', answer[1] print 'all done'