【发布时间】:2020-06-13 21:36:38
【问题描述】:
说,字典提供了某些值。 如何找到最大的数字?
输入
d1 = {1: 1, 2: 6, 3: 7, 4: 1, 5: 3}
vector = 5
d1 = {1: 1, 2: 6, 3: 7, 4: 1, 5: 3}
vector = 5
l1 = list(td.values())
基于向量值,它应该打印输出。
向量是 5,所以形成向量的字典值的总和是3,1,1
对应键为5,4,1
所以,output should be 541 但这里略有变化。
由于value '1' 与multiple keys 相关联,它应该接highest key,
所以,output should be 544 instead of 541(对于上述输入,简要介绍组合,不考虑 '1+1+1+1+1' 到 '44444')
另一个例子
d1 = {1: 1, 2: 6, 3: 7, 4: 1, 5: 3}
vector = 7
Possible combinations:
3 # --> Key of 7
21 # --> Key of 6 & 1 (6+1 = 7)
24 # --> Key of 6 & 1 (6+1 = 7)
12 # --> Key of 1 & 6 (1+6 = 7)
42 # --> Key of 1 & 6 (1+6 = 7)
Output : 42 (Highest number)
另一个
d1 = {1:9,2:4,3:2,4:2,5:6,6:3,7:2,8:2,9:1}
vector = 5
here, it would be 1+2+2 (988).
But, '1' can also be added 5 times to form vector 5,
which would be '99999'
由于@Patrick Artner 要求提供最小可重现示例,但发布此内容并没有按预期工作。
from itertools import combinations
def find_sum_with_index(l1, vector):
index_vals = [iv for iv in enumerate(l1) if iv[1] < target]
for r in range(1, len(index_vals) + 1):
for perm in combinations(index_vals, r):
if sum([p[1] for p in perm]) == target:
yield perm
d1 = {1: 1, 2: 6, 3: 7, 4: 1, 5: 3}
vector=5
l1=list(d1.values())
for match in find_sum_with_index(l1, vector):
print(dict(match))
Is there any specific algorithm to be chosen for these kind of stuffs ?
【问题讨论】:
-
你有什么问题。您是否有查看值并计算所有可能的部分总和以达到
vector的算法? minimal reproducible example? -
@Patrick Artner:向量不过是总和。并且从 dict-values 中,应该找到形成向量和的组合。然后,应该找到这些组合的键(最高值)。
-
@PatrickArtner :我理解您对最小可重现示例的担忧。
-
从itertools/combinations(列表)中,可以得到可能的组合形成向量。 d1 = {1: 1, 2: 6, 3: 7, 4: 1, 5: 3} , vector=5, , l1 = list(d1.values()) 即 l1 = [1,6,7, 1,3]。你会得到 {0:1,3:1,4:3} 的结果(来自列表,{index:element})。如果你追溯它以获得最高数字形成向量将是 430 这是不正确的。应该是 544 wrt 字典。
-
@PatrickArtner : 发布在上面,希望现在清楚了。
标签: python-3.x list dictionary itertools