Python – 大小为 K 的字典值组合
有时在使用Python字典时,我们可能会遇到一个问题,即我们需要提取某个键的大小为 K 的值的组合。这通常是当值以字符串的形式出现时。这可以在日常编程中应用。让我们讨论一种可以执行此任务的方式。
Input : test_dict = {‘a’ : ‘a’, ‘b’ : ‘b’, ‘c’ : ‘c’, ‘d’ : ‘d’}
Output : [‘aaa’, ‘bbb’, ‘ccc’, ‘ddd’]
Input : test_dict = {‘a’ : ‘abcd’, ‘b’ : ”, ‘c’ : ”, ‘d’ : ”}
Output : [‘aaa’, ‘aab’, ‘aac’, ‘aad’]
方法:使用递归+生成器函数+yield
上述功能的组合可以用来解决这个问题。在此,我们使用递归执行所有可能的组合任务。生成器函数用于动态创建值并使用yield返回调用函数。
Python3
# Python3 code to demonstrate working of
# Dictionary values combination of size K
# Using yield + generator function + recursion
def gen_strs(chr_key, test_dict, K):
def hlpr(s):
if len(s) == K:
yield s
elif len(s) < K:
for ltr in test_dict[s[-1]]:
yield from hlpr(s + ltr)
for ltr in chr_key:
yield from hlpr(ltr)
# initializing dictionary
test_dict = {'a' : 'abc', 'b' : 'bd', 'c' : 'c', 'd' : 'ab'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K = 3
# initializing character keys
chr_key = 'abcd'
# Dictionary values combination of size K
# Using yield + generator function + recursion
res = []
for ele in gen_strs(chr_key, test_dict, K):
res.append(ele)
# printing result
print("The extracted combinations : " + str(res))
输出 :
原字典:{'b': 'bd', 'a': 'abc', 'd': 'ab', 'c': 'c'}
提取的组合:['aaa', 'aab', 'aac', 'abb', 'abd', 'acc', 'bbb', 'bbd', 'bda', 'bdb', 'ccc', ' daa','dab','dac','dbb','dbd']