Presentation is loading. Please wait.

Presentation is loading. Please wait.

EECS 110: Lec 17: Review for the Final Exam

Similar presentations


Presentation on theme: "EECS 110: Lec 17: Review for the Final Exam"— Presentation transcript:

1 EECS 110: Lec 17: Review for the Final Exam
Aleksandar Kuzmanovic Northwestern University

2 General Info Wednesday, May 31, 9:30-11:00am, PLSAUD
To be done individually Closed book One 8.5” by 11” sheet of paper permitted Please do not discuss the exam with others until everyone has taken it. There are six questions. Each question is worth 20 points. Hence, you can acquire 120 points in total. Those who get > 90 points will get an A. Those who get >80 points and <90 points will get a B, etc.  

3 Final Exam 6 questions: Misc Loops and recursion Mutation 2D in Python
Dictionaries Classes and Objects

4 Loops (while and for) and Recursion
Q2 (and Q1): Loops (while and for) and Recursion What does this code do? print('It keeps on') while True: print('going and') print('Phew! I\'m done!’)

5 Extreme Looping Anatomy of a while loop: print('It keeps on')
the loop keeps on running as long as this test is True print('It keeps on') while True: print('going and') print('Phew! I\'m done!') “while” loop This won't print until the while loop finishes - in this case, never!

6 What do these two loops print?
while n > 1: print(n) if n%2 == 0: n = n/2 else: n = 3*n + 1 n = 0 for c in 'forty-two': if c not in 'aeiou': n += 1 print(n) ??

7 What do these two loops print?
while n > 1: print(n) if n%2 == 0: n = n/2 else: n = 3*n + 1 ?? n = 0 for c in 'forty-two': if c not in 'aeiou': n += 1 print(n) 7

8 What do these two loops print?
while n > 1: print(n) if n%2 == 0: n = n/2 else: n = 3*n + 1 3 n = 0 for c in 'forty-two': if c not in 'aeiou': n += 1 print(n) 7

9 What do these two loops print?
while n > 1: print(n) if n%2 == 0: n = n/2 else: n = 3*n + 1 3 10 n = 0 for c in 'forty-two': if c not in 'aeiou': n += 1 print(n) 7

10 What do these two loops print?
while n > 1: print(n) if n%2 == 0: n = n/2 else: n = 3*n + 1 3 10 5 n = 0 for c in 'forty-two': if c not in 'aeiou': n += 1 print(n) 7

11 What do these two loops print?
while n > 1: print(n) if n%2 == 0: n = n/2 else: n = 3*n + 1 3 10 5 16 n = 0 for c in 'forty-two': if c not in 'aeiou': n += 1 print(n) 7

12 What do these two loops print?
while n > 1: print(n) if n%2 == 0: n = n/2 else: n = 3*n + 1 3 10 5 16 8 n = 0 for c in 'forty-two': if c not in 'aeiou': n += 1 print(n) 7

13 What do these two loops print?
while n > 1: print(n) if n%2 == 0: n = n/2 else: n = 3*n + 1 3 10 5 16 8 4 n = 0 for c in 'forty-two': if c not in 'aeiou': n += 1 print(n) 7

14 What do these two loops print?
while n > 1: print(n) if n%2 == 0: n = n/2 else: n = 3*n + 1 3 10 5 16 8 4 2 n = 0 for c in 'forty-two': if c not in 'aeiou': n += 1 print(n) 7

15 fore! for x in range(8): print('x is', x) print('Phew!') 1 3 2 4
x is assigned each value from this sequence 1 for x in range(8): print('x is', x) print('Phew!') 3 LOOP back to step 1 for EACH value in the list 2 the BODY or BLOCK of the for loop runs with that x 4 Code AFTER the loop will not run until the loop is finished.

16 Two kinds of for loops sum = 0 for x in L: sum += x sum = 0
Element-based Loops Index-based Loops sum = 0 for x in L: sum += x sum = 0 for i in range(len(L)): sum += L[i] i 1 2 L = [ 42, -10, 4 ] L = [ 42, -10, 4 ] x L[i]

17 Q2: Recursion vs. Loops Solve a problem using: (a) recursion (b) loops

18 Let recursion do the work for you.
Example 1a: fac(N) with recursion Let recursion do the work for you. Exploit self-similarity Less work ! Produce short, elegant code def fac(N): if N <= 1: return 1 else: return N * fac(N-1) You handle the base case – the easiest possible case to think of! Recursion does almost all of the rest of the problem!

19 Example 1b: fac with for (v1)
def fact( n ): answer = 1 for x in range(n): answer = answer * x return answer

20 Example 1b: fac with for (v2)
def fact( n ): answer = 1 for x in range(1,n+1): answer = answer * x return answer

21 Example 2a: sum(L) with recursion
def sum(L): """ input: a list of numbers, L output: L's sum """ if len(L) == 0: return 0.0 else: return L[0] + sum(L[1:]) Base Case This input to the recursive call must be "smaller" somehow… if the input has no elements, its sum is zero Recursive Case if L does have an element, add that element's value to the sum of the REST of the list…

22 Example 2b: sum(L) with for
Finding the sum of a list: def sum( L ): """ returns the sum of L's elements """ sum = 0 for x in L: sum = sum + x return sum Accumulator!

23 Example 3: uniquify(L) Problem: Part A
Use loops (no recursion!) to write a Python function uniquify(L), which takes in any list L and returns a list of the distinct elements in the list L. The order of the elements may be preserved, but they do not have to be. For example, >>> uniquify( [ 42, 'spam', 42, 5, 42, 5, 'spam', 42, 5, 5, 5 ] ) [ 'spam', 42, 5 ] >>> L = range(4) + range(3) >>> uniquify(L) [ 3, 0, 1, 2 ]

24 Example 3a: uniquify(L)
def uniquify(L): s = [] for i in range(len(L)): n=0 for j in range(i+1,len(L)): if L[i] == L[j]: n=1 if n == 0: s=s+[L[i]] return s

25 Example 3: uniquify(L) Problem: Part B
Use recursion (no loops!) to write a Python function uniquify(L), which takes in any list L and returns a list of the distinct elements in the list L. The order of the elements may be preserved, but they do not have to be. For example, >>> uniquify( [ 42, 'spam', 42, 5, 42, 5, 'spam', 42, 5, 5, 5 ] ) [ 'spam', 42, 5 ] 

26 Example 3b: uniquify(L)
def uniquify(L): if len(L) == 0: return [] else: if L[0] in L[1:]: return uniquify(L[1:]) return L[0:1] + uniquify(L[1:])

27 Mutable vs. Immutable data
Question 3: Mutation Mutable vs. Immutable data Changeable types: Unchangeable types: tuple dictionary float string list bool int

28 Functions and (immutable) Variables
def fact(a): result = 1 while a > 0: result *= a a -= 1 return result >>> x = 5 >>> y = fact(x) >>> x ?? NO SIDE EFFECTS!

29 Functions and (immutable) Variables
def fact(a): result = 1 while a > 0: result *= a a -= 1 return result >>> x = 5 >>> y = fact(x) >>> x 5 NO SIDE EFFECTS!

30 Functions and (immutable) Variables
def swap(a, b): temp = a a = b b = temp >>> x = 5 >>> y = 10 >>> swap(x, y) >>> print(x, y) ?? x y a b temp

31 Functions and (immutable) Variables
def swap(a, b): temp = a a = b b = temp >>> x = 5 >>> y = 10 >>> swap(x, y) >>> print(x, y) 5, 10 x y a b temp

32 Functions and Mutable Types
MyL def swap(L, i1, i2): temp = L[i1] L[i1] = L[i2] L[i2] = temp >>> MyL = [2, 3, 4, 1] >>> swap(myL, 0, 3) >>> print(myL) ?? L i1 i2 RAM 42 43 44 45

33 Functions and Mutable Types
MyL def swap(L, i1, i2): temp = L[i1] L[i1] = L[i2] L[i2] = temp >>> MyL = [2, 3, 4, 1] >>> swap(myL, 0, 3) >>> print(myL) [1,3,4,2] L i1 i2 RAM 42 43 44 45

34 Those changes will be visible everywhere.
The conclusion You can change the contents of lists in functions that take those lists as input. (actually, lists or any mutable objects) Those changes will be visible everywhere. (immutable objects are safe, however)

35 Example 1 def zeroOdd1( L ): for i in range(len(L)): if L[i] % 2 == 1:
for i in L: if i % 2 == 1: i = 0 >>> L = [1, 2, 3, 4, 5] >>> zeroOdd1(L) >>> L ?? >>> zeroOdd2(L)

36 Example 1 def zeroOdd1( L ): for i in range(len(L)): if L[i] % 2 == 1:
for i in L: if i % 2 == 1: i = 0 >>> L = [1, 2, 3, 4, 5] >>> zeroOdd1(L) >>> L [0,2,0,4,0] >>> zeroOdd2(L) ??

37 Example 1 def zeroOdd1( L ): for i in range(len(L)): if L[i] % 2 == 1:
for i in L: if i % 2 == 1: i = 0 >>> L = [1, 2, 3, 4, 5] >>> zeroOdd1(L) >>> L [0,2,0,4,0] >>> zeroOdd2(L) [1,2,3,4,5]

38 What are the values of A, B, C and D at the indicated points?
Example 2 What are the values of A, B, C and D at the indicated points? def mystery1(L1, N, C): for i in L1: if i == N: C += 1 return C def mystery2(C): for i in range(len(C)): C[i] *= 2 >>> A = [22, 10, 30] >>> B = 22 >>> C = 0 >>> D = mystery1(A, B, C) >>> mystery2(A) 1) 2) 1 2

