Search code examples
pythonarraysstring-comparison

Is there an easier way to compare the count of data in an array with each other in Python?


I needed to compare the count of data stored in an array for a tie in a voting system.


if votes.count(1) == votes.count(2) or votes.count(1) == votes.count(3) or votes.count(1) == votes.count(4) or votes.count(2) == votes.count(1) or  votes.count(2) == votes.count(3) or votes.count(2) == votes.count(4) or votes.count(3) == votes.count(1) or votes.count(3) == votes.count(4) or votes.count(3) == votes.count(2) or votes.count(4) == votes.count(1) or votes.count(4) == votes.count(3) or votes.count(4) == votes.count(2):

Votes would be stored in the array in number form. So if you were to vote for the first candidate, it would be stored as '1' and so on. I wanted to know if there was an easier way to check if there was a tie between not all of the candidates, but for example two.


Solution

  • store the Count of each element and store them in the form of list. Then check use set to remove duplicate and check whether the length of the set is equal to the list

    Try something like this.:

    votes = [1, 1, 1, 1, 5, 5, 3, 3, 3, 4]
    
    lst = [votes.count(x) for x in list(set(votes))]
    
    print('No tie' if len(set(lst))==len(lst) else 'tie' )
    

    But I would suggest using a dictionary:

    vote = {'candidate1': 3, 'candidate2': 5, 'candidate3':5}
    
    print('No tie' if len(set(list(vote.values())))==len(list(vote.values())) else 'tie')
    

    And If you want to know the candidates with tie votes try this:

    vote = {'candidate1': 3, 'candidate2': 5, 'candidate3':5}
    
    print('No tie' if len(set(list(vote.values())))==len(list(vote.values())) else 'tie')
    
    duplicate = []
    
    for cand, value in vote.items():
        if list(vote.values()).count(value) > 1:
            duplicate.append(cand)
        
    print(duplicate)