cs 17700 review, iclicker -questions week 15

104
1 CS 17700 Review, iClicker -Questions Week 15

Upload: franz

Post on 25-Feb-2016

48 views

Category:

Documents


0 download

DESCRIPTION

CS 17700 Review, iClicker -Questions Week 15. Announcements. ANY QUESTIONS?. Variables and Functions. Clicker Question: Are these programs equivalent?. 1. 2. p rint(Hello). p rint(“Hello”). A: yes. B: no. C: maybe. Clicker Question. Which variable name is not valid? a seven 4a - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CS  17700  Review,  iClicker -Questions Week  15

1

CS 17700 Review, iClicker -Questions

Week 15

Page 2: CS  17700  Review,  iClicker -Questions Week  15

Announcements

2

Page 3: CS  17700  Review,  iClicker -Questions Week  15

ANY QUESTIONS?

3

Page 4: CS  17700  Review,  iClicker -Questions Week  15

Variables and Functions

4

Page 5: CS  17700  Review,  iClicker -Questions Week  15

Clicker Question:Are these programs

equivalent?

print(Hello) print(“Hello”)21

A: yes

C: maybeB: no

Page 6: CS  17700  Review,  iClicker -Questions Week  15

Clicker Question• Which variable name is not valid?A. aB. sevenC. 4aD. _4

Page 7: CS  17700  Review,  iClicker -Questions Week  15

Clicker Question:Are these programs

equivalent?def myFun(a): print(a) return aprint(myFun(4))

def myFun(a): print(a)print (myFun(4))

21

A: yes

B: no

Page 8: CS  17700  Review,  iClicker -Questions Week  15

Function CallOnce 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)

Page 9: CS  17700  Review,  iClicker -Questions Week  15

Clicker Question:Are these programs

equivalent?a = 3def myFun(a): print(a)print(a)

a = 3def myFun(a): print(a) print(a)

21

A: yes

B: no

Page 10: CS  17700  Review,  iClicker -Questions Week  15

Clicker Question:Are these programs

equivalent?a = 3def myFun(b): print(b)print(a)myFun(3)

a = 3def myFun(b): print(b) print(b)myFun(3)

21

A: yes B: no

Page 11: CS  17700  Review,  iClicker -Questions Week  15

Clicker Question:Are these programs

equivalent?a = 3def myFun(a): print (a)myFun(4)

a = 3print (a)

21

A: yes

B: no

Page 12: CS  17700  Review,  iClicker -Questions Week  15

Clicker Question: does this program print 3 or 4?

x = 3def myFun(): print (x)x = 4myFun()

A: 3

B: 4

Page 13: CS  17700  Review,  iClicker -Questions Week  15

Variables and FunctionsVariables used in functions but defined outside

of the function can be changedMultiple calls to a function may yield different

results if the program “rebinds” such variables

Page 14: CS  17700  Review,  iClicker -Questions Week  15

You must be careful!x = 3def myFun(): print (x) x = 1x = 4myFun()x =5myFun()

ERROR!

ERROR!

Page 15: CS  17700  Review,  iClicker -Questions Week  15

Global VariablesHow 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 functionNew keyword global

Page 16: CS  17700  Review,  iClicker -Questions Week  15

This works!x = 3def myFun(): global x print (x) x =1x = 4myFun()myFun()

Page 17: CS  17700  Review,  iClicker -Questions Week  15

Global or Local?If the global keyword is used, the variable is

globalIf the first use of the variable is a ‘read’

(reference), the variable is globalNOTE: We cannot assign to such a variable laterFunction arguments are always local

If the first use of the variable is a write (assignment), the variable is localUnless the variable is defined global

Page 18: CS  17700  Review,  iClicker -Questions Week  15

Clicker Question: Is x global or local?

x = 3def myFun(): y = 4 z = x + ymyFun()

A: global

B: local

Page 19: CS  17700  Review,  iClicker -Questions Week  15

Let’s ReviewFunctions take input and produce outputOutput 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!

Page 20: CS  17700  Review,  iClicker -Questions Week  15

Conditionals and Loops

20

Page 21: CS  17700  Review,  iClicker -Questions Week  15

ConditionalsIt is also possible to specify what to do if the

condition is False. Contrast these two examples.

x = 7if x > 10: print xx = x + 1

x = 7if x > 10: print xelse: x = x + 1

Page 22: CS  17700  Review,  iClicker -Questions Week  15

CQ: Are these programs equivalent?

21

A: yesB: no

x = 7if x > 10: print xx = x + 1print x

x = 7if x > 10: print xelse: x = x + 1print x

Page 23: CS  17700  Review,  iClicker -Questions Week  15

if x > 10

print x

x = x + 1

End

True False

x = 7x = 7if x > 10: print xx = x + 1

