DefaultDict Tutorial | HackerRank
DefaultDict Tutorial | HackerRank
Create dictionary value fields with predefined data types.
www.hackerrank.com
Goal
The first line contains integers, n and m separated by a space.
The next lines contains the words belonging to group A.
The next lines contains the words belonging to group B.
Output m lines.
The i-th line should contain the 1-indexed positions of the occurrences of the i-th word separated by spaces.
Solution
We can practice with defaultdict to solve this task.
Importing the defaultdict class from the collections module
and creating a defaultdict object d that will hold the input values.
Taking two inputs separated by a space and storing them in x and y.
Then using a for loop to iterate int(x) times, taking input values
and appending them to the 'A' key of the defaultdict object d.
Similarly, for int(y) times, taking input values
and appending them to the 'B' key of the defaultdict object d.
Taking two inputs separated by a space and storing them in x and y.
Then using a for loop to iterate int(x) times, taking input values
and appending them to the 'A' key of the defaultdict object d.
Similarly, for int(y) times, taking input values and appending them to the 'B' key of the defaultdict object d.
# DefaultDict Tutorial
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import defaultdict
d = defaultdict(list)
x, y = input().split()
for i in range(int(x)):
d['A'].append(input())
for j in range(int(y)):
d['B'].append(input())
for i in range(len(d['B'])):
value = d['B'][i]
matches = [k+1 for k in range(0,len(d['A'])) if value == d['A'][k]]
if len(matches) == 0:
print("{}".format(-1))
else:
print(*matches,sep=' ')
'software Engineering > (Python)HackerRank' 카테고리의 다른 글
[Python] HackerRank - Collections.namedtuple() (0) | 2023.03.08 |
---|---|
[Python] HackerRank - Exceptions (0) | 2023.03.01 |
[Python] HackerRank - Introduction to Sets (0) | 2023.02.24 |
[Python] HackerRank - itertools.permutations() (0) | 2023.02.23 |
[Python] HackerRank - collections.Counter() (0) | 2023.02.22 |