DefaultDict Tutorial

Sort by

recency

|

1110 Discussions

|

  • + 0 comments

    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")

  • + 0 comments
    from collections import defaultdict
    
    d = defaultdict(str)
    n,m = map(int,input().split())
    for i in range(n): d[input()]+=f'{i+1} '
    for i in range(m): print(d.get(input(),-1))
    

    .get() allows a simple way to print the value or -1 and avoids creating new values in defaultdict

  • + 0 comments
    from collections import defaultdict
    
    def main():
        counts = input().split()
        n = int(counts[0])
        m = int(counts[1])
        group_a = defaultdict(list)
        for i in range(n):
            element = input()
            group_a[element].append(i+1)
        for _ in range(m):
            element = input()
            if group_a[element] == []:
                print(-1)
            else:
                print(" ".join(str(x) for x in group_a[element]))
    
    if __name__ == "__main__":
        main()
    
  • + 0 comments

    Thanks, HackerRank, for making Python collections feel less intimidating. Looking forward to applying this in more complex problems! Cricbet99 club login

  • + 0 comments
    from collections import defaultdict
    
    n, m = map(int, input().split())
    
    d = defaultdict(list)
    
    for _ in range(n):
        d['A'].append(input().strip())
    
    for _ in range(m):
        d['B'].append(input().strip())
    
    for item in d['B']:
        positions = [i+1 for i, val in enumerate(d['A']) if val.strip().lower() == item.lower()]
        if positions:
            print(*positions)
        else:
            print(-1)
    '