Task:
Complete the following function that determines if the number of even and odd values in an list of Integers is the same.
| In | Out | Why |
|------------------|-------|------------------------|
| [5, 1, 0, 2] | true | two evens and two odds |
| [5, 1, 0, 2, 11] | false | too many odds |
| [] | true | both have 0 |
The function should not affect the contents of the list.
My code:
def balanced(lst):
n = len(lst)
if n % 2 != 0:
return False
if n % 2 == 0:
count_1 = 0
count_2 = 0
for item in lst:
if item % 2 == 0: #even
count_1 += 1
if item % 2 != 0: #odd
count_2 += 1
if count_1 == count_2:
return True
else:
return False
def result(lst):
if balanced(lst):
print("Your list is successfully balanced! It has same number of evens and odds!!")
else:
print("Oh no! Sorry! Your list seems to be not balanced! Try another list please!")
def main():
lst_1 = [1,2,3,5,6,8,5,9]
lst_2 = []
lst_3 = [2,4,5,7]
lst_4 = [1,2,4,4]
lst_5 = [1,2,3]
result(lst_1)
result(lst_2)
result(lst_3)
result(lst_4)
result(lst_5)
main()