如何查找列表中的哪些值求和为指定值 [英] How to find what values of a list sum to a specified value

查看:164
本文介绍了如何查找列表中的哪些值求和为指定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编程背包加密算法.我是Python编程的新手.我有一个列表和一个确定的整数值.我想查找列表中的哪些元素将总计为我的整数值.我可以让它运行两个或更少的元素,但是不能运行两个以上的元素.

I am programming a knapsack encryption algorithm. I am new to Python programming. I have a list and an integer value I have determined. I want to find what elements in my list will sum up to my integer value. I can get it running for two elements or less but I can not run it for more than two elements.

假设:

privkey = [2,3,6,13,27,52]
cipher = 9

我当前的功能可以运行上述场景:

My current function can run the scenario above:

searchList = []
for i, number in enumerate(privkey[:-1]):  
    complementary = cipher - number
    if complementary in privkey[i+1:]:  
        searchList.append(number)
        searchList.append(complementary)
        print("Solution Found: {} and {}".format(number, complementary))
        break
else:  
    print("No solutions exist")
print(searchList)

其预期输出为[3,6],并且确实有效.

The expected output of this will be [3,6] and indeed works.

但是,如果将密码更改为需要超过三个字符的总和的条件,例如:

However if cipher is changed to a condition which requires the sum of more than three characters for example:

cipher = 11

这将需要privkey [0] + privkey [1] + privkey [2]之和.

This would require the sum of privkey[0]+privkey[1]+privkey[2].

我如何创建也涵盖这些基础的代码?

How can I create a code that covers these bases as well?

推荐答案

您可以使用此代码(适用于python3).该代码将为您提供私钥列表中满足密码整数的所有可能组合.

You can use this code (For python3). This code will provide you all possible combinations from privkey list which satisfy the cipher integer.

from itertools import combinations

privkey = [2,3,6,13,27,52]
cipher = 9
character = 2  # change it to get sum of dynamic no. of character

possible_combination = list(combinations(privkey, character))

li =[each for each in possible_combination if sum(each) == cipher]
if li:
    print("List-> ", *li)
else:
    print("No combination found from privkey list to satisfy the cipher integer.")

输出:

(3, 6)

这篇关于如何查找列表中的哪些值求和为指定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