Task: Complete the following function that determines if the number of even and odd values in an integer list is the same. The function would return true if the list contains 5, 1, 0, 2 (two evens and two odds), but it would return false for the list containing 5, 1, 0, 2, 11 (too many odds). The function should return true if the list is empty, since an empty list contains the same number of evens and odds (0 for both). The function does 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()