Page 24: CS  17700  Review,  iClicker -Questions Week  15

x = 7if x > 10: print xelse: x = x + 1

if x > 10

print x

End

True False

x = 7

x = x + 1

Page 25: CS  17700  Review,  iClicker -Questions Week  15

Truth Tables

and True FalseTrue True FalseFalse False False

or True FalseTrue True TrueFalse True False

not True False

False True

Page 26: CS  17700  Review,  iClicker -Questions Week  15

CQ:Are these programs equivalent?

printCountNTimes(8) printCountNTimes(4)printCountNTimes(4)

21

A: yes B: no

def printCountNTimes(n): count = 0 while (count < n):

print ('The count is: ', count ) count = count + 1

Page 27: CS  17700  Review,  iClicker -Questions Week  15

While Loop DangersWhile 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

Page 28: CS  17700  Review,  iClicker -Questions Week  15

CQ: Do these programs print the same things?

21

A: yesB: no

x = 12if x > 10: print (x)x = x + 1print (x)

x = 12if x > 10: print(x)else: x = x + 1print(x)

Page 29: CS  17700  Review,  iClicker -Questions Week  15

Clicker QuestionNow we can start building useful conditions

Does this check if x > 0?

if x and y > 0:print( x , y )

A: yes

B: no

Page 30: CS  17700  Review,  iClicker -Questions Week  15

Tests ContinuedWe could write such a condition as follows:

if x > 0 and y > 0:print (x + y)

Page 31: CS  17700  Review,  iClicker -Questions Week  15

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

Page 32: CS  17700  Review,  iClicker -Questions Week  15

Example Revisited

if x < 10 and y < 100: print(x+y) print(x)if x < 10 and y >= 100: print(x+y) print(y)

if x < 10: print(x+y) if y < 100: print(x) else: print(y)

Page 33: CS  17700  Review,  iClicker -Questions Week  15

Analysis

a<=b

a<=c

b<=c

y

yy

n

n n

not b!not a!

ab cc

Who can be min?def minOfThree(a,b,c):if a<=b: if a<=c:

return aelse:

return celse:if b<=c:return belse: return c

Page 34: CS  17700  Review,  iClicker -Questions Week  15

Clicker Question 1if “False”: print(“hi”)

2if False: print(“hi”)

A: 1 and 2 both print

B: only 1 prints

C: only 2 prints

D: neither 1 nor 2 print

Page 35: CS  17700  Review,  iClicker -Questions Week  15

Clicker Question 3if eval(“False”): print(“hi”)

2if False: print(“hi”)

A: 3 and 2 both print

B: only 3 prints

C: only 2 prints

D: neither 3 nor 2 print

Page 36: CS  17700  Review,  iClicker -Questions Week  15

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

Page 37: CS  17700  Review,  iClicker -Questions Week  15

Definite Loopsfor loops alter the flow of program execution, so

they are referred to as control structures.

more items in <sequence>

<var> = next item

<body>

yes

no

Page 38: CS  17700  Review,  iClicker -Questions Week  15

CQ:Are these programs equivalent?

A: YesB: No

x = 0y = 0

for k in range(5):x = x + ky = x + k

print (y)

x = 0y = 0

for k in range(5):x = x + k

y = x + kprint (y)

1 2

Page 39: CS  17700  Review,  iClicker -Questions Week  15

CQ:Are these programs equivalent?

a = 0while(a < 10): print(a) a = a+1

for a in range(10): print(a)

21

A: yes

B: no

Page 40: CS  17700  Review,  iClicker -Questions Week  15

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

Page 41: CS  17700  Review,  iClicker -Questions Week  15

When might they be equivalent?

What about when a=b?That is, we call the functions and provide the same

values for a and bOutput of nested1(2,2) = output of nested2(2,2)

Page 42: CS  17700  Review,  iClicker -Questions Week  15

String Operations

42

Page 43: CS  17700  Review,  iClicker -Questions Week  15

String Operations

Page 44: CS  17700  Review,  iClicker -Questions Week  15

CQ: Are these programs equivalent?

1.capitalize() “1”.capitalize()21

A: yes

B: no

Page 45: CS  17700  Review,  iClicker -Questions Week  15

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

Page 46: CS  17700  Review,  iClicker -Questions Week  15

CQ: Are these programs equivalent?

i = 0x = “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

Page 47: CS  17700  Review,  iClicker -Questions Week  15

What is going on here?

x = “This is a string”for y in x: print (y)

Txhis

i….

y = x[j]

Under the hood we are doing something similar to:

Page 48: CS  17700  Review,  iClicker -Questions Week  15

CQ: Are these programs equivalent?

i = 0x = “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

Page 49: CS  17700  Review,  iClicker -Questions Week  15

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

