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

28 lines
583 B
Python

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 = int(input('k: '))
alternateSumStopAt(k)