39 What are the values of A, B, C and D at the indicated points?
Example 2 What are the values of A, B, C and D at the indicated points? def mystery1(L1, N, C): for i in L1: if i == N: C += 1 return C def mystery2(C): for i in range(len(C)): C[i] *= 2 >>> A = [22, 10, 30] >>> B = 22 >>> C = 0 >>> D = mystery1(A, B, C) >>> mystery2(A) >>> A 1) 2) A = [22, 10, 30] B = 22 C = 0 D = 1 1 2

40 What are the values of A, B, C and D at the indicated points?
Example 2 What are the values of A, B, C and D at the indicated points? def mystery1(L1, N, C): for i in L1: if i == N: C += 1 return C def mystery2(C): for i in range(len(C)): C[i] *= 2 >>> A = [22, 10, 30] >>> B = 22 >>> C = 0 >>> D = mystery1(A, B, C) >>> mystery2(A) >>> A 1) 2) A = [22, 10, 30] B = 22 C = 0 D = 1 A = [44, 20, 60] 1 2

41 Example 3: avoiding mutation
Problem: Write function x(L), …., The list L should NOT mutate, i.e., it should stay the same.

42 Example 3: avoiding mutation
def x(L): # some function L2=copyList(L) … # manipulate L2, not L def copyList(L): L2 = [] for x in L: L2 += [x] return L2

