Adding odd numbers in a list

前端 未结 6 1002
执笔经年
执笔经年 2021-01-01 03:37

I am trying to find the sum of all odd numbers within a given range but I cannot figure out how to specify which numbers are odd. My professor said to use \"for num in numbe

6条回答
  •  离开以前
    2021-01-01 04:14

    Just to make a quick comment in the form of an answer. If you wanted to make a list of all the odd number in a between 0 and 10, the end points don't matter. If the list was from 0 to 11 then the end point matters. Just remember that range(0,11) = [0,1,2,3,4,5,6,7,8,9,10] and won't include 11.


    Now to explain the generator that is being used. To make to list using numbers as defined by you, you could do this.

    odds = []
    for num in numbers:
        if num % 2 == 1:
            odds.append(num)
    

    This would give you odds = [1,3,5,7,9]. Python has something call list comprehension that make it really easy to do things like this. The above can be easily written like this

    odds = [num for num in number if num % 2 == 1]
    

    and since you want the sum off all the numbers in the list and the sum function takes list, the answer is just

    sum([num for num in number if num % 2 == 1])
    

    Note that most of the answer don't have brackets. This is because without it it becomes a generator.

    odds = (num for num in number if num % 2 == )
    print odds  #-->  at 0x7f9d220669b0>
    odds.next() # 1
    odds.next() # 3
    ...
    

    Since sum takes these as well and generator are faster and less memory intensive than list that is why the best answer is

    sum(num for num in numbers if num % 2 == 1)
    

提交回复
热议问题