-3

I wrote this program:

from collections import defaultdict

num = int(input())
mylist = defaultdict(list)
#Horror = Romance = Comedy = History = Adventure = Action = []

for i in list(range(num)):
    str = input()
    #lst.append(str)
    word = str.split()
    for i in word[1:]:
        if i == "Horror":
            mylist["Horror"].append(word[0])
        if i == "Romance":
            mylist["Romance"].append(word[0])
        if i == "Comedy":
            mylist["Comedy"].append(word[0])
        if i == "History":
            mylist["History"].append(word[0])
        if i == "Adventure":
            mylist["Adventure"].append(word[0])
        if i == "Action":
            mylist["Action"].append(word[0])


for i in ["Action" , "Comedy" , "History" , "Horror" , "Romance" , "Adventure"]:
    print(f"{i} : {len(mylist[i])}")

I want this program to publish the most interesting genres in order.

example: for this input:

4
hossein Horror Romance Comedy
mohsen Horror Action Comedy
mina Adventure Action History
Farhad Romance Horror Action

i want to get this output:

Action : 3
Horror : 3
Comedy : 2
Romance : 2
Adventure : 1
History : 1

Please help me.

...............................................................................................................................................................................

  • Does this answer your question? [Sorted Word frequency count using python](https://stackoverflow.com/questions/4088265/sorted-word-frequency-count-using-python) – thinkgruen Nov 01 '21 at 09:16

1 Answers1

0
from collections import defaultdict

num = int(input())
mylist = defaultdict(list)
genres = {'Action':0,'Adventure':0,'Comedy':0,'History':0,'Horror':0,'Romance':0}

for i in list(range(num)):
    str = input()
    word = str.split()
    for i in word :
        if i in genres.keys():
            genres[i] = genres[i] + 1

l = list(genres.values())
l.sort(reverse=True)
M = []
for i in l :
    for j in genres.keys():
        if genres[j]==i:
            if (j,i) not in M:
                M.append((j,i))

print(M)
Ayyoub ESSADEQ
  • 776
  • 2
  • 14
  • Thanks, but how do I print genres that are equal in alphabetical order? – hello world Oct 30 '21 at 12:45
  • I make some edits on the order of type movies in `genres` , in this way you will all the time get the output in alphabetical order . – Ayyoub ESSADEQ Oct 30 '21 at 13:19
  • Caveat: This solution only works when `genres` is already sorted by keys. I think the counting dictionary should be built dynamically. Some other improvements: Firstly the wrapping of `list(range(num))` and `list(genres.values())` are both redundant. I also wouldn't advice using the same variable name `i` for both outer and inner loops. – thinkgruen Nov 02 '21 at 08:56