如何从提供的向量中找到最大的数字?

问题描述 投票:0回答:1

说,词典提供了某些值。如何找到最高号码?

输入

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,所以构成向量的dict值之和是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 ?
    

说,词典提供了某些值。如何找到最高编号?输入d1 = {1:1、2:6、3:7、4:1、5:3}向量= 5 d1 = {1:1、2:6、3:7、4:1、5:3}向量= 5 l1 = list(td ....

python-3.x list dictionary itertools
1个回答
1
投票

与其他答案类似,但是允许重复使用相同的键来获取键的最大数量,其总和为矢量:


1
投票

涉及一些步骤,请参见代码注释中的文档:

© www.soinside.com 2019 - 2024. All rights reserved.