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

19 lines
505 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 alternateSum(n):
2020-09-14 16:36:09 +02:00
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]
]
2020-09-14 14:34:03 +02:00
return sum(positiveNumbers + negativeNumbers)
2020-09-14 16:36:09 +02:00
2020-09-14 14:34:03 +02:00
if __name__ == "__main__":
2020-09-23 11:09:25 +02:00
n = inputTypeCheck('n: ', int)
2020-09-14 14:34:03 +02:00
print(alternateSum(n))