簡體   English   中英

我如何生成如下所示的組合?

[英]how can i generate combinations as like below?

我有一個清單

a=[1,2,3] 

我想在此列表上執行組合(相鄰數字),並且希望將每個組合相乘,如下所示

1
1 2
2
1 2 3
2 3
3

之后,我要執行

a) 1*1= 1 
b) 1*2+2*2= 6
c) 2*2= 4
d) 1*3+2*3+3*3= 18
e) 2*3+3*3= 15
f) 3*3= 9

預期輸出

[1,2,4,18,15,9]

這是我嘗試的代碼:

def grouper(input_list, n = 2):
    for i in xrange(len(input_list) - (n - 1)):
        yield input_list[i:i+n] 
a = [1,2,3]

for item in [a[0:m+1] for m in range(len(a))]:
    for n in  range(len(item)):
        result.append(item[n:])
        test.append(sum([k * len(item) for k in item[n:]]))

print result
print test

輸出

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

[1, 6, 4, 18, 15, 9]

更長的長度

a = [1,2,3,4]

輸出

[[1], [1, 2], [2], [1, 2, 3], [2, 3], [3], [1, 2, 3, 4], [2, 3, 4], [3, 4], [4]]

[1, 6, 4, 18, 15, 9, 40, 36, 28, 16]

簡單使用for循環

a = [1,2,3] 
tmp = []

for m in range(len(a)):
    tmp.append( a[0:m +1])

result = []
test = []


for item in tmp:
    for n in  range(len(item)):
        result.append(item[n:])
        test.append(sum([k * len(item) for k in item[n:]]))

print tmp
print result
print test

輸出量

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

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

[1, 6, 4, 18, 15, 9]

創建組合:

a = [1,2,3]

# create combinations
combinations = []
for i in range(len(a)):
    for j in range(len(a)):
        result = a[i:j+1]
        if result:
            combinations.append(result)

輸出:

combinations [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]

要計算所需的值:

for values in combinations:
    last_val = values[-1]
    computation = ''
    result = 0
    for val in values:
        computation += "{}*{} + ".format(val, last_val)
        result += val * last_val
    computation = computation[:-2] + '= {}'.format(result)
    print(computation)

輸出:

1*1 = 1
1*2 + 2*2 = 6
1*3 + 2*3 + 3*3 = 18
2*2 = 4
2*3 + 3*3 = 15
3*3 = 9

@Vikash Singh在這里給出了一個幾乎完整的解決方案:除了這些組合幾乎沒有不匹配:

我設法糾正了同樣的問題:

a = [1,2,3]

combinations = []
for i in range(len(a)+1):
    for j in range(i):
        result = a[j:i]
        if result:
            combinations.append(result)

print combinations

輸出將是

[[1],[1、2],[2],[1、2、3],[2、3],[3]]

如果列表為[1,2,3,4] ,則輸出為:

[[1],[1、2],[2],[1、2、3],[2、3],[3],[1、2、3、4],[2、3、4] ,[3、4],[4]

我希望這可以通過組合解決OP的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM