python組合數
① 如何用python編寫排列組合
importmath
importrandom
oTemp=[]
oList=[]
i=0
whileTrue:
a=random.randint(1,4)
ifainoTemp:
continue
else:
oTemp.append(a)
i+=1
ifi%4==0:
Num=oTemp[0]*1000+oTemp[1]*100+oTemp[2]*10+oTemp[3]
ifNuminoList:
i=0
oTemp=[]
continue
else:
oList.append(Num)
i=0
oTemp=[]
iflen(oList)==24:
break
forminoList:
forninrange(2,int(math.sqrt(m))+1):
ifm%n==0:
oList.remove(m)
break
printoList
這段代碼是用1-4生成4位數,4個位上的數字不相同的素數。可以做下參考
② Python實現的排列組合計算操作示例
Python實現的排列組合計算操作示例
本文實例講述了Python實現的排列組合計算操作。分享給大家供大家參考,具體如下:
1. 調用 scipy 計算排列組合的具體數值
>> from scipy.special import comb, perm
>> perm(3, 2)
6.0
>> comb(3, 2)
3.0
2. 調用 itertools 獲取排列組合的全部情況數
>> from itertools import combinations, permutations
>> permutations([1, 2, 3], 2)
<itertools.permutations at 0x7febfd880fc0>
# 可迭代對象
>> list(permutations([1, 2, 3], 2))
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
>> list(combinations([1, 2, 3], 2))
[(1, 2), (1, 3), (2, 3)]
③ python中的組合數據類型可以分為哪三類
根據數據之間的關系,組合數據類型可以分為3類,分別是:序列類型、集合類型和映射類型。組合數據類型更能夠將多個同類或不同類型組織起來,通過單一的表示使數據更有序、更容易。
序列類型是一個元素向量,元素之間的存在先後關系,通過序號訪問,元素之間不排他。
集合類型是一個元素類型,元素之間無序,相同元素在集合中唯一存在。
映射類型是「鍵-值」數據項的組合,每個元素是一個鍵值對,表示為(key, value)。
推薦教程:python教程以上就是小編分享的關於python中的組合數據類型可以分為哪三類的詳細內容希望對大家有所幫助,更多有關python教程請關注環球青藤其它相關文章!
④ python 實現6個數的排列組合,每個數可選值為0和1
fromitertoolsimportproct
foriinproct(range(2),repeat=6):
printi
⑤ Python取隨機數排列組合
沒懂你的意思,既然是排列組合,就是針對3個固定元素。
如果3個元素本身就是隨機的,就不用排列了,下面的getplans函數也就沒有意義,直接循環2-5行代碼就好。
⑥ Python列出多個數字組合相加的和最接近或等於某個數的演算法
演算法 列出這5個數的所有組合,找出組合的和減268的絕對值最小的組合,
完整的Python程序如下
import math
def combine(a,n,num):
real_size=int(math.pow(2, n))
min=abs(sum(a)-num)
min_comb=[]
for i in range(real_size):
min_list=[]
total=0
for j in range(n):
if i & (1 << j):
min_list.append(a[j])
total=total+a[j]
if abs(total-num)<=min:
if abs(total-num)==min:
min_comb.append(min_list)
else:
min_comb=[min_list]
min=abs(total-num)
print(min_comb)
a=[110,120,130,140,150]
num=268
combine(a,len(a),num)
源代碼(注意源代碼的縮進)
⑦ python 數組組合
mm=[['a','b','c','d','e'],[1,2,3,4],[5,6,7,8],[9,10,11,12,13]]
longs=[]
forninmm:
longs.append(len(n))
ll=max(longs)
printll
outall=[]
foriinrange(0,ll,2):
outone=[]
forjinmm:
ifi<ll-1:
printi
outone.append(j[i])
outone.append(j[i+1])
else:
try:
outone.append(j[i])
except:
pass
outall.append(outone)
printoutall
結果:[['a','b',1,2,5,6,9,10],['c','d',3,4,7,8,11,12],['e',13]]
代碼中的2,就是你要的,改成4,下面i改到+3為止。
⑧ 如何使用Python的遞歸方法來實現組合數
defC(n,m):
ifm>n:
return0
elifm==1:
returnn
elifn==1:
return1
else:
returnC(n-1,m-1)+C(n-1,m)
print(C(5,1))#5
print(C(5,2))#10
print(C(5,3))#10
print(C(5,4))#5
print(C(5,5))#1
⑨ 如何用Python列出N個數字的所有排列組合
>> from itertools import combinations, permutations
>> permutations([1, 2, 3], 2)
<itertools.permutations at 0x7febfd880fc0>
# 可迭代對象
>> list(permutations([1, 2, 3], 2)) #排列
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
>> list(combinations([1, 2, 3], 2)) #組合
[(1, 2), (1, 3), (2, 3)]
⑩ 怎麼樣讓python計算任意六位數的排列組合
from itertools import proct
for i in proct(range(2),repeat=6):
print i