Python案例:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?

实现1,2,3,4组合不重复数字的三位数

题目见链接

方法一

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

利用for循环嵌套实现,最内部的循环,利用if判断筛选出无重复的数。

# 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?


list_1 = [1, 2, 3, 4]
count = 0
for a in list_1:
    for b in list_1:
        # print(a)
        for c in list_1:
            if (a != b) and (a != c) and (b != c):
                count += 1
                print(a, end="")
                print(b, end="")
                print(c, end=" ")

print("")
print("共计%d个结果" % count)

方法二

利用itertools库实现
permutations的用法见文章

# 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
# 导入itertools
import itertools

list_1 = [1, 2, 3, 4]
count = 0
list_2 = list(itertools.permutations(list_1, 3))
for tuple_1 in list_2:
    print("".join("%s" % i for i in tuple_1), end=" ")
    count += 1

print("")
print("共计有%d种结果" % count)

猜你喜欢

转载自blog.csdn.net/sinat_37960022/article/details/110479589