CSC15 Final Exam Study Guide Practice problems. (Sample solutions to be posted) 1. Write a function to reverse a string (non-destructively). For example, reverse("abcd") should return "dcba" def reverse(S): R = "" # string to be constructed i = 0 while ioccurs(A[i],B): answer = False i += 1 return answer 2c. (mega-challenge). Write a version of sublist that also respects the order of appearence of the elements, so sublist([4,2,1],[3,4,1,5,2]) should return False, because 4,2,1 do not appear in the same order in the second list. (the best solution was due to Paras Patel). def sublist3(A,B): i, j = 0 answer = True while i A[i+1]: answer = False i +=1 return answer #sorted. 4. Write a function 'substringcount' that counts the number of times the substring A occurs in the string B. For example, substringcount("aba","aababa") should return 2, since two subtrings, both equal to "aba", are found in the second list. Note that the substrings can overlap. Note: there is the following built-in operation that finds substrings: s.find(sub): Returns the lowest index in s where substring sub is found. Returns -1 if sub is not found. But you'll have to decide to use it or write your function from scratch. # first version: def subcount(A,B): j = 0 # indexes B count = 0 # counts substrings while j otherpc.cpuclock and self.ram > otherpc.ram: return True else: return False #PC mypc = PC("core2 quad",2.4,4096,1000,"nvidia 8600GT") yourpc = PC("pentium 3",1.0, 256, 20, "ati mach64") yourpc.upgrade(128,20) % add 128 megs and 20 gigs mypc.overclock(0.25) # overclock by 25% mypc.changevideo("nvidia 8800GTx") if mypc.betterthan(yourpc): print "my pc is better than your pc" ---- 7. # Determine the output of the following program fragments and explain why. # i A = [2,4,6] def f(B): B = [1,3,5] # f f(A) print A prints [2,4,6]. Nothing was changed, B is a local variable (which is a pointer). # ii. Draw a memory-allocation diagram at the point indicated. x = 0 A = [2,4,6] def f(B,x): x = x+1 B[1] = x B = [7,8,9] # draw stack-heap allocation diagram for this point #f f(A,x) print x, A[1] prints 0, 1 # change to B[1] was made before B was reassigned. # Memory allocation diagrams must be clear as to what delineates stack frames, # the content of each stack frame. And for pointers, where they point to. #iii class AA: def __init__(t,x): t.x = x t.y = 0 # init def f(self,a): self.y = a + self.x # f def g(s,B): if s.x+s.y > B.x+B.y: return True else: return False #g #AA A = AA(3) B = AA(4) A.f(3) if A.g(B): print "yes" # prints yes print A.y, B.y # prints 6,0 #iv k = 0 while k < 4: j = ord("A")+k # ord("A") is 65 while j <= ord("D"): # ord("D") is 68 print chr(j), # note , (no new line) j +=1 # while j k += 1 print "" # prints new line # while k output: A B C D B C D C D D #v def f(x): if x<2: return x else: return f(x-1) + x #f print f(6) prints 21 (1+2+3+4+5+6) ### In addition to these problems, don't forget to review the midterm exam.