0

The input will contain a list of food items where each occurrence of an item represents one vote. You should print the winning food item as output. If there is no clear winner, print "NOTA".

Sample Input:

["pasta","pasta","pasta","pasta","pasta","paratha","paratha","paratha"]

Sample Output:

pasta
import ast,sys
input_str = sys.stdin.read()
votes = ast.literal_eval(input_str)

    d = {}
    for i in votes:
        if i not in d:
            d[i]=1
        else:
            d[i] = d[i] + 1
    for key, value in d.items():
        if value == max(d.values()):
            print("{}".format(key))
khelwood
  • 46,621
  • 12
  • 59
  • 83

1 Answers1

1

You can simplify the dictionary population using a defaultdict.

Then I would use sorted to generate a list of votes in descending order. Then you just need to check if the 2nd vote is equal to the first.

See below:

from collections import defaultdict

votes = ["pasta","pasta","pasta","pasta","paratha","paratha","paratha","paratha"]

count_votes = defaultdict(int)

for vote in votes:
    count_votes[vote] += 1

sorted_votes = sorted(count_votes.items(), key=lambda kv: kv[1], reverse=True)
if len(sorted_votes) > 1:
    if sorted_votes[1][1] == sorted_votes[0][1]:
        print('NOTA')
    else:
        print(sorted_votes[0][0])
alfajet
  • 344
  • 1
  • 11
  • Thanks for replying and providing the answer. Can you explain the code.. what are we trying to receive in sorted_votes the compline line. How come it has two dimensions – Navin Kumar Oct 13 '19 at 18:05
  • @NavinKumar use `statistics.mode` [See this answer](https://stackoverflow.com/a/55553448/10669139) – Avm-x Oct 13 '19 at 19:18