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

34 lines
755 B
Python

try:
from common.inputChecking.typeCheck import inputTypeCheck
except ModuleNotFoundError:
print('Sjekk README.md for hvilke flagg python trenger')
exit(1)
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)
counter += 1
def alternateSumStopAt(k):
numGen = AlternateNumberGenerator()
previousN = None
n = next(numGen)
iterations = 0
while n < k:
previousN = n
n = next(numGen)
iterations += 1
print(
f'Summen av tallene før summen blir større enn k er {previousN}. Antall iterasjoner: {iterations}'
)
if __name__ == "__main__":
k = inputTypeCheck('k: ', int)
alternateSumStopAt(k)