Unit 3.17 & 3.18 Hacks
iterations = 0
def collatz(i):
while i > 1:
if (i % 2):
i = 3*i + 1
else:
i = i//2
print(i, end=' ')
global iterations
iterations += 1
i = int(input('Enter i: '))
print("Input:", i, "\nSequence: ", end=" ")
collatz(i)
print("\nNumber of iterations:",iterations)
numList = [9,12,49,22,1,59,3,2,55,47,34]
sum = 0
for x in range(len(numList)):
sum += numList[x]
print(sum)
numList = [9,12,49,22,1,59,3,2,55,47,34]
sum2 = 0
for x in range(len(numList)):
for i in range(numList[x]):
sum2 += 1
print(sum2)
The first one is more efficient because it has less code and less iterations that need to take place. In the second one it is inefficient because it repeats the addition many more times than the first one.
The first one is more efficient because it is adding the values to the sum for each number. The second one is inefficient because it is adding 1 to the sum the amount of times of whatever the number in the list is and doing this for every number. So if the number was 5 it would add 1, 5 times to the sum. This would make it iterate a lot more than the efficient one.
numList = [9,12,49,22,1,59,3,2,55,47,34]
sum = 0
if sum == 0:
for x in range(len(numList)):
sum += numList[x]
print("Sum of:", numList, "is", sum)