This Python script demonstrates the use of defaultdict from the collections module. It takes two integers as input, followed by a series of words. The script then maps each word to its index and prints these indices for a given set of words.
CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷
The script uses defaultdict from the collections module in Python. It initializes a defaultdict with list as the default factory. It then takes two integers as input, 'n' and 'm'. For 'n' times, it takes a word as input and appends its index (1-indexed) to the defaultdict entry for that word. For 'm' times, it takes a word as input and prints the indices of that word in the previous list of words. If the word is not found, it prints -1. The key approach here is the use of defaultdict which allows to append to a list for each word without initializing the list explicitly.
from collections import defaultdict
d = defaultdict(list)
n, m = map(int, input().split())
for i in range(n):
w = input()
d[w].append(str(i + 1))
for _ in range(m):
w = input()
print(" ".join(d[w]) or -1)
If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.
AI is here now, and other candidates might be using it to get ahead and win the job. 🧐
The form has been successfully submitted.