Page 50: CS  17700  Review,  iClicker -Questions Week  15

ListOperations

50

Page 51: CS  17700  Review,  iClicker -Questions Week  15

List

Page 52: CS  17700  Review,  iClicker -Questions Week  15

List

Page 53: CS  17700  Review,  iClicker -Questions Week  15

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

Page 54: CS  17700  Review,  iClicker -Questions Week  15

CQIs this list empty?

[ [ ] ]

A: This list is empty

B: This list is not empty

Page 55: CS  17700  Review,  iClicker -Questions Week  15

CQ: What is S[:] ?A. SB. S[0:0]C. S[0:len(S)]

Page 56: CS  17700  Review,  iClicker -Questions Week  15

56

CQ: How many?What does the following program print?S = "a,b,,d,e"print(len(S.split(",")))

A. 8B. 5C. 4

Python Programming, 2/e

Page 57: CS  17700  Review,  iClicker -Questions Week  15

Decision Tree

57

Page 58: CS  17700  Review,  iClicker -Questions Week  15

Example: Directory trees

Page 59: CS  17700  Review,  iClicker -Questions Week  15

We call this structure a tree

Root

Root

Page 60: CS  17700  Review,  iClicker -Questions Week  15

Trees can be more complex

Tree = [‘Root’, ‘Leaf1’, ‘Leaf2’, [‘Node1’, ‘Leaf3’, ‘Leaf4’, ‘Leaf5’]]

Root

Leaf1 Leaf2

Leaf3 Leaf4 Leaf5

Node1

Page 61: CS  17700  Review,  iClicker -Questions Week  15

Trees can be more complex

Tree = [‘Root’, ‘Leaf1’, ‘Leaf2’, [‘Node1’, ‘Leaf3’, ‘Leaf4’, ‘Leaf5’]]

Root

Leaf1 Leaf2

Leaf3 Leaf4 Leaf5

Node1

Page 62: CS  17700  Review,  iClicker -Questions Week  15

Trees can be more complex

Tree = [‘Root’, ‘Leaf1’, ‘Leaf2’, [‘Node1’, ‘Leaf3’, ‘Leaf4’, ‘Leaf5’]]

Root

Leaf1 Leaf2

Leaf3 Leaf4 Leaf5

Node1

Page 63: CS  17700  Review,  iClicker -Questions Week  15

Indices allow us to “traverse” the tree

Root

Leaf1

Leaf2

Leaf3 Leaf4

Leaf6Tree = [‘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

Page 64: CS  17700  Review,  iClicker -Questions Week  15

Recursion

64

Page 65: CS  17700  Review,  iClicker -Questions Week  15

Recursion

Page 66: CS  17700  Review,  iClicker -Questions Week  15

Recursion

Page 67: CS  17700  Review,  iClicker -Questions Week  15

Traversing a Tree

Page 68: CS  17700  Review,  iClicker -Questions Week  15

68

Recursion : String Reversal

def reverse(s): if s == "": return s else: return reverse(s[1:]) + s[0]

>>> reverse("Hello")'olleH'

Page 69: CS  17700  Review,  iClicker -Questions Week  15

Dictionary

69

Page 70: CS  17700  Review,  iClicker -Questions Week  15

Dictionary Syntax: {‘Unique_Key’:value}

Page 71: CS  17700  Review,  iClicker -Questions Week  15

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

Page 72: CS  17700  Review,  iClicker -Questions Week  15

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’] = 5A[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'}

Page 73: CS  17700  Review,  iClicker -Questions Week  15

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

Page 74: CS  17700  Review,  iClicker -Questions Week  15

Operations on TuplesConcatenation:

(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) produces 15 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)

Page 75: CS  17700  Review,  iClicker -Questions Week  15

Big-ONotation

75

Page 76: CS  17700  Review,  iClicker -Questions Week  15

Big-O Notation

Page 77: CS  17700  Review,  iClicker -Questions Week  15

Why Size Matters?

Page 78: CS  17700  Review,  iClicker -Questions Week  15

Identify the term that has the largest growth rate

Num of steps growth term asympt. complexity6n + 3 6n O(n)2n2 + 6n + 3 2n2 O(n2)2n3 + 6n + 3 2n3 O(n3)2n10 + 2n + 3 2n O(2n)n! + 2n12 + 2n + 3 n! O(n!)

Page 79: CS  17700  Review,  iClicker -Questions Week  15

CQ: Arithmetic SeriesLet . ThenA. T(n) is O(n)B. T(n) is O(n2)C. T(n) is O(n3)

Page 80: CS  17700  Review,  iClicker -Questions Week  15

Clicker Questiondef getFirst(list): if len(list) == 0: return -1 return (list[0])

A: O(n) B: O(n2)C: O(1)

