gpt4 book ai didi

python-3.x - 如何从提供的向量中找到最高数字?

转载 作者:行者123 更新时间:2023-12-04 09:40:05 26 4
gpt4 key购买 nike

比如说,字典提供了某些值。
如何找到最高的数字?

输入

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 ?

最佳答案

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

d1 = {1: 1, 2: 6, 3: 7, 4: 1, 5: 3}
vector = 7

#create a dict that contains value -> max-key for that value
d2 = {}
for k,v in d1.items():
d2[v] = max(d2.get(v,-1), k)

def mod_powerset(iterable,l):
# uses combinations_with_replacement to allow multiple usages of one value
from itertools import chain, combinations_with_replacement
s = list(set(iterable))
return chain.from_iterable(combinations_with_replacement(s, r) for r in range(l))

# create all combinations that sum to vector
p = [ s for s in mod_powerset(d1.values(),vector//min(d1.values())+1) if sum(s) == vector]
print(p)
# sort combinations by length then value descending and take the max one
mp = max( (sorted(y, reverse=True) for y in p), key=lambda x: (len(x),x))

# get the correct keys to be used from d2 dict
rv = [d2[num] for num in mp]

# sort by values, biggest first
rv.sort(reverse=True)

# solution
print(''.join(map(str,rv)))

原装电源组 - 见 itertools-recipes .

关于python-3.x - 如何从提供的向量中找到最高数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62365847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com