Trying to make a function that returns a tuple of the number of odds and evens in a list [closed]
Trying to make a function that returns a tuple of the number of odds and evens in a list [closed]
I tried to do value1 if expression1 else value2 for loop
value1 if expression1 else value2 for loop
odds_evens(lista) = [odd,even odd+=1 if lista[i]%2==0 else even+=1 for i in range[0,len(lista)]]
What am I doing wrong?
I expect odds_evens([1,2,3]) to give the answer (2,1)
odds_evens([1,2,3])
(2,1)
Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.
even odd
You haven't defined a function. You can't do
+= , an assignment, in conditional expressions– wwii
Sep 11 '18 at 2:30
+=
So heres what I think is going on, he wants to print a tuple (num_odds, num_evens) and he is using a comprehension to count and add the totals to the tuple.
– vash_the_stampede
Sep 11 '18 at 2:31
Welcome to SO. Please take the time to read How to Ask, Minimal, Complete, and Verifiable example, and the other links found on that page.
– wwii
Sep 11 '18 at 2:34
4 Answers
4
Solution without for-loops:
def odds_evens(lista):
return (sum(num%2 == 1 for num in lista), sum(num%2 == 0 for num in lista))
if __name__ == '__main__':
print(odds_evens([1,2,3]))
If you really needed to use a for loop, here's a way to do it:
def odds_evens(lista):
odd = 0, even = 0 # Variable Initialization
for i in range(0, len(lista)): # You did range. range is a method - range()
if lista[i]%2==0:
even+=1
else:
odd+=1
return (odd, even) # Returns a tuple
if __name__ == '__main__':
print(odds_evens([1,2,3]))
Show your second solution first. Can entirely avoid for-loops.
– smci
Sep 11 '18 at 3:04
@smci I updated it.
– Meyi
Sep 11 '18 at 3:06
Solution
Before you jump into the comprehension, its easier to construct the code more in the more expanded version
lista = [1, 2, 3]
odds = 0
evens = 0
for i in range(len(lista)):
if lista[i]%2 == 0:
evens += 1
else:
odds += 1
odds_evens = (odds, evens)
print(f"odds_evens = odds_evens")
Output
(xenial)vash@localhost:~/python/AtBS$ python3.7 pattern.py
odds_evens = (2, 1)
Use a list comprehension and exploit the neat function list.count(value). No need for for-loops:
list.count(value)
def odds_evens(lista):
remainder = [x % 2 for x in lista]
return (remainder.count(0), remainder.count(1))
>>> lista = [1,2,3,5,7,8,9,10,12,13,17]
>>> odds_evens(lista)
(4, 7)
Only the even (or odd) numbers need to be counted.
def odds_evens(lista):
even = 0
for i in lista:
if i%2==0:
even += 1
return (even, len(lista) - even)
I've got a lot of questions. First of all, what is
even odd? Also, try expanding this into a regular for loop and if statement.– OldBunny2800
Sep 11 '18 at 2:30