python之排列组合(有序)

1.贴题

题目来自
Python数学计算,编程练习题实例一


简述:这里有四个数字,分别是:1、2、3、4
提问:能组成多少个互不相同且无重复数字的三位数?各是多少?

Python解题思路分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去 掉不满足条件的排列。


2.参考代码

count = 0 #初始化变量count为0
li = [] #初始化列表为空
for i in range(1,5): #百位迭代
    for j in range(1,5): #十位迭代
        for k in range(1,5): #各位迭代
            if i != j and j != k and i != k: #如果找到百位十位各位都不相等的三位数
                count += 1 #计数变量加一
                li.append(100*i+10*j+k) #将该数添加到列表
print(count) #打印个数
print(li) #打印列表

一行写法

print([100*i+10*j+k for i in range(1,5) for j in range(1,5) for k in range(1,5) if i != j and j != k and i != k])

3.拓展知识

想着python这么强大的库肯定不能让你手打,经过查资料发现果然有现成的函数可以使用。
参考博文python内置函数-排列组合函数

import itertools #导入itertools库

print(list(itertools.product('1234', repeat = 2))) #有重复的排列
print(list(itertools.permutations('1234', 2))) #无重复的排列
print(list(itertools.combinations('1234', 2))) #无重复的组合
print(list(itertools.combinations_with_replacement('1234', 2))) #有重复的组合

输出是这样的

[('1', '1'), ('1', '2'), ('1', '3'), ('1', '4'), ('2', '1'), ('2', '2'), ('2', '3'), ('2', '4'), ('3', '1'), ('3', '2'), ('3', '3'), ('3', '4'), ('4', '1'), ('4', '2'), ('4', '3'), ('4', '4')]
[('1', '2'), ('1', '3'), ('1', '4'), ('2', '1'), ('2', '3'), ('2', '4'), ('3', '1'), ('3', '2'), ('3', '4'), ('4', '1'), ('4', '2'), ('4', '3')]
[('1', '2'), ('1', '3'), ('1', '4'), ('2', '3'), ('2', '4'), ('3', '4')]
[('1', '1'), ('1', '2'), ('1', '3'), ('1', '4'), ('2', '2'), ('2', '3'), ('2', '4'), ('3', '3'), ('3', '4'), ('4', '4')]

itertools的其他工具可以参考python itertools功能详解

猜你喜欢

转载自blog.csdn.net/weixin_41980474/article/details/80102979