>>> getFirst([])-1>>> getFirst([0,1,2,3])0>>> getFirst(["a", "b", "c"])'a’

Page 81: CS  17700  Review,  iClicker -Questions Week  15

Sorting Arrays

81

Page 82: CS  17700  Review,  iClicker -Questions Week  15

How to find an alienLogic 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?

Page 83: CS  17700  Review,  iClicker -Questions Week  15

Solution 1: Weigh one marble vs another

What is the complexity of this solution?

Page 84: CS  17700  Review,  iClicker -Questions Week  15

Finding the ComplexityStep 1: What is our input?

The marblesStep 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 measurementsWhat if we had 100 marbles or 1000?

Page 85: CS  17700  Review,  iClicker -Questions Week  15

Clicker Question: What is the complexity of this

algorithm?

A: O(n)

B: O(n2)C: O(1)

D: O(log n)

Page 86: CS  17700  Review,  iClicker -Questions Week  15

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 measurementHow might we do this?

What about weighing multiple marbles at once?

Page 87: CS  17700  Review,  iClicker -Questions Week  15

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 measurementsWhat if we had 100 marbles or 1000?

Page 88: CS  17700  Review,  iClicker -Questions Week  15

What happens at each step?

We eliminated 2/3rds of the marbles

Page 89: CS  17700  Review,  iClicker -Questions Week  15

Clicker Question: What is the complexity of this

algorithm?

A: O(n)

B: O(n2)C: O(1)

D: O(log n)

Page 90: CS  17700  Review,  iClicker -Questions Week  15

Big-O – Sorting ArraysType of Sort Best Worst Average Memory

Space

Bubble Sort O(N) O(N2) O(N2) 1

Selection SortO(N2) O(N2) O(N2) 1

Heap SortO(N log N) O(N log N) O(N log N) 1

Merge Sort O(N log N) O(N log N) O(N log N) Worst =N

Page 91: CS  17700  Review,  iClicker -Questions Week  15

O(n2) – that is too much !Selection sort repeatedly extracts max, O(n)

timesEach max extraction is O(n) comparisonsSo selection sort is O(n2) -- not very goodProblem:

After extracting the max, we get no help extracting the max in the remaining slice

Can we fix that?

Page 92: CS  17700  Review,  iClicker -Questions Week  15

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,…

Page 93: CS  17700  Review,  iClicker -Questions Week  15

Example Tree, Encoding & Access

Tree encoding: a = [9, 6, 4, 5, 1, 2]

9

6 4

5 21

2:1:

0:

3: 4: 5: 6:

Access Mappings: Parent to left child: Parent to right child: Child to parent:

• Find Parent of: 4 a[2]=4 i=(2-1)//2 = 0 Parent is at a[0] =9

Page 94: CS  17700  Review,  iClicker -Questions Week  15

Heap Representation

Page 95: CS  17700  Review,  iClicker -Questions Week  15

Step- 1

Step-3

Step- 2

Heap- Insert

Page 96: CS  17700  Review,  iClicker -Questions Week  15

Complexity: Tree StatsWith n the number of items in the list, how high is the

tree?n height1: 12-3: 24-7: 38-15: 4

2k-(2k+1-1): k+1So if the list has n elements, it encodes a tree of height Therefore, insertion and deletion of one element takes

steps

Page 97: CS  17700  Review,  iClicker -Questions Week  15

Tree-Complexity

Page 98: CS  17700  Review,  iClicker -Questions Week  15

CQ: Is this a Priority Queue?

A. YesB. No

9

6 4

5 24

2:1:

0:

3: 4: 5: 6:

x

y z

≥≥

Page 99: CS  17700  Review,  iClicker -Questions Week  15

CQ: Is this a Priority Queue?

A. YesB. No

9

5 4

6 24

2:1:

0:

3: 4: 5: 6:

Page 100: CS  17700  Review,  iClicker -Questions Week  15

CQ: Is this a priority queue?

[9,8,4,7,3,2,5,6,1]

A. YesB. No

Page 101: CS  17700  Review,  iClicker -Questions Week  15

CQ: how many children for L[5]?

[9,7,4,6,5,4,2,2,1,1,1,1]

A. 0B. 1C. 2

Page 102: CS  17700  Review,  iClicker -Questions Week  15

CQ: how many children for L[5]?

[9,7,4,6,5,4,2,2,1,1,1,1]

A. 0B. 1C. 2

9

7 4

56 4 2

2 1 1 1 1

Page 103: CS  17700  Review,  iClicker -Questions Week  15

Merge Sort

log(n)n elementsmerged

Page 104: CS  17700  Review,  iClicker -Questions Week  15

Putting it all togetherWe know that there are log(n) splits

At each “level” we split each list in twoWe know that we need to merge a total of n

elements at each “level”n * log(n) thus O(n log n)