1 CS 17700 Review, iClicker -Questions Week 15. Announcements 2.

Slides:



Advertisements
Similar presentations
Michael Alves, Patrick Dugan, Robert Daniels, Carlos Vicuna
Advertisements

String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
© The McGraw-Hill Companies, Inc., Chapter 2 The Complexity of Algorithms and the Lower Bounds of Problems.
Announcements Midterm next week! No class next Friday Review this Friday.
CMPT 225 Priority Queues and Heaps. Priority Queues Items in a priority queue have a priority The priority is usually numerical value Could be lowest.
Sorting Heapsort Quick review of basic sorting methods Lower bounds for comparison-based methods Non-comparison based sorting.
2 -1 Chapter 2 The Complexity of Algorithms and the Lower Bounds of Problems.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
2 -1 Analysis of algorithms Best case: easiest Worst case Average case: hardest.
Fundamentals of Python: From First Programs Through Data Structures
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
Python Control of Flow.
Maps A map is an object that maps keys to values Each key can map to at most one value, and a map cannot contain duplicate keys KeyValue Map Examples Dictionaries:
Announcements Class / Recitation slides available on the syllabus page Check morning of for latest version We will start grading clickers next lecture.
Data Structures More List Methods Our first encoding Matrix.
Announcements Project 2 Available Tomorrow (we will send mail) Will be due 11:59PM October 9 th (Sunday) Week 6 ( I will be traveling this week) Review.
Comp 249 Programming Methodology Chapter 15 Linked Data Structure - Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
1 Chapter 1 Analysis Basics. 2 Chapter Outline What is analysis? What to count and consider Mathematical background Rates of growth Tournament method.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved For Loops October 16, 2013 Slides by Evan Gallagher.
The Power of Incorrectness A Brief Introduction to Soft Heaps.
Heaps, Heapsort, Priority Queues. Sorting So Far Heap: Data structure and associated algorithms, Not garbage collection context.
Analysis of Algorithms These slides are a modified version of the slides used by Prof. Eltabakh in his offering of CS2223 in D term 2013.
Topics: Sequence Sequences Index into a sequence [] notation Slicing and other operations.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
If statements while loop for loop
Announcements Additional office hours tomorrow: 3-6pm in HAAS 142 Midterm Bring a #2 pencil (test given via scantron sheet) Photo ID No Labs or Recitation.
Interpretation Environments and Evaluation. CS 354 Spring Translation Stages Lexical analysis (scanning) Parsing –Recognizing –Building parse tree.
Sorting. Pseudocode of Insertion Sort Insertion Sort To sort array A[0..n-1], sort A[0..n-2] recursively and then insert A[n-1] in its proper place among.
Announcements Project1 Due Wednesday September 21 st 4:30pm We will post instructions on how to turnin from home Note: you can always turn in from the.
Built-in Data Structures in Python An Introduction.
Topics: IF If statements Else clauses. IF Statement For the conditional expression, evaluating to True or False, the simple IF statement is if : x = 7.
Introduction to: Programming CS105 Lecture: Yang Mu.
Topics: Function Intitution Algorithm Example Function Definition (and Indentation) Function Call Naming and Binding Local Variables Function Arguments.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
Announcements Survey link (can be found on piazza): OCJ6
Priority Queues and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
Announcements Course evaluation Your opinion matters! Attendance grades Will be posted prior to the final Project 5 grades Will be posted prior to the.
Java Methods Big-O Analysis of Algorithms Object-Oriented Programming
Announcements: Project 5 Everything we have been learning thus far will enable us to solve interesting problems Project 5 will focus on applying the skills.
Midterm Review 1. Midterm Exam Thursday, October 15 in classroom 75 minutes Exam structure: –TRUE/FALSE questions –short questions on the topics discussed.
8 January Heap Sort CSE 2011 Winter Heap Sort Consider a priority queue with n items implemented by means of a heap  the space used is.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
Chapter 10 Loops: while and for CSC1310 Fall 2009.
Scope, Aliasing, Tuples & Mutability Intro2CS – week 4a 1.
Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(
Announcements No Labs / Recitation this week On Friday we will talk about Project 3 Release late afternoon / evening tomorrow Cryptography.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
1 CS Review, iClicker -Questions Week 15. ANY QUESTIONS? 2.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
1 Algorithms Searching and Sorting Algorithm Efficiency.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Announcements Reading Read Chapter 4 (functions).
CMSC201 Computer Science I for Majors Lecture 05 – Comparison Operators and Boolean (Logical) Operators Prof. Katherine Gibson Prof. Jeremy.
More about Iteration Victor Norman CS104. Reading Quiz.
Python Boot Camp Booleans While loops If statements Else clauses
Announcements Reading Project1 Codelab: Read Chapter 4 (functions)
Announcements Project 4 due Wed., Nov 7
Heap Sort Example Qamar Abbas.
Teach A level Computing: Algorithms and Data Structures
(2,4) Trees 11/15/2018 9:25 AM Sorting Lower Bound Sorting Lower Bound.
Algorithm design and Analysis
What does this do? def revList(L): if len(L) < = 1: return L x = L[0] LR = revList(L[1:]) return LR + x.
(2,4) Trees 2/28/2019 3:21 AM Sorting Lower Bound Sorting Lower Bound.
Topic: Loops Loops Idea While Loop Introduction to ranges For Loop
Heaps & Multi-way Search Trees
CMPT 225 Lecture 16 – Heap Sort.
Presentation transcript:

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)