python 100例之例一

题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?
解题思路:第一步,将四个数字组成三位数,百位、十位、个位都有可能出现四个数字中的一个,总共有64种,使用嵌套for循环即可以实现;第二步,在三位数字中去重,即百位出现的数字不能出现在十位、个位,同理十位出现的不能出现在百位、个位,个位出现的不能出现在百位、十位,用程序表示如百位为a,十位为b,个位为c,则a!=b and a!=c and b!=a and b!=c and c!=a and c!=b, 简化为 a!=b and a!=c and b!=c。
代码:

results = []
for a in range(1,5):
    for b in range(1,5):
        for c in range(1,5):
            if a!=b and b!=c and a!=c :
                results.append('%d%d%d' %(a,b,c),)
print results 
print len(results)

执行结果:

['123', '124', '132', '134', '142', '143', '213', '214', '231', '234', '241', '243', '312', '314', '321', '324', '341', '342', '412', '413', '421', '423', '431', '432']
24

解题思路二:使用python内建函数itertools函数 permutations方法实现:

import itertools
list_p = list(itertools.permutations([1,2,3,4],3))
print list_p,len(list_p)

执行结果:

[(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

itertools函数是python内建循环函数,类似permutations方法的是combinations,区别是permutations无排序功能,combinations有排序功能,要求前一个元素一定小于后一个元素,如

import itertools
list_c = list(itertools.combinations([1,2,3,4],3))
print list_c, len(list_c)

执行结果:

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

类似combinations的方法是combinations_with_replacement,此方法支持元素复用:

list_cwr = list(itertools.combinations_with_replacement([1,2,3,4],3))
print list_cwr, len(list_cwr)

执行结果:

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

修改元素长度,可以更明显看出两个函数的区别:

list_c = list(itertools.combinations([1,2,3,4],2))
print list_c, len(list_c)
list_cwr = list(itertools.combinations_with_replacement([1,2,3,4],2))
print list_cwr, len(list_cwr)

执行结果:

[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] 6
[(1, 1), (1, 2), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (4, 4)] 10

itertools还有很多排列方法,具体参考:

https://docs.python.org/2/library/itertools.html

猜你喜欢

转载自blog.csdn.net/u012209424/article/details/78643791
今日推荐