DefaultDict Tutorial

Sort by

recency

|

1055 Discussions

|

  • + 0 comments

    from collections import defaultdict d = defaultdict(list) list1=[]

    n, m = map(int,input().split())

    for i in range(0,n): d[input()].append(i+1)

    for i in range(0,m): list1=list1+[input()]

    for i in list1: if i in d: print(" ".join( map(str,d[i]) )) else: print(-1)

  • + 0 comments

    I fail to see the utility of defaultdicts for this problem. List comprehensions provide, IMO, more readable code:

    n, m = [int(x.strip()) for x in input().split()]
    
    a = [input().strip() for _ in range(n)]
    
    b = [input().strip() for _ in range(m)]
    
    for w in b:
        indices = [i+1 for i, x in enumerate(a) if x == w]
        if indices:
            print(*indices)
        else:
            print(-1)
    
  • + 0 comments

    n,m=[int(i) for i in input().split()] l1=[] l2=[] i=0 while(i

  • + 0 comments

    The defaultdict in Python is a powerful tool that simplifies dictionary handling by automatically assigning a default value to keys that don’t yet exist. This feature saves time and reduces code complexity, especially when dealing with cases where keys might not be initialized. Bc game

  • + 0 comments
    from collections import defaultdict
    d = defaultdict(list)
    n, m = map(int, input().split())
    
    ### Optimized Version ###
    # Precompute the positions of each value in group_A
    positions_dict = defaultdict(list)
    for i in range(n):
        value = input()
        positions_dict[value].append(i + 1)  # Store 1-based index positions
    
    # Check and print the positions for each value in group_B
    for _ in range(m):
        value = input()
        if value in positions_dict:
            print(*positions_dict[value])  # Print all positions found
        else:
            print(-1)  # Print -1 if no occurrence found
    
    ### Less Efficient Version ###
    # for _ in range(n):
    #     d['group_A'].append(input())
    # for _ in range(m):
    #     d['group_B'].append(input())
        
    # for value in d['group_B']:
    #     positions = [i + 1 for i, v in enumerate(d['group_A']) if v == value]  # Find all occurrences
    #     if positions:
    #         print(*positions)  # Print all positions found
    #     else:
    #         print(-1)  # Print -1 if no occurrence found