Previous Lecture Lecture 8 Next Lecture

Lecture 8, Thu 04/25

Algorithm Analysis, Python List and Dictionary

Slides folder

Recorded video

Plan for today

Quick Notes

Derive the Order of Magnitude (Big-O)

Time Complexity Iclicker Questions

Question 1:

def print_pair(n):
  for i in range(n):
	 for val in range(n):
		print(i, val) 

Question 2:

def print_pair(n):
  for i in range(n):
	 for val in range(n*n):
		print(i, val) 

Time complexity: O(n^3)

Question 3

def print_pair(n):
  for i in range(n):
	 for val in range(n):
		print(i, val) 

for num in range(0, 1000):
  print_pair(num)

Even though the for loop runs in constant time, its body runs in quadratic as we saw earlier.

However, because this specific algorithm is driven by num, which is constant, the entire algorithm is constant O(1).

As a sanity check, if we were to plug our nested for loops from the function into the for num in range(0, 1000): loop, we’ll see that the n in those loops becomes fixed to 1000 as its max value.

Question 4:

def print_pair(n):
  for i in range(n):
	 if i == 100:
		break
	 for val in range(n):
		print(i, val) 

Rememeber: break gets us out of the innermost loop that it is housed in.

Question 5:

def print_pair(n):
  for i in range(n):
	 if i == 100:
		break
	 print(**i)
  for val in range(n):
	 print(i*val) 

Because of the loop sequencing: Time complexity: O(n) = O(1) + O(n)

Question 6:

def print_pair(n):
  for i in range(n):
	 if i == 100:
		return
 	 print(**i)
  for val in range(n):
	 print(i*val) 

Time complexity: O(1)

Question 7:

def print_pair(n):
  i = 0
  for j in range(n):
	 while i < j:
		print(i, j) 
		i += 1

Time complexity:

Question 8:

def print_pair(n):
  i = 0
  for j in range(n):
	 while i <= j:
		print(i, j) 
		i += 1
  	 i = 0

Time complexity:

Question 9:

def print_pair(n):
  for i in range(n):
	 for j in range(n, 0, -1):
		if i == j:
			break
		print(i, val) 

break gets us out of the innermost loop

Time complexity: O(n^2)

Student questions

Python Lists Vs Dictionaries Demo