For example:
from collections import defaultdict
d = defaultdict(list)
d['python'].append("awesome")
d['something-else'].append("not relevant")
d['python'].append("language")
for i in d.items():
    print i
('python', ['awesome', 'language'])
('something-else', ['not relevant'])
Example:
- Group A contains 'a', 'b', 'a'
- Group B contains 'a', 'c'
- For the first word in group B, 'a', it appears at positions 1 and 3 in group A. The second word, 'c', does not appear in group A, so print -1.
Expected output:
1 3
-1
- The first line contains integers, n, and m separated by a space.
- The next n lines contain the words belonging to group A.
- The next m lines contain the words belonging to group B.
Constraints:
- 1 <= n <=10000
- 1 <= m <= 100
- 1 <= length of each word in input <= 100
Output Format:
- Output m lines.
- The ith line should contain the 1-indexed positions of the occurrences of the ith word separated by spaces.
Sample Input:
STDIN   Function
-----   --------
5 2     group A size n = 5, group B size m = 2
a       group A contains 'a', 'a', 'b', 'a', 'b'
a
b
a
b
a       group B contains 'a', 'b'
b
1 2 4
3 5
- 'a' appeared 3 times in positions 1, 2, and 4.
- 'b' appeared 2 times in positions 3 and 5.
- In the sample problem, if 'c' also appeared in word group B, you would print -1.
Solution:
from collections import defaultdict
n, m = map(int,input().split())
A = [input() for _ in range(n)]
B = [input() for _ in range(m)]
d = defaultdict(list)
for index,item in enumerate(A,1):
    d[item].append(index)
for item in B:
    if d[item]:
        print(*d[item])
    else:
        print(-1)
No comments:
Post a Comment