43 Handling rectangular arrays …
Question 4: 2D in Python Handling rectangular arrays … list list A[0] A A[0][0] list A[1] list A[2] A[2][3] How many rows does A have, in general ? How many columns does A have, in general ?

44 Handling rectangular arrays …
list list A[0] A A[0][0] list A[1] list A[2] A[2][3] len(A) How many rows does A have, in general ? How many columns does A have, in general ?

45 Handling rectangular arrays …
list list A[0] A A[0][0] list A[1] list A[2] A[2][3] len(A) How many rows does A have, in general ? len(A[0]) How many columns does A have, in general ?

46 Which one works? A = [ [0]*width ]*height A = [ [0]*height ]*width
How could we create a rectangular array (of default data, 0), given its height and width ? A = [ [0]*width ]*height or A = [ [0]*height ]*width

47 Which one works? A = [ [0]*width ]*height A = [ [0]*height ]*width
How could we create a rectangular array (of default data, 0), given its height and width ? A = [ [0]*width ]*height A = [ [0]*height ]*width

48 What's really going on? A = [ [0]*width ]*height inner = [0]*width
A = [inner]*height

49 Creating a 2d array def create2dArray( width, height ):
""" does just that """ A = [] # start with nothing for row in range( height ): for col in range( width ):

50 Creating a 2d array def create2dArray( width, height ):
""" does just that """ A = [] # start with nothing for row in range( height ): A = A + [[]] for col in range( width ): A[row] = A[row] + [0] return A

