You are viewing a single comment's thread. Return to all comments →
I am new to python and I had difficulty understanding the code.
Why are two same two for-loops needed? And how does this statement get us the solution : print(cnt[input().strip()]) ?
@tusharkailash29 ... or anyone else currently wondering.
We are comparing two variable input ranges in this question, and the ranges may vary in length. The "for loops" are used to organize the inputs as "S" strings followed by "Q" queries.
cnt = Counter([input().strip() for _ in range(int(input()))])
The Counter() function creates a dictionary (key,value) pairs. The "S" string inputs are the keys, and their occurences (a.k.a counts) are the value. For every duplicate key that appears in this loop, it's value (count) increases by one.
for _ in range(int(input().strip())):
In the second & third lines, "Q" query inputs are the keys we search in the "cnt" dictionary. Think of "input().strip()" in print(cnt[input().strip()]) as the key in (key,value) pair. Searching by cnt[key] provides the dictionary value associated with it. The second "for loop" repeats the cnt[key] search step for the remaining "Q" query inputs.