题目:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?输出所有组合?
循环就不多说了,直接上代码:
def my_permutation(num_list: List[int]):
counts = 0
for i in num_list:
for j in num_list:
if j != i:
for k in num_list:
if k != j and k != i:
counts += 1
print(i*100 + j*10 + k, end=" ")
print()
print(f"共计{counts}种组合")
my_permutation([1, 2, 3, 4])
第二种方法:
itertools库方法permutations
import itertools
list1 = [1, 2, 3, 4]
# 对list1进行无序排列,无重复元素。第二个参数相当于位数限制,题中要求三位数,则为3.如果求4位数,同步修改匿名函数
list2 = list(map((lambda x: x[0]*100 + x[1]*10 + x[2]), itertools.permutations(list1, 3)))
print(f"共计{len(list2)}种组合,分别是:\n{list2}")