TDT4109/Exercise 3/9 - Alternerende sum/task9b.py

34 lines
755 B
Python
Raw Normal View History

2020-09-23 11:09:25 +02:00
try:
from common.inputChecking.typeCheck import inputTypeCheck
except ModuleNotFoundError:
print('Sjekk README.md for hvilke flagg python trenger')
exit(1)
2020-09-14 14:34:03 +02:00
def AlternateNumberGenerator():
isEven = lambda n: n % 2 == 0
n = 1
counter = 2
while True:
yield n
n = n + (-counter**2 if isEven(counter) else counter**2)
2020-09-14 16:36:09 +02:00
counter += 1
2020-09-14 14:34:03 +02:00
def alternateSumStopAt(k):
numGen = AlternateNumberGenerator()
previousN = None
n = next(numGen)
iterations = 0
2020-09-14 16:36:09 +02:00
while n < k:
2020-09-14 14:34:03 +02:00
previousN = n
n = next(numGen)
iterations += 1
2020-09-14 16:36:09 +02:00
print(
f'Summen av tallene før summen blir større enn k er {previousN}. Antall iterasjoner: {iterations}'
)
2020-09-14 14:34:03 +02:00
if __name__ == "__main__":
2020-09-23 11:09:25 +02:00
k = inputTypeCheck('k: ', int)
2020-09-14 14:34:03 +02:00
alternateSumStopAt(k)