Crashers - 3.17 Algorithmic Efficiency Python Hacks
Learn about algorithms and how they can be more or less efficient
Algorithmic Efficiency Hacks: Python
Let’s test your knowledge on algorithmic efficiency!
Hack 1: How Much Time?
Objective: write the time complexity of the algorithm below using Big-O notation.
(don’t worry about special cases such as n = 1 or n = 0).
n = int(input()) # remember what O(n) means? This is a good way of visualizing n.
for i in range(n):
print(i)
#TODO: print the above algorithm's time complexity
Hack 2: Your Turn!
Objective: write an algorithm with O(n^2) time complexity.
n = int(input())
#TODO: Write an algorithm with O(n^2) time complexity
#Hint: think about nested loops...
Hack 3: Gotta Go Fast!
Objective: Optimize this algorithm so that it has a lower time complexity without modifying the outer loop
import math
n = int(input())
count = 0
for i in range(n):
for j in range(math.ceil(math.sqrt(n)*2)):
count += 1
print(count)
#TODO: make this algorithm more efficient, but keep the outer loop and make sure the output is still the same!
#Hint: how does the inner loop affect time complexity?
42
Hack 4: Extra Challenge
Objective: Write an algorithm that does NOT have a time complexity of O(1), O(n), or O(n^x) and identify the time complexity
(I will not accept O(n^3) or some other power, it needs to be more complex.)
n = int(input())
#TODO: Write an algorithm that has a more complicated time complexity than O(n^x).