Создает дикт по умолчанию с кортежами (item:inf, {():0})
?
Почему бы просто не добавить один элемент и убедиться самим?
from collections import defaultdict
from math import inf
dp = defaultdict(lambda: inf, {(): 0})
dp[42]
print(dp)
Вывод:
defaultdict(<function <lambda> at 0x7f5b389a7e18>, {(): 0, 42: inf})
Добавлен оператор печати в this во вспомогательный вызов
from collections import Counter, defaultdict
from math import inf, isinf
from pprint import pprint
class Solution(object):
def minStickers(self, stickers, target):
s_cnts = *map(Counter, stickers),
dp = defaultdict(lambda: inf, {(): 0})
def helper(cnt):
_id = tuple(cnt.items())
if isinf(dp[_id]):
dp[_id] = 1 + min((helper(cnt - s_cnt) for s_cnt in s_cnts
if s_cnt[_id[0][0]]), default=inf)
pprint(dp)
return dp[_id]
# no python 3.8 available, replaced walrussoperator
return -1 if isinf( helper(Counter(target))) else helper(Counter(target))
s = Solution()
print(s.minStickers(["with", "example", "science"], "thehat"))
приводит к
defaultdict(<function Solution.minStickers.<locals>.<lambda> at 0x03A4C4F8>,
{(): 0,
(('e', 1), ('a', 1)): inf,
(('t', 1), ('h', 1), ('e', 1), ('a', 1)): inf,
(('t', 2), ('h', 2), ('e', 1), ('a', 1)): inf})
defaultdict(<function Solution.minStickers.<locals>.<lambda> at 0x03A4C4F8>,
{(): 0,
(('a', 1),): inf,
(('e', 1), ('a', 1)): inf,
(('t', 1), ('h', 1), ('e', 1), ('a', 1)): inf,
(('t', 2), ('h', 2), ('e', 1), ('a', 1)): inf})
defaultdict(<function Solution.minStickers.<locals>.<lambda> at 0x03A4C4F8>,
{(): 0,
(('a', 1),): 1,
(('e', 1), ('a', 1)): inf,
(('t', 1), ('h', 1), ('e', 1), ('a', 1)): inf,
(('t', 2), ('h', 2), ('e', 1), ('a', 1)): inf})
defaultdict(<function Solution.minStickers.<locals>.<lambda> at 0x03A4C4F8>,
{(): 0,
(('a', 1),): 1,
(('e', 1), ('a', 1)): 1,
(('t', 1), ('h', 1), ('e', 1), ('a', 1)): inf,
(('t', 2), ('h', 2), ('e', 1), ('a', 1)): inf})
defaultdict(<function Solution.minStickers.<locals>.<lambda> at 0x03A4C4F8>,
{(): 0,
The thread 'MainThread' (0x1) has exited with code 0 (0x0).
(('a', 1),): 1,
(('e', 1), ('a', 1)): 1,
(('t', 1), ('h', 1), ('e', 1), ('a', 1)): 2,
(('t', 2), ('h', 2), ('e', 1), ('a', 1)): inf})
defaultdict(<function Solution.minStickers.<locals>.<lambda> at 0x03A4C4F8>,
{(): 0,
(('a', 1),): 1,
(('e', 1), ('a', 1)): 1,
(('t', 1), ('h', 1), ('e', 1), ('a', 1)): 2,
(('t', 2), ('h', 2), ('e', 1), ('a', 1)): 3})