








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Various implementations of recursive and loop functions, along with examples and hints for further practice. Topics include merge functions, skip functions, defining classes, and partition algorithms. Additional resources for practice problems are also provided.
Typology: Slides
1 / 14
This page cannot be seen from the preview
Don't miss anything!









def skip(s): """Returns: copy of string s, odd letters(i.e., 1 st , 3 rd , 5 th ) dropped. Example: 'abcd' -> 'bd'. '' -> '' 'abc' -> 'b', 'zzz' -> 'z' """ if len(s) <= 1: # One base case return '' else: # s >= 2 characters (if exactly 2, another base case) return s[1] + (skip(s[2:]) if len(s) > 2 else '')
def skip(s): """Returns: copy of string s, odd letters(i.e., 1 st , 3 rd , 5 th ) dropped. Example: 'abcd' -> 'bd'. '' -> '' 'abc' -> 'b', 'zzz' -> 'z' """ out = '' # progress towards output
for i in range(len(s)): if (i % 2 == 1): out += s[i] return out
class Paper(object): """An instance is a scientific paper. Class variables: number [int]: number of papers that have been created. >= 0 Instance variables: title [string]: title of this paper. At least one char long. cites [list of Papers]: papers that this book cites cited_by [list of Papers]: papers that this paper is cited by """ number = 0 # initial value is 0
def init(self, title, cites=None): """Initializer. A new paper with title , citing the papers in list <cites> (set to [] if <cites> is None), and with cited_by set to []. Unlike in A4, this initializer should also update the relevant attributes of any papers in the list <cites>. Pre: arg values as in class specification. Don't forget to update the class variable. """
def partition(b, h, k): """Partition list b[h..k] around a pivot x = b[h]""" i = h; j = k
while i < j: if b[i+1] >= b[i]:
b[i+1], b[j] = b[j], b[i+1] j = j - 1 else: # b[i+1] < b[i] b[i], b[i+1] = b[i+1], b[i] i = i + 1
return i
def evaluate(p, x): """(spec on previous slide)""" sum = 0 # sum of all the coeffsxy for coeffs seen so far xval = 1 # value to multiply with next coeff yet unseen for c in p: # c is next unseen coefficient sum = sum + cxval xval = xval * x return sum
def evaluate(p, x): """(spec on previous slide)""" i=0; xval = 1; sum = p[i] # no point in multiplying by 1; showing
i = 1 while i < len(p):
xval = x # or, xval = xvalx sum += p[i]xval # or, sum = sum + p[i]xval i += 1 # or, i = i + 1 return sum