请将我的伪代码转换为可用的Python程序

时间:2016-12-02 01:15:34

标签: python python-3.x

我一直在研究下面给出的问题

  

给定一个集合S = {x1,x2 ,. 。 。 ,xn}的整数和整数t(称为目标)决定是否存在S的子集,其总和等于t。

请问,是否有人将我的伪代码转换为有效的Python程序?

If L is a set of integers and x is another integer, then we use the shorthand L + x to denote the list of integers derived from L by increasing each element of L by x, i.e. L + x = {`k + x | `k ∈ L}. For example, if L = {1, 5, 9}, then L + 3 = {4, 8, 12}.

以下是基于动态编程方法的SSP伪代码

1:    L ← {0}
2:    for x ∈ {x1, . . . , xn} do
3:        L ← L ∪ (L + x)
4:        remove from L every element that is greater than t
5:     end for
6:     return True if t ∈ L, False otherwise

1 个答案:

答案 0 :(得分:0)

首先,不,我们无法将此转换为适合您的Python代码。那是作弊。

代数地,结果更容易。目标可以实现 iff

  1. 目标可被x整除;
  2. 目标< = sum(S)
  3. sum(S)= x *(n + 1)* n / 2

    您的代码实际上构建了一个解决方案;这不是必要的。