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

19 lines
505 B
Python

try:
from common.inputChecking.typeCheck import inputTypeCheck
except ModuleNotFoundError:
print('Sjekk README.md for hvilke flagg python trenger')
exit(1)
def alternateSum(n):
positiveNumbers = [
num**2 for num in [i for i in range(1, n + 1) if i % 2 != 0]
]
negativeNumbers = [
-num**2 for num in [i for i in range(1, n + 1) if i % 2 == 0]
]
return sum(positiveNumbers + negativeNumbers)
if __name__ == "__main__":
n = inputTypeCheck('n: ', int)
print(alternateSum(n))