1 CS Review, iClicker -Questions Week 15
Announcements 2
ANY QUESTIONS? 3
Variables and Functions 4
Clicker Question: Are these programs equivalent? print(Hello)print(“Hello”) 21 A: yes C: maybe B: no
Clicker Question Which variable name is not valid? A. a B. seven C. 4a D. _4
Clicker Question: Are these programs equivalent? def myFun(a): print(a) return a print(myFun(4)) def myFun(a): print(a) print (myFun(4)) 21 A: yes B: no
Function Call Once the function is defined it can be called as many times as one likes If the function has a return it can be stored into a variable at the call myFunction(6,7) myFunction(4,10) a = myFunction(6,7)
Clicker Question: Are these programs equivalent? a = 3 def myFun(a): print(a) a = 3 def myFun(a): print(a) 21 A: yes B: no
Clicker Question: Are these programs equivalent? a = 3 def myFun(b): print(b) print(a) myFun(3) a = 3 def myFun(b): print(b) myFun(3) 21 A: yesB: no
Clicker Question: Are these programs equivalent? a = 3 def myFun(a): print (a) myFun(4) a = 3 print (a) 21 A: yes B: no
Clicker Question: does this program print 3 or 4? x = 3 def myFun(): print (x) x = 4 myFun() A: 3 B: 4
Variables and Functions Variables used in functions but defined outside of the function can be changed Multiple calls to a function may yield different results if the program “rebinds” such variables
You must be careful! x = 3 def myFun(): print (x) x = 1 x = 4 myFun() x =5 myFun() ERROR!
Global Variables How can we get the example code we saw earlier to work? Python is not sure if we want x to be a local variable or if it should refer to the x we defined outside of the function We can inform python if we want x to refer to the variable outside of the function New keyword global
This works! x = 3 def myFun(): global x print (x) x =1 x = 4 myFun()
Global or Local? If the global keyword is used, the variable is global If the first use of the variable is a ‘read’ (reference), the variable is global NOTE: We cannot assign to such a variable later Function arguments are always local If the first use of the variable is a write (assignment), the variable is local Unless the variable is defined global
Clicker Question: Is x global or local? x = 3 def myFun(): y = 4 z = x + y myFun() A: global B: local
Let’s Review Functions take input and produce output Output is provided by the “return” statement Otherwise the function does not provide output At the call site of the function the arguments get bound The arguments can rebind variables that have already been defined for the duration of the call You can use global variables, defined outside the function, but you must be careful!
Conditionals and Loops 20
Conditionals It is also possible to specify what to do if the condition is False. Contrast these two examples. x = 7 if x > 10: print x x = x + 1 x = 7 if x > 10: print x else: x = x + 1
CQ: Are these programs equivalent? 21 A: yes B: no x = 7 if x > 10: print x x = x + 1 print x x = 7 if x > 10: print x else: x = x + 1 print x
if x > 10 print x x = x + 1 True False x = 7 if x > 10: print x x = x + 1
x = 7 if x > 10: print x else: x = x + 1 if x > 10 print x TrueFalse x = 7 x = x + 1
Truth Tables andTrueFalse True False orTrueFalse True FalseTrueFalse notTrue Fals e True
CQ:Are these programs equivalent? printCountNTimes(8) printCountNTimes(4) 2 1 A: yesB: no def printCountNTimes(n): count = 0 while (count < n): print ('The count is: ', count ) count = count + 1
While Loop Dangers While loops do not require that the loop ever stop. In this example, count starts at 0 and gets smaller. Thus it will always be < 9 count = 0 while (count < 9): print ('The count is: ', count ) count = count - 1
CQ: Do these programs print the same things? 2 1 A: yes B: no x = 12 if x > 10: print (x) x = x + 1 print (x) x = 12 if x > 10: print(x) else: x = x + 1 print(x)
Clicker Question Now we can start building useful conditions Does this check if x > 0? if x and y > 0: print( x, y ) A: yes B: no
Tests Continued We could write such a condition as follows: if x > 0 and y > 0: print (x + y)
Clicker Question: Are these programs equivalent? if (x+y) < 10: print(x) if (x+y)>=10: print(y) if(x+y) < 10: print(x) else: print(y) 21 A: yes B: no
Example Revisited if x < 10 and y < 100: print(x+y) print(x) if x = 100: print(x+y) print(y) if x < 10: print(x+y) if y < 100: print(x) else: print(y)
Analysis a<=b a<=c b<=c y y y n n n not b! not a! a b c c Who can be min? def minOfThree(a,b,c): if a<=b: if a<=c: return a else: return c else: if b<=c: return b else: return c
Clicker Question 1 if “False”: print(“hi”) 2 if False: print(“hi”) A: 1 and 2 both print B: only 1 prints C: only 2 prints D: neither 1 nor 2 print
Clicker Question 3 if eval(“False”): print(“hi”) 2 if False: print(“hi”) A: 3 and 2 both print B: only 3 prints C: only 2 prints D: neither 3 nor 2 print
CQ:Are these programs equivalent? for a in range(0, 10, 1): print(a) for a in range(10): print(a) 21 A: yes B: no
Definite Loops for loops alter the flow of program execution, so they are referred to as control structures. more items in = next item yes no
CQ:Are these programs equivalent? A: Yes B: No x = 0 y = 0 for k in range(5): x = x + k y = x + k print (y) x = 0 y = 0 for k in range(5): x = x + k y = x + k print (y) 1 2
CQ:Are these programs equivalent? a = 0 while(a < 10): print(a) a = a+1 for a in range(10): print(a) 21 A: yes B: no
CQ: Do these functions have the same output? def nested1(a,b): for x in range(0, a): for y in range (0, b): print(x*y) def nested2(a,b): for y in range(0,b): for x in range (0, a): print(x*y) A: yes B: no
When might they be equivalent? What about when a=b? That is, we call the functions and provide the same values for a and b Output of nested1(2,2) = output of nested2(2,2)
String Operations 42
String Operations
CQ: Are these programs equivalent? 1.capitalize()“1”.capitalize() 21 A: yes B: no
Clicker Question: Are these two functions equivalent? def printByCharacter(str) i = 0 while i < len(str): print (str[i]) i = i + 1 def printByCharacter(str) i = 0 while i < 16: print (str[i]) i = i + 1 A: yes B: no
CQ: Are these programs equivalent? i = 0 x = “This is a string” while i < len(x): print (x[i]) i = i + 1 x = “This is a string” for y in x: print (y) A: yes B: no
What is going on here? x = “This is a string” for y in x: print (y) Tx h i s i …. y = x[j] Under the hood we are doing something similar to:
CQ: Are these programs equivalent? i = 0 x = “This is a string” while i < len(x): print (x[i]) i = i + 1 A: yes B: no x = “This is a string” i = 0 – len(x) while i < 0: print (x[i]) i = i + 1
CQ:Are these programs equivalent? b = [‘h’,’e’,’l’,’l’,’o’] b.insert(len(b), “w”) print(b) b = [‘h’,’e’,’l’,’l’,’o’] b.append(“w”) print(b) 21 A: yes B: no
List Operations 50
List
Slicing x = “This is a string” print (x[0]) print (x[0:5]) print (x[:3]) print (x[3:]) print (x[-1:]) print (x[:-1])
CQ Is this list empty? [ [ ] ] A: This list is empty B: This list is not empty
CQ: What is S[:] ? A. S B. S[0:0] C. S[0:len(S)]
CQ: How many? What does the following program print? S = "a,b,,d,e" print(len(S.split(","))) A. 8 B. 5 C. 4 Python Programming, 2/e 56
Decision Tree 57
Example: Directory trees
We call this structure a tree Root
Trees can be more complex Tree = [‘Root’, ‘Leaf1’, ‘Leaf2’, [‘Node1’, ‘Leaf3’, ‘Leaf4’, ‘Leaf5’]] Root Leaf1Leaf2 Leaf3 Leaf4Leaf5 Node1
Trees can be more complex Tree = [‘Root’, ‘Leaf1’, ‘Leaf2’, [‘Node1’, ‘Leaf3’, ‘Leaf4’, ‘Leaf5’]] Root Leaf1Leaf2 Leaf3 Leaf4Leaf5 Node1
Trees can be more complex Tree = [‘Root’, ‘Leaf1’, ‘Leaf2’, [‘Node1’, ‘Leaf3’, ‘Leaf4’, ‘Leaf5’]] Root Leaf1Leaf2 Leaf3 Leaf4Leaf5 Node1
Indices allow us to “traverse” the tree Root Leaf1 Leaf2 Leaf3Leaf4 Leaf6 Tree = [‘Root’, [‘Node1’, ‘Leaf0’, ‘Leaf1’], ‘Leaf2’, [‘Node2’, ‘Leaf3’, ‘Leaf4’, [‘Node3’, ‘Leaf5’, ‘Leaf6’]]] Leaf0 Leaf5 [0] [3][1] [3][3][1] [1][1][1][2] [1] [3][2] [3][3][2] [2] [3][3] [3] [1][0] [3][0] [3][3][0] Node1 Node2 Node3
Recursion 64
Recursion
Traversing a Tree
68 Recursion : String Reversal def reverse(s): if s == "": return s else: return reverse(s[1:]) + s[0] >>> reverse("Hello") 'olleH'
Dictionary 69
Dictionary Syntax: {‘Unique_Key’:value}
CQ: do these programs print the same thing? A = [‘mike’, ‘mary’, ‘marty’] print A[1] A = {1:’mary’, 2:’marty’, 0:’mike’} print A[1] 21 A: yes B: no
Clicker Question: What is the output of this code? A = {0:’mike’, 1:’mary’, 2:’marty’, ‘marty’:2, ‘mike’:0, ‘mary’:1} A[3] = ‘mary’ A[‘mary’] = 5 A[2] = A[0] + A[1] A: {'mike': 0, 'marty': 2, 3: 'mary', 'mary': 5, 2: 'mikemary', 1: 'mary', 0: 'mike'} B: {'mike': 0, 'marty': 2, 'mary’:3, 'mary': 5, 2: 'mikemary', 1: 'mary', 0: 'mike'} C: {'mike': 0, 'marty': 2, 'mary’:3, 'mary': 5, 2:1, 1: 'mary', 0: 'mike'}
Printing a Dictionary A = {0:'mike', 1:'mary', 2:'marty’} for k,v in A.iteritems(): print(k, ":", v) Prints: 2 : marty 1 : mary 0 : mike A = {0:'mike', 1:'mary', 2:'marty’} for k in A: print(k) Prints: 2 1 0
Operations on Tuples Concatenation: (1, 2, 3) + (6, 5, 4)produces(1, 2, 3, 6, 5, 4) 3*(1,2)produces(1, 2, 1, 2, 1, 2) 3 * (5)produces15 3 * (5,)produces(5, 5, 5) A[2] = 4 produces ERROR Type change tuple([1,2,3])evaluates to(1, 2, 3) tuple(‘abc’)evaluates to(‘a’, ’b’, ’c’) tuple(12)evaluates to an error Argument of tuple() should be a sequence (iterable)
Big-O Notation 75
Big-O Notation
Why Size Matters?
Identify the term that has the largest growth rate Num of steps growth term asympt. complexity 6n + 3 6n O(n) 2n 2 + 6n + 3 2n 2 O(n 2 ) 2n 3 + 6n + 3 2n 3 O(n 3 ) 2n n n O(2 n ) n! + 2n n + 3 n! O(n!)
CQ: Arithmetic Series
Clicker Question def getFirst(list): if len(list) == 0: return -1 return (list[0]) A: O(n) B: O(n 2 ) C: O(1) >>> getFirst([]) >>> getFirst([0,1,2,3]) 0 >>> getFirst(["a", "b", "c"]) 'a’
Sorting Arrays 81
How to find an alien Logic Puzzle: You have 9 marbles. 8 marbles weigh 1 ounce each, & one marble weighs 1.5 ounces. You are unable to determine which is the heavier marble by looking at them. How do you find the marble which weighs more?
Solution 1: Weigh one marble vs another What is the complexity of this solution?
Finding the Complexity Step 1: What is our input? The marbles Step 2: How much work do we do per marble? We weight each marble once (except one) Step 3: What is the total work we did? 8 measurements What if we had 100 marbles or 1000?
Clicker Question: What is the complexity of this algorithm? A: O(n) B: O(n 2 ) C: O(1) D: O(log n)
We can do better! Lets pull some intuition from our search algorithm that was O(log n) We want a way to eliminated ½ (or more) of the marbles with each measurement How might we do this? What about weighing multiple marbles at once?
Finding the complexity of the optimal solution Step 1: What is our input? The marbles Step 2: How much work do we do per marble? LOGARITHMIC Step 3: What is the total work we did? 2 measurements What if we had 100 marbles or 1000?
What happens at each step? We eliminated 2/3rds of the marbles
Clicker Question: What is the complexity of this algorithm? A: O(n) B: O(n 2 ) C: O(1) D: O(log n)
Big-O – Sorting Arrays Type of SortBestWorstAverageMemory Space Bubble SortO(N)O(N 2 ) 1 Selection Sort O(N 2 ) 1 Heap Sort O(N log N) 1 Merge SortO(N log N) Worst =N
O(n 2 ) – that is too much ! Selection sort repeatedly extracts max, O(n) times Each max extraction is O(n) comparisons So selection sort is O(n 2 ) -- not very good Problem: After extracting the max, we get no help extracting the max in the remaining slice Can we fix that?
Two Phases using a Priority Queue 1. Put all items in the input list into a priority queue 2. Extract items by decreasing magnitude and put them into the output list We get a sorted list that way [3,7,2,9,… [9,8,7,6,…
Example Tree, Encoding & Access Tree encoding: a = [9, 6, 4, 5, 1, 2] :1: 0: 3:4:5: 6: Find Parent of: 4 a[2]=4 i=(2-1)//2 = 0 Parent is at a[0] =9
Heap Representation
Step- 1 Step-3 Step- 2 Heap- Insert
Complexity: Tree Stats
Tree-Complexity
CQ: Is this a Priority Queue? A. Yes B. No :1: 0: 3:4:5: 6: x yz ≥≥
CQ: Is this a Priority Queue? A. Yes B. No :1: 0: 3:4:5: 6:
CQ: Is this a priority queue? [9,8,4,7,3,2,5,6,1] A. Yes B. No
CQ: how many children for L[5]? [9,7,4,6,5,4,2,2,1,1,1,1] A. 0 B. 1 C. 2
CQ: how many children for L[5]? [9,7,4,6,5,4,2,2,1,1,1,1] A. 0 B. 1 C
Merge Sort log(n) n elements merged
Putting it all together We know that there are log(n) splits At each “level” we split each list in two We know that we need to merge a total of n elements at each “level” n * log(n) thus O(n log n)