[Python] defaultdict with default value 1?

Discussão em 'Python' iniciado por Stack, Julho 2, 2025.

  1. Stack

    Stack Membro Participativo

    I read an implementation of counting sort:

    from collections import defaultdict
    def sort_colors(A):
    ht = {} # a hash map
    ht = defaultdict(lambda:0, ht) # with default value 1
    for i in A:
    ht += 1
    ret = []
    for k in [0, 1, 2]:
    ret.extend([k]*ht[k])
    return ret


    In the first two lines of the func:

    ht = {}
    ht = defaultdict(lambda:0, ht)


    I am not clear about this initialization. Shall we just replace these two lines with following?

    ht = defaultdict(int) # default value 0

    Continue reading...

Compartilhe esta Página