We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Python
- Collections
- Word Order
- Discussions
Word Order
Word Order
Sort by
recency
|
1614 Discussions
|
Please Login in order to post a comment
First tried a few loops, worked but slow so didn't pass:
So did a one pass attempt which works and passed:
import collections
n = int(input()) odi = collections.OrderedDict()
for word in range(n): word = input() odi[word] = odi.setdefault(word, 0) + 1
print(len(odi)) print(*list(odi.values()))
This was using OrderedDict and setdefault()
Dont crtl c/v ! Read and pls try to comprehend
n = int(input()) # Number of words l = [] # List to store the words seen = {} # Dictionary to keep track of occurrences
for i in range(n): word = input() # Input the word l.append(word) # Append word to list if word in seen: seen[word] += 1 # Increment count if word is already in the dictionary else: seen[word] = 1 # Initialize count to 1 if it's the first occurrence of the word
result = [] for word in l: if seen.get(word) is not None: result.append(seen[word]) # Append the count of occurrences del seen[word] # Remove the word from the dictionary to avoid duplicates in output
print(len(result)) # Print the number of distinct words print(*result) # Print the counts of occurrences in the order of appearance
from collections import defaultdict
dic=defaultdict(int)
for i in range(int(input())):
print(len(dic))
print(' '.join([ str(dic[x]) for x in dic.keys() ]))