-3

so i been giving a list with numbers, I need to grab the odd numbers from the list and sum them, the problem is that I need to only grab the first 5 odd numbers from the list on a while loop, this is what i came up with:

num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69 , 113, 166]
runs = 0
odd = []


while runs <=5:
    for i in num_list:
        if i % 2 == 1:
            odd.append(i)
            runs += 1
print(odd)

the code runs but my counter is not working, it appends all the odd numbers instead of the first 5 it finds on the iteration, what is wrong here?

EDIT: thank you all for the answers, It would be easier to do it without the while loop but they asked me to use the while loop.

Alex
  • 3
  • 3
  • 3
    Does this answer your question? [How to step through Python code to help debug issues?](https://stackoverflow.com/questions/4929251/how-to-step-through-python-code-to-help-debug-issues) – mkrieger1 Sep 18 '21 at 18:08
  • 3
    `list(islice((i for i in num_list if i % 2), 5))` [`islice()`](https://docs.python.org/3/library/itertools.html#itertools.islice) – Olvin Roght Sep 18 '21 at 18:17

5 Answers5

2

You don't need the outer while loop. It is only repeating the procedure 5 times. This should work.

num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69 , 113, 166]
runs = 0
odds = []

for n in num_list:
    if n % 2 == 1:

        odds.append(n)
        runs += 1
        if runs == 5:
            break
print(odds)
Zain Sarwar
  • 1,226
  • 8
  • 10
  • This is the most reasonable answer so far (one of the answers is just a duplicate of this). Some (extremely) minor quibbles though: `if` is not a function, so writing conditional checks like `if(runs == 5)` is a bit ugly (opinion). Conventionally `i` is more appropriate for index variables, use `n` here (also opinion). Finally, `odd` would be more appropriately named `odds`. I realize you're just copying OP's `odd` list. Pointing this out mostly for future readers. – ddejohn Sep 18 '21 at 18:30
  • 1
    Thanks @ddejohn, I've made the changes you pointed out. – Zain Sarwar Sep 18 '21 at 20:47
1

You are almost there.

But in this case, you don't need two nested loops, you can just check at the end of your for loop if you already got enough numbers, and break the loop.

runs = 0
for i in num_list:
    if i % 2 == 1:
        odd.append(i)
        runs += 1
        if runs == 5:
           break
print(odd)

Or else, you can check the length of your result array instead of counting the number of runs.

odd = []
for i in num_list:
    if i % 2 == 1:
        odd.append(i)
        if len(odd) == 5:
          break
print(odd)

As you progress in you journey of learning python, you might get to know other techniques that could be used for a task like this. For example, using list comprehensions.

odd = [i for i in array if i % 2 == 1][:5]

That implementation has the disadvantage that it first calculates odd for the whole array, then discards everything but the first 5. You could get around this by using generators.

odd = (i for i in array if i % 2 == 1)
print(list(next(odd) for _ in range(5)))

The previous snippet is just to show you some new language features. There are problems with that implementation, so I would not really use that.

One of the strong points of python is its great standard library. You might get familiar with the itertools module.

import itertools
odds = (i for i in array if i % 2 == 1)
list(itertools.islice(odds, 5))
Rodrigo Rodrigues
  • 7,545
  • 1
  • 24
  • 36
  • 1
    No point checking the length unless you appended. – no comment Sep 18 '21 at 18:22
  • No point in checking the length at all, running a counter is much more efficient. I'd say just remove that second version altogether. – ddejohn Sep 18 '21 at 18:26
  • FWIW this doesn't add much to the discussion as an existing answer already provides the same solution nearly verbatim. – ddejohn Sep 18 '21 at 18:32
  • The point is just to give OP some different ideas and help him to get better understanding of coding and python. – Rodrigo Rodrigues Sep 18 '21 at 18:44
  • 2
    Another way to slice first N values from generator without `itertools` is to `zip()` generator with range: `print([i for i, _ in zip(odd, range(5))])` – Olvin Roght Sep 18 '21 at 19:14
0

Check out this. You can use the condition in while loop to check the length of odd number's list.

num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69 , 113, 166]
odd = []
i = 0

while len(odd) < 5:
    if num_list[i] %2 != 0:
        odd.append(num_list[i])
    i+=1
       
print(odd)
Yash V. Monpara
  • 126
  • 1
  • 2
  • A `while` loop isn't really appropriate here since we're dealing with a finite number of elements via `num_list`, and hence have an *a priori* knowledge of the upper bound on the number of iterations. That said, it'd be better to run a counter instead of querying the length of `odd` ever iteration, as this is quite an expensive operation. Furthermore, this solution doesn't account for lists which do not contain at least 5 odd numbers, and will raise an `IndexError` in those cases. – ddejohn Sep 18 '21 at 18:26
  • this is exactly what i needed thank you very much, I also tried to do it with length but checking your code i see i wrote the len wrong. – Alex Sep 18 '21 at 18:29
  • @ddejohn Yes, You're right there is a chance of getting `IndexError`. – Yash V. Monpara Sep 19 '21 at 05:29
0

you may consider to create odd generator from num_list, then run 5 times generator to return first 5 odd numbers.

num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69 , 113, 166]
odd=(x for x in num_list if x%2!=0)  # generator will return only odd numbers using source as num_list
sumOdds=0
for i in range(5):
   sumOdds+=next(odd)  # next runs generator and returns value
jozefow
  • 626
  • 3
  • 14
-1

Try this one out.

num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69 , 113, 166]
i=0
odd_nums=[]
while(i < len(num_list)):
      
    # checking condition
    if num_list[i] % 2 != 0 and len(odd_nums)<5:
        odd_nums.append(num_list[i])
      
    # increment i  
    i += 1
print(odd_nums)