0

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])
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
user2803555
  • 161
  • 2
  • 2
  • 10
  • 1
    You only want to sum the odd numbers in the list? – sberry Sep 22 '13 at 06:09
  • Note: `range(100, 200)` is not list of odd number, it has all number from `100 to 199`. – Grijesh Chauhan Sep 22 '13 at 06:42
  • 1
    `sum([n])` makes a list whose only element is the single number `n`, then evaluates the sum of that list, producing `n` again. That's not what you want; you need to keep track of the sum of all the odd numbers you've gone through so far. – user2357112 Sep 22 '13 at 06:43
  • @user2357112 no it is not works like this read Sberry's answer he explained from fundamental also covered how to use `sum()` function. – Grijesh Chauhan Sep 22 '13 at 07:22

2 Answers2

10

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
sberry
  • 128,281
  • 18
  • 138
  • 165
  • `sum(filter(lambda x: x % 2, nums))` could be replace by `sum(nums[: : 2])` Correct? Which one you prefer? – Grijesh Chauhan Sep 22 '13 at 06:37
  • 1
    No, my example was showing numbers that were not in a particular pattern of odd, even, odd, even, odd. So slicing like this will not work. – sberry Sep 22 '13 at 07:10
5

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.

Paul Hankin
  • 54,811
  • 11
  • 92
  • 118