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
- DefaultDict Tutorial
- Discussions
DefaultDict Tutorial
DefaultDict Tutorial
Sort by
recency
|
1110 Discussions
|
Please Login in order to post a comment
from collections import defaultdict import sys input = sys.stdin.read data = input().splitlines()
n, m = map(int, data[0].split()) group_a = data[1:n+1]
group_b = data[n+1:]
word_positions = defaultdict(list)
for idx, word in enumerate(group_a, 1): word_positions[word].append(str(idx))
for word in group_b: if word in word_positions: print(" ".join(word_positions[word])) else: print("-1")
.get() allows a simple way to print the value or -1 and avoids creating new values in defaultdict
Thanks, HackerRank, for making Python collections feel less intimidating. Looking forward to applying this in more complex problems! Cricbet99 club login