Sort by

recency

|

1588 Discussions

|

  • + 0 comments

    from collections import Counter n = int(input()) l = [] for i in range(n): word = input() l.append(word) val = Counter(l) print(len(val.keys())) for x,y in val.items(): print(y, end=' ')

  • + 0 comments

    Before Python 3.7, the order is not guaranteed in dictionaries:

    from collections import Counter, OrderedDict
    
    class OrderedCounter(Counter, OrderedDict): 
        pass
    
    words = OrderedCounter(input() for _ in range(int(input())))
    print(len(words))
    print(*words.values())
    

    Since Python 3.7, the order is guaranteed to be kept in dictionaries which makes the code even simpler:

    from collections import Counter
    
    words = Counter(input() for _ in range(int(input())))
    print(len(words))
    print(*words.values())
    
  • + 0 comments

    Use OrderedDict to preserve the order of input words. Loop over input lines, setting each word's count to zero initially. Update each word's count as it appears. Finally, print the count of unique words and their occurrences.

  • + 0 comments
    n = int(input())
    words = {}
    
    for i in range(n):    
        key = input()
        if key in words:
            words[key] += 1
        else:
            words[key] = 1
    
    print(len(words))
    print(*words.values())
    
  • + 0 comments

    Here's my codes.

    using native:

    res = {}
    for i in range(int(input())):
        u = input()
        if u in res:
            res[u] += 1
            continue
        res[u] = 1
    print(len(res.keys()))
    print(*res.values())
    

    with Counter func:

    from collections import Counter
    res = Counter(input() for _ in range(int(input())))
    print(len(res.keys()))
    print(*res.values())