您的位置:

包含使用python实现排列组合的词条

本文目录一览:

如何用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 长度人员组,有序,元素可重复

举例

模块其他函数: