3.17 and 3.18 Hacks
def collatz(i):
while i != 1:
if i % 2 > 0:
i =((3 * i) + 1)
list_.append(i)
else:
i = (i / 2)
list_.append(i)
return list_
print('Please enter a number: ', end='')
while True:
try:
i = int(input())
list_ = [i]
break
except ValueError:
print('Invaid selection, try again: ', end='')
l = collatz(i)
print('')
print('Number of iterations:', len(l) - 1)
print(l)
3.17 Algorithm Efficiency
Hacks/assignment
- Write 2 algorithms: One is efficent and one is innefficent, then explain why one is efficent while the other isn't. (.25)
- Explain why one algorithm is more efficient than another using mathematical and/or formal reasoning. (.25)
- use variables, if statements, and loops to program your algorithm and upload to jupyter notebooks/ fastpages. (.25)
def inefficientWay(numbers):
# Then it loops over the numbers
for i in range(len(numbers)):
# Now it finds the minimum number in the unsorted part of the list
min_index = i
for j in range(i+1, len(numbers)):
if numbers[j] < numbers[min_index]:
min_index = j
# Then it swaps the minimum number with the first unsorted number
numbers[i], numbers[min_index] = numbers[min_index], numbers[i]
return numbers
# test the algorithm
print(inefficientWay([2, 4, 5, 1, 3]))
list = [5,3,2,1,4]
list.sort()
print(list)
My algorithm works similarly to the "inefficient" algorithm shown in the examples for a multitude of reasons
- My algorithm uses a built in sort function, which ultimately leads to my code being shorter than the inefficient code; this saves a lot of time.
- A built in sort function will take less RAM than a bunch of code that makes a procedure
- Since there is less code, many less errors can occur (plus a built in function can sort all numbers, including floats and alphabetical orders)
- Takes up less room
- Faster because the sort function (one step) is faster than running multiple steps.
tasks = ["Morning", "Hungry", "Stressed", "School"]
for item in tasks:
if item == "Morning":
print("Waking up now!")
if item == "Hungry":
print("Eating now")
if item == "Stressed":
print("I'm gonna go for a walk")
if item == "School":
print("I'm going to school!")