python 穷举银行密码方法
列出从数字1,2,3,4中任取3个数的所有排列与组合
实现
import itertools
# 排列(有序)
my_list = list(itertools.permutations([1, 2, 3, 4], 3))
print(my_list)
# 组合(无序)
my_list = list(itertools.combinations([1, 2, 3, 4], 3))
print(my_list)
[(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)]
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
需求2
列出银行密码所有可能
import itertools
# 普通模式
my_list = [''.join(x) for x in itertools.product('0123456789', repeat=6)]
print(my_list)
# 生成器模式(节约内存,用一个生成一个)
my_list = (''.join(x) for x in itertools.product('0123456789', repeat=6))
print(next(my_list))
print(next(my_list))
实现
import itertools
# 普通模式
my_list = [''.join(x) for x in itertools.product('0123456789', repeat=6)]
print(my_list[0])
print(my_list[1])
# 生成器模式(节约内存,用一个生成一个)
my_list = (''.join(x) for x in itertools.product('0123456789', repeat=6))
print(next(my_list))
print(next(my_list))