题目:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
环境:Pycharm2022 + Anaconda3
先用数学排列组合分析再用Python实现 并进行方法总结
目录
用数学排列组合分析
首先我想到的是排列数组合数,由于题目要求是无重复数字,因此为排列数。排列的定义:从n个不同元素中,任取m(m≤n,m与n均为自然数,下同)个不同的元素按照一定的顺序排成一列,叫做从n个不同元素中取出m个元素的一个排列;从n个不同元素中取出m(m≤n)个元素的所有排列的个数,叫做从n个不同元素中取出m个元素的排列数。
我们可以得出此题的排列数是 4! / (4-3)! = 4! = 24 (个)
Python实现
方法一:
import time
tts = time.time()
arrange = 0
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 (k != i)):
print(i, j, k)
arrange += 1
print(arrange)
tte = time.time()
print("方法一运行时间", tte - tts, '秒')
运行结果如下:
1 2 3
1 2 4
1 3 2
1 3 4
1 4 2
1 4 3
2 1 3
2 1 4
2 3 1
2 3 4
2 4 1
2 4 3
3 1 2
3 1 4
3 2 1
3 2 4
3 4 1
3 4 2
4 1 2
4 1 3
4 2 1
4 2 3
4 3 1
4 3 2
24
方法一运行时间 0.0010006427764892578 秒
方法二:
import time
tts = time.time()
import itertools
sum2 = 0
a = [1, 2, 3, 4]
for i in itertools.permutations(a, 3):
print(i)
sum2 += 1
print(sum2)
tte = time.time()
print("方法二运行时间", tte - tts, '秒')
运行结果如下:
(1, 2, 3)
(1, 2, 4)
(1, 3, 2)
(1, 3, 4)
(1, 4, 2)
(1, 4, 3)
(2, 1, 3)
(2, 1, 4)
(2, 3, 1)
(2, 3, 4)
(2, 4, 1)
(2, 4, 3)
(3, 1, 2)
(3, 1, 4)
(3, 2, 1)
(3, 2, 4)
(3, 4, 1)
(3, 4, 2)
(4, 1, 2)
(4, 1, 3)
(4, 2, 1)
(4, 2, 3)
(4, 3, 1)
(4, 3, 2)
24
方法二运行时间 0.0 秒
方法总结
可以发现方法二运行速度比方法一快,方法二种用到的 itertools.permutations 类,该类内容如下:
class permutations(object):
"""
Return successive r-length permutations of elements in the iterable.
permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)
"""
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __init__(self, range, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass
def __setstate__(self, *args, **kwargs): # real signature unknown
""" Set state information for unpickling. """
pass
def __sizeof__(self, *args, **kwargs): # real signature unknown
""" Returns size in memory, in bytes. """
pass
permutations类创建一个迭代器,返回iterable中所有长度为r的项目序列,如果省略了r,那么序列的长度与iterable中的项目数量相同,即会返回一个全排列的结果。