How to count the odd and even sum of pairs in a list with Python

1 Answer

0 votes
def count_odd_and_even_sum_of_pairs(lst):
    total_even = 0
    total_odd = 0
    size = len(lst)

    for i in range(size):
        if lst[i] % 2 == 0:
            total_even += 1
        else:
            total_odd += 1

    # For all the even elements -> sum of the pair will be even
    even_pairs = (total_even * (total_even - 1)) // 2

    # For all the odd elements -> sum of the pair will be even
    even_pairs += (total_odd * (total_odd - 1)) // 2

    # All even elements * all odd element -> sum of the pair will be odd
    odd_pairs = total_even * total_odd

    return even_pairs, odd_pairs


lst = [1, 2, 3, 4, 5]

# 1 + 3, 1 + 5, 2 + 4, 3 + 5 = 4 Even
# 1 + 2, 1 + 4, 2 + 3, 2 + 5, 3 + 4, 4 + 5 = 6 Odd

even_pairs, odd_pairs = count_odd_and_even_sum_of_pairs(lst)

print("Total Even Sum =", even_pairs)
print("Total Odd Sum =", odd_pairs)



'''
run:

Total Even Sum = 4
Total Odd Sum = 6

'''

 



answered Jun 17, 2024 by avibootz

Related questions

1 answer 121 views
1 answer 157 views
1 answer 126 views
1 answer 130 views
1 answer 113 views
...