51 Example 1: What 2d loops would create a checkerboard image?
def checkerboard(): # loop over each pixel for col in range(width): for row in range(height):

52 Example 1: What 2d loops would create a checkerboard image?
def checkerboard(): # loop over each pixel for col in range(width): for row in range(height): if (col//20 + row//20)%2 == 0: image.plotPoint( col, row )

53 Example 2: Write a function that returns the number of all-zero rows

54 Example 2: Write a function that returns the number of all-zero rows
def num_zero_rows(L): width = len(L[0]) height = len(L) n = 0 for row in range(height): k = 0 for col in range(width): if L[row][col] != 0: k = 1 if k == 0: n += 1 return n

55 Question 5: Dictionaries
In Python a dictionary is a set of key - value pairs. >>> d = {} >>> d[1988] = 'dragon' >>> d[1989] = 'snake' >>> d {1988: 'dragon', 1989: 'snake'} >>> d[1988] 'dragon' >>> d[1987] key error It's a list where the index can be any immutable-type key.

56 Lists vs. Dictionaries In Python a dictionary is a set of key - value pairs. >>> d = {} >>> d[1988] = 'dragon' >>> d[1989] = 'snake' >>> d {1988: 'dragon', 1989: 'snake'} >>> d[1988] 'dragon' >>> d[1987] key error creates an empty dictionary, d 1988 is the key 'dragon' is the value 1989 is the key 'snake' is the value Anyone seen this before? Retrieve data as with lists… or almost ! It's a list where the index can be any immutable-type key.

57 More on dictionaries Dictionaries have lots of built-in methods:
>>> d = {1988: 'dragon', 1989: 'snake'} >>> d.keys() [ 1989, 1988 ] >>> 1988 in d True >>> 1969 in d False >>> d.pop( 1988 ) 'dragon' get all keys check if a key is present delete a key (and its value)

58 A family dictionary?

59 A family dictionary… T['abe'] T = {'abe' :['homer','herb'],
'jackie':['marge','patty','selma'], 'homer' :['hugo','bart','lisa','maggie'], 'marge' :['hugo','bart','lisa','maggie']} keys can be any immutable type values can be any type at all… T['abe'] How to get 'selma' from T?

60 A family dictionary… T['abe'] T = {'abe' :['homer','herb'],
'jackie':['marge','patty','selma'], 'homer' :['hugo','bart','lisa','maggie'], 'marge' :['hugo','bart','lisa','maggie']} keys can be any immutable type values can be any type at all… T['abe'] ['homer','herb'] How to get 'selma' from T?

61 A family dictionary… T['abe'] T = {'abe' :['homer','herb'],
'jackie':['marge','patty','selma'], 'homer' :['hugo','bart','lisa','maggie'], 'marge' :['hugo','bart','lisa','maggie']} keys can be any immutable type values can be any type at all… T['abe'] ['homer','herb'] How to get 'selma' from T? T['jackie'][2] (T['jackie'] is a list)

