python 2.5.2中的置换
我有一个数字列表供输入,例如python 2.5.2中的置换,python,list,permutation,Python,List,Permutation,我有一个数字列表供输入,例如 671.00 1,636.00 436.00 9,224.00 我想生成所有可能的和,并用一种方法将其标识为输出,例如: 671.00 + 1,636.00 = 2,307.00 671.00 + 436.00 = 1,107.00 671.00 + 9,224.00 = 9,224.00 671.00 + 1,636.00 + 436.00 = 2,743.00 ... 我想用Python来做 我目前的限制是: a) 我现在正在学习python(这是想法
671.00
1,636.00
436.00
9,224.00
我想生成所有可能的和,并用一种方法将其标识为输出,例如:
671.00 + 1,636.00 = 2,307.00
671.00 + 436.00 = 1,107.00
671.00 + 9,224.00 = 9,224.00
671.00 + 1,636.00 + 436.00 = 2,743.00
...
我想用Python来做
我目前的限制是:
a) 我现在正在学习python(这是想法的一部分)
b) 我将不得不使用Python 2.5.2(无intertools)
我想我已经找到了一段代码,可能会有所帮助:
def all_perms(str):
if len(str) <=1:
yield str
else:
for perm in all_perms(str[1:]):
for i in range(len(perm)+1):
#nb str[0:1] works in both string and list contexts
yield perm[:i] + str[0:1] + perm[i:]
def all_perms(str):
如果len(str)下面的代码生成给定列表的所有“子集”(空集除外),即返回列表列表
def all_sums(l): #assumes that l is non-empty
if len(l)==1:
return ([[l[0]]])
if len(l)==0:
return []
result = []
for i in range(0,len(l)):
result.append([l[i]])
for p in all_sums(l[i+1:]):
result.append([l[i]]+p)
return result
现在您也可以为输出编写一个短函数doit
:
def doit(l):
mylist = all_sums(l)
print mylist
for i in mylist:
print str(i) + " = " + str(sum(i))
doit([1,2,3,4])
排列是指将一组有序的事物进行排列,并将其移动(即改变顺序)。您的问题是关于列表中的内容组合
现在,枚举组合的一种简单方法是将列表中的条目映射到数字中的位。例如,假设设置了位#0(即1),则数字lst[0]
参与组合,如果设置了位#1,则lst[1]
参与组合,等等。这样,使用itertools(Python>=2.6)的范围0中的数字将是:
from itertools import *
a=[1,2,3,4]
sumVal=[tuple(imap(sum,combinations(a,i))) for i in range(2,len(a)+1)]
具有与itertools等价的代码。排列
是否确实要将636+1636
和1636+636
作为不同的元素?我认为这是比排列更多的组合。我也这么认为。在讨论Python的内容之前,您是否可以编写您想要用来完成这项工作的算法?有几种方法可以得到你想要的结果。
def GetSublistByCombination(lst, combination_id) :
res = [x for (i,x) in enumerate(lst) if combination_id & (1 << i)]
return res
# Testing:
>>> GetSublistByCombination([0,1,2,3], 1)
[0]
>>> GetSublistByCombination([0,1,2,3], 3)
[0, 1]
>>> GetSublistByCombination([0,1,2,3], 12)
[2, 3]
>>> GetSublistByCombination([0,1,2,3], 15)
[0, 1, 2, 3]
def IterAllSums(lst) :
combinations = [i for i in range(1 << len(lst)) if HasAtLeastTwoBitsSet(i)]
for comb in combinations :
sublist = GetSublistByCombination(lst, comb)
sum_str = '+'.join(map(str, sublist))
sum_val = sum(sublist)
yield (sum_str, sum_val)
>>> for sum_str, sum_val in IterAllSums([1,2,3,4]) : print sum_str, sum_val
1+2 3
1+3 4
2+3 5
1+2+3 6
1+4 5
2+4 6
1+2+4 7
3+4 7
1+3+4 8
2+3+4 9
1+2+3+4 10
from itertools import *
a=[1,2,3,4]
sumVal=[tuple(imap(sum,combinations(a,i))) for i in range(2,len(a)+1)]