Recursion and Loops: Implementations and Examples, Slides of Introduction to Computing

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

2012/2013

Uploaded on 08/17/2013

bakul
bakul 🇮🇳

4.6

(16)

69 documents

1 / 14

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Material emphasized!
Recursion (A4, Lab 6)!
Defining and using classes (A4, A6, Lab 8)!
For- and while-loops (A4, A6, Lab10)!
Code development from invariants (A6, Lab10)!
[We will assume knowledge of the material covered
previously, in the sense that you should know how to,
say, create lists, draw folders and frames, manipulate
strings, make appropriate test cases. and so on. This
shouldn't require additional studying.]!
Hint: re-read spec after doing problem.!
docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download Recursion and Loops: Implementations and Examples and more Slides Introduction to Computing in PDF only on Docsity!

Material emphasized

Recursion (A4, Lab 6)

Defining and using classes (A4, A6, Lab 8)

For- and while-loops (A4, A6, Lab10)

Code development from invariants (A6, Lab10)

[We will assume knowledge of the material covered

previously, in the sense that you should know how to,

say, create lists, draw folders and frames, manipulate

strings, make appropriate test cases. and so on. This

shouldn't require additional studying.]

Hint: re-read spec after doing problem.

Additional sources of practice problems

• Fall 2012 Prelim 2, questions 4, 5.

• Fall 2012 Final questions, questions 4, 6, 7 given the

invariant for insertion sort and the helper function

push_down.

• The worked exercises on loop invariants

• Loop problems at

http://codingbat.com/python (interactive

programming exercises). You can try solving the

problems via both loops and recursion, often.

Provide a recursive implementation

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 '')

Provide a for-loop implementation

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

Inv: chars s[0..i-1] have been processed. Done when i is len(s)

for i in range(len(s)): if (i % 2 == 1): out += s[i] return out

Defining a class

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. """

Implement according to invariant

  • Given a sequence b[h..k] with some value x in b[h]:
  • Swap elements of b[h..k] and store in i to truthify post: x? h k pre: b <= x x >= x h i i+1 k post: b <= x x? >= x h i j k inv : b

Partition Algorithm Implementation

def partition(b, h, k): """Partition list b[h..k] around a pivot x = b[h]""" i = h; j = k

invariant: b[h..i-1] < b[i], b[j+1..k] >= b[i]

while i < j: if b[i+1] >= b[i]:

Move to end of block.

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

post: b[h..i-1] < x, b[i] is x, and b[i+1..k] >= x

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

One implementation

def evaluate(p, x): """(spec on previous slide)""" i=0; xval = 1; sum = p[i] # no point in multiplying by 1; showing

i for clarity; it's not really necessary here

i = 1 while i < len(p):

Invariant: xval = x**(i-1); sum = eval(p[..i-1], x)

xval = x # or, xval = xvalx sum += p[i]xval # or, sum = sum + p[i]xval i += 1 # or, i = i + 1 return sum

Alternate implementation