CS 17700 Review, iClicker -Questions Week 15

Post on 25-Feb-2016

46 views 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

1

CS 17700 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: maybeB: no

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

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

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)

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

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

Clicker Question:Are these programs

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

a = 3print (a)

21

A: yes

B: no

Clicker Question: does this program print 3 or 4?

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

A: 3

B: 4

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

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

ERROR!

ERROR!

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

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

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

Clicker Question: Is x global or local?

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

A: global

B: local

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!

Conditionals and Loops

20

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

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

if x > 10

print x

x = x + 1

End

True False

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

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

if x > 10

print x

End

True False

x = 7

x = x + 1

Truth Tables

and True FalseTrue True FalseFalse False False

or True FalseTrue True TrueFalse True False

not True False

False True

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

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

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)

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

Tests ContinuedWe 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 < 10 and y >= 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

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

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

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

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

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

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

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 bOutput 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 = 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

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:

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

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

ListOperations

50

List

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

CQIs this list empty?

[ [ ] ]

A: This list is empty

B: This list is not empty

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

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

Decision Tree

57

Example: Directory trees

We call this structure a tree

Root

Root

Trees can be more complex

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

Root

Leaf1 Leaf2

Leaf3 Leaf4 Leaf5

Node1

Trees can be more complex

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

Root

Leaf1 Leaf2

Leaf3 Leaf4 Leaf5

Node1

Trees can be more complex

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

Root

Leaf1 Leaf2

Leaf3 Leaf4 Leaf5

Node1

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

Recursion

64

Recursion

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

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

Big-ONotation

75

Big-O Notation

Why Size Matters?

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

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

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’

Sorting Arrays

81

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?

Solution 1: Weigh one marble vs another

What is the complexity of this solution?

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?

Clicker Question: What is the complexity of this

algorithm?

A: O(n)

B: O(n2)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 measurementHow 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 measurementsWhat 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(n2)C: O(1)

D: O(log n)

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

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?

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]

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

Heap Representation

Step- 1

Step-3

Step- 2

Heap- Insert

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

Tree-Complexity

CQ: Is this a Priority Queue?

A. YesB. No

9

6 4

5 24

2:1:

0:

3: 4: 5: 6:

x

y z

≥≥

CQ: Is this a Priority Queue?

A. YesB. No

9

5 4

6 24

2:1:

0:

3: 4: 5: 6:

CQ: Is this a priority queue?

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

A. YesB. No

CQ: how many children for L[5]?

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

A. 0B. 1C. 2

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

Merge Sort

log(n)n elementsmerged

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)