I have a list of odd numbers but I still need to add them:
for n in range(100, 200):
if n % 2 == 1:
print sum([n])
I have a list of odd numbers but I still need to add them:
for n in range(100, 200):
if n % 2 == 1:
print sum([n])
If you are looking to sum the odd numbers in the range of 100 to 200, then the most straight forward way would be:
sum(range(101, 200, 2))
Start at 101 (odd), go till 199 (odd) and increment by 2 so that each number is odd. For instance,
>>> range(101, 110)
[101, 102, 103, 104, 105, 106, 107, 108, 109]
Then you can just sum them.
If you have a preexisting list of numbers then either of the two following methods should fit your need:
>>> nums = [1, 2, 4, 5, 6, 9, 11, 15, 20, 21]
>>> sum(filter(lambda x: x % 2, nums))
62
>>> sum(num for num in nums if num % 2)
62
And this is probably what you were trying to do:
>>> total = 0
>>> for num in nums:
... if num % 2:
... total += num
...
>>> total
62
The sum of all numbers from 1 to N (inclusive) is N * (N + 1) / 2.
def sum_all(N):
return N * (N + 1) // 2
The sum of all even numbers from 1 to N (inclusive) is double the sum of all numbers from 1 to N//2.
def sum_even(N):
return sum_all(N // 2) * 2
The sum of all odd numbers from 1 to N (inclusive) is the difference of these.
def sum_odd(N):
return sum_all(N) - sum_even(N)
Finally, the sum of all odd numbers between a and b is the sum of all odd numbers from 1 to b minus the sum of all odd numbers from 1 to a - 1.
def sum_odd_range(a, b):
return sum_odd(b) - sum_odd(a - 1)
To answer the original question:
print sum_odd_range(100, 199)
Note that unlike solutions using sum(), these are O(1) and will be arbitrarily faster for larger inputs.