'How would I print the sum of my range for my code?
Code for printing a range where odd numbers are negative and even numbers are positive. Need help with adding the sum of the range.
def evenoddsequence(i):
for i in range(i):
if i%2 != 0:
i = i*-1
print(i, end=" ")
elif i == None:
return i
else:
print(i, end=" ")
print()
result = evenoddsequence(7)
print("Sum of terms in the sequence:", result)
Solution 1:[1]
I think you are overcomplicating things. What you want to do is to change the sign for every other element in the sequence:
x->(-1)**(x%2)*x
i.e. 0->0, 1->-1, 2->2, 3->-3. So you can just apply this function to every element in the sequence and get a new sequence:
[(-1)**(x%2)*x for x in range(7)] -> [0, -1, 2, -3, 4, -5, 6]
Given that your function is named evenoddsequence I would suggest returning that and do the sum outside:
def evenoddsequence(i):
return [(-1)**(x%2)*x for x in range(i)]
print(sum(evenoddsequence(7)))
or rename it to say sum_of_evenoddsequence:
def sum_of_evenoddsequence(i):
return sum([(-1)**(x%2)*x for x in range(i)])
print(sum_of_evenoddsequence(7))
FWIW, you may notice that you add -1 to the sum for every other element:
0-1, 2-3, 4-5, ...
if there are an odd number of elems the sum will be positive, otherwise negative. The absolute value of the sum will therefor be half the length of the sequence:
(len(range(i))//2)*(-1)**len(range(i-1))
A less cryptic version:
def g(i):
if i%2==0:
return -1*(i//2)
else:
return i//2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
