本文目錄一覽:
- 1、如何用python編寫排列組合
- 2、在python中如何實現列表中元素的所有排列組合?如輸入為[‘1′,’2′,’3’]和2輸出為[‘
- 3、Python實現的排列組合計算操作示例
- 4、【基礎】Python3小程序_之排列組合
如何用python編寫排列組合
import math
import random
oTemp = []
oList = []
i = 0
while True:
a = random.randint(1,4)
if a in oTemp:
continue
else:
oTemp.append(a)
i +=1
if i%4==0:
Num = oTemp[0]*1000+oTemp[1]*100+oTemp[2]*10+oTemp[3]
if Num in oList:
i = 0
oTemp=[]
continue
else:
oList.append(Num)
i = 0
oTemp=[]
if len(oList)==24:
break
for m in oList:
for n in range(2,int(math.sqrt(m))+1):
if m%n==0:
oList.remove(m)
break
print oList
這段代碼是用1-4生成4位數,4個位上的數字不相同的素數。可以做下參考
在python中如何實現列表中元素的所有排列組合?如輸入為[‘1′,’2′,’3’]和2輸出為[‘
#!/usr/bin/python
#Two method for generate a list whose item is all possible permutation and combination come from every item of many list.
A = [‘1’, ‘2’]
B = [‘a’, ‘b’, ‘c’]
C = [‘A’, ‘B’, ‘C’, ‘D’]
retList = []
for a in A:
for b in B:
for c in C:
retList.append((a,b,c))
print retList
print ‘*’ * 40
def myfunc(*lists):
#list all possible composition from many list, each item is a tuple.
#Here lists is [list1, list2, list3], return a list of [(item1,item2,item3),…]
#len of result list and result list.
total = reduce(lambda x, y: x * y, map(len, lists))
retList = []
#every item of result list.
for i in range(0, total):
step = total
tempItem = []
for l in lists:
step /= len(l)
tempItem.append(l[i/step % len(l)])
retList.append(tuple(tempItem))
return retList
print myfunc(A,B,C)
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)]
【基礎】Python3小程序_之排列組合
有1、2、3、4個數字,能組成多少個互不相同且無重複數字的三位數?具體有哪些數字
方法一:for循環+集合去重複項
方法二:內置函數itertools
排列組合迭代器:
itertools.product p,q…[repeat=l]笛卡爾積,相當於嵌套的for
itertools.permutation p[,r]長度為r元組,所有可能得排列,無重複元素
itertools.combination p,r 長度r元組,有序,無重複元素
itertools.combinaton_with_replacement p,r 長度人員組,有序,元素可重複
舉例
模塊其他函數:
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/297757.html