本文目錄一覽:
- 1、如何窮舉(任意個數組)的成員的組合?
- 2、python 數組組合
- 3、Python問題 運用窮舉法
- 4、python 數組裡面求和為某固定值的所有組合?
- 5、python怎麼生成list的所有元素的組合
- 6、求python語言 從m個數中選擇n個 所有組合的代碼(只要所有組合情況即可,不要排列)
如何窮舉(任意個數組)的成員的組合?
後
int a1,a2,a3….ai i=你要用幾個數
int b[i]
for(a1=0;a1n-i;a1++)
{
b[0]=a[a1];
for(a2=a1+1;a2n-i+1;a2++)
{
b[1]=a[a2];
……………………
寫到 ai
然後輸出數組b
} 第一個for循環結束
python 數組組合
mm=[[‘a’,’b’,’c’,’d’,’e’],[1,2,3,4],[5,6,7,8],[9,10,11,12,13]]
longs=[]
for n in mm:
longs.append(len(n))
ll = max(longs)
print ll
outall=[]
for i in range(0,ll,2):
outone = []
for j in mm:
if i ll-1:
print i
outone.append(j[i])
outone.append(j[i+1])
else:
try:
outone.append(j[i])
except:
pass
outall.append(outone)
print outall
結果:[[‘a’, ‘b’, 1, 2, 5, 6, 9, 10], [‘c’, ‘d’, 3, 4, 7, 8, 11, 12], [‘e’, 13]]
代碼中的2,就是你要的,改成4,下面i改到+3為止。
Python問題 運用窮舉法
7744
首先,車號的模式是XXYY
其次,確定整數的範圍:32-99
最後,確認出來這個整數是88,也就是車號是7744
python 數組裡面求和為某固定值的所有組合?
l = [2,3,4,5,6,7,8,10,12,13,23,34,56]
def combination(l, n):
l = list(sorted(filter(lambda x: x = n, l)))
combination_impl(l, n, [])
def combination_impl(l, n, stack):
if n == 0:
print(stack)
return
for i in range(0, len(l)):
if l[i] = n:
stack.append(l[i])
combination_impl(l[i + 1:], n – l[i], stack)
stack.pop()
else:
break
combination(l, 22)
python怎麼生成list的所有元素的組合
生成排列可以用product:
from itertools import product
l = [1, 2, 3]
print list(product(l, l))
print list(product(l, repeat=4))
組合的話可以用combinations:
from itertools import combinations
print list(combinations([1,2,3,4,5], 3))
下面是我以為沒有combinations然後自己寫的,沒有itertools的python(2.6以下)可供參考。
import copy
def combine(l, n):
answers = []
one = [0] * n
def next_c(li = 0, ni = 0):
if ni == n:
answers.append(copy.copy(one))
return
for lj in xrange(li, len(l)):
one[ni] = l[lj]
next_c(lj + 1, ni + 1)
next_c()
return answers
print combine([1, 2, 3, 4, 5], 3)
輸出:
[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]
求python語言 從m個數中選擇n個 所有組合的代碼(只要所有組合情況即可,不要排列)
def combinations(iterable, r):
# combinations(‘ABCD’, 2) — AB AC AD BC BD CD
# combinations(range(4), 3) — 012 013 023 123
pool = tuple(iterable)
n = len(pool)
if r n:
return
indices = list(range(r))
yield tuple(pool[i] for i in indices)
while True:
for i in reversed(range(r)):
if indices[i] != i + n – r:
break
else:
return
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1] + 1
yield tuple(pool[i] for i in indices)這是Python幫助文檔中 itertools.combinations(iterable, r) 的代碼,僅供參考
原創文章,作者:AXUWN,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/130881.html