62 Example 1: favChild def favChild( person, Tree ):
""" person is a name (a string) Tree is a dictionary of children returns person's favorite child """ if person in Tree: Kids = Tree[person] Kids.sort() return Kids[0] else: return 'no children' Who is favored ? Side effects ?

63 For example, >>> addChild( 'lisa', T, 'abejr' )
def addChild( person, Tree, jr ): """ adds person's new child to Tree ""“

64 For example, >>> addChild( 'lisa', T, 'abejr' )
def addChild( person, Tree, jr ): """ adds person's new child to Tree ""“ if person in Tree: kids = Tree[person] kids += [jr]

65 def favChild( person, Tree ):
if person in Tree: Kids = Tree[person] Kids.sort() return Kids[0] else: return 'no children' EXAMPLE 3: Based on favChild, write favGChild to return the first grandchild alphabetically - or return 'no one' if there are none.

66 def favGChild( person, Tree ): gChildren = [] if person in Tree :
def favChild( person, Tree ): if person in Tree: Kids = Tree[person] Kids.sort() return Kids[0] else: return 'no children' EXAMPLE 3: Based on favChild, write favGChild to return the first grandchild alphabetically - or return 'no one' if there are none. def favGChild( person, Tree ): gChildren = [] if person in Tree : for child in Tree[person]: if child in Tree: gChildren += Tree[child] if gChildren == []: return 'no one' else: gChildren.sort() return gChildren[0]

67 (1) A class is a type of variable.
Question 6: Classes and Objects An object-oriented programming language allows you to build your own customized types of variables. (1) A class is a type of variable. (2) An object is one such variable. There will typically be MANY objects of a single class.

68 An object is a data structure (like a list), except
Objects An object is a data structure (like a list), except (1) Its data elements have names chosen by the programmer. (2) Data elements are chosen & organized by the programmer (3) An object can have behaviors built-in by the programmer.

69 Objects An object is a data structure (like a list), except
(1) Its data elements have names chosen by the programmer. (2) Data elements are chosen & organized by the programmer (3) An object can have behaviors built-in by the programmer. usually called "methods" instead of functions

70 The Date class class Date: """ a blueprint (class) for objects
that represent calendar days """ def __init__( self, mo, dy, yr ): """ the Date constructor """ self.month = mo self.day = dy self.year = yr def __repr__( self ): """ used for printing Dates """ s = "%02d/%02d/%04d" % (self.month, self.day, self.year) return s The Date class

71 The Date Class >>> d = Date(1,1,2017) >>> d 1/1/2017
this is a CONSTRUCTOR … this is an object of type Date the representation of a particular object of type Date

72 More Date class Date: def copy(self):
def __init__( self, mo, dy, yr ): def __repr__(self): def isLeapYear(self): def copy(self): """ returns a DIFFERENT object w/SAME date! """ def equals(self, d2): """ returns True if they represent the same date; False otherwise """

73 More Date class Date: def copy(self):
def __init__( self, mo, dy, yr ): def __repr__(self): def isLeapYear(self): def copy(self): """ returns a DIFFERENT object w/SAME date! ""“ return Date(self.month, self.day, self.year) def equals(self, d2): """ returns True if they represent the same date; False otherwise """

74 More Date class Date: def copy(self):
def __init__( self, mo, dy, yr ): def __repr__(self): def isLeapYear(self): def copy(self): """ returns a DIFFERENT object w/SAME date! ""“ return Date(self.month, self.day, self.year) def equals(self, d2): """ returns True if they represent the same date; False otherwise ""“ return self.month == d2.month and self.day == d2.day and self.year == d2.year

75 Good luck with the Exam!


Download ppt "EECS 110: Lec 17: Review for the Final Exam"

Similar presentations


Ads by Google