3.17

Take the two codes above and combine them so one input gives the output that contains both the hailstone numbers and the number of iterations it takes i = 1. The more efficient the code, the higher your grade will be. (Algorithm Efficiency) (.25)

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)
Please enter a number: 
Number of iterations: 6
[10, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]

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])) 
[1, 2, 3, 4, 5]
list = [5,3,2,1,4]
list.sort()
print(list)
[1, 2, 3, 4, 5]

My algorithm works similarly to the "inefficient" algorithm shown in the examples for a multitude of reasons

  1. 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.
  2. A built in sort function will take less RAM than a bunch of code that makes a procedure
  3. Since there is less code, many less errors can occur (plus a built in function can sort all numbers, including floats and alphabetical orders)
  4. Takes up less room
  5. 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!")
Waking up now!
Eating now
I'm gonna go for a walk
I'm going to school!