获取python列表中元素的总和

2024-10-02 16:25:02 发布

您现在位置:Python中文网/ 问答频道 /正文

鉴于:

[1, 3, 46, 1, 3, 9]

找到这两者之间的不同组合,以获得尽可能多的目标编号=47。46+1和1+46是相同的。

我的代码:

def stockPairs(stocksProfit, target):
    # Write your code here
    print(stocksProfit)
    #print(target)

    count = 0
    for t, sp in enumerate(stocksProfit):
        #print(stocksProfit[t])
        for l in range(1, len(stocksProfit)): 
            total = stocksProfit[t] + stocksProfit[l]
            #print(total, stocksProfit[t], stocksProfit[l] )
            if total == target :

                count = count + 1
    return count

预期结果是1,因为我只想要不同的组合


Tags: 代码intarget目标foryourdefcount
1条回答
网友
1楼 · 发布于 2024-10-02 16:25:02

解决方案1:任意2个数字的组合

import itertools

input_list=[1, 3, 46, 1, 3, 9]
combinations_of_2 = itertools.combinations(input_list,2)

sum_of_47 = [ sorted(combination) for combination in combinations_of_2 if sum(combination) == 47 ]
print(sum_of_47)

输出

[[1, 46], [1, 46]]

解决方案2:列表中任意数量元素的组合

import itertools
input_list=[1, 3,44,2, 1, 3, 9]

all_combinations = [ itertools.combinations(input_list, r) for r in range(len(input_list)+1) ]

sum_of_47 = [ sorted(combination) for combination_by_len in all_combinations for combination in combination_by_len if sum(combination) == 47 ]

print(sum_of_47) 

输出

[[3, 44], [3, 44], [1, 2, 44], [1, 2, 44]]

注意:两种解决方案都有重复。需要通过逻辑删除重复元组

相关问题 更多 >