python在编写排列组合是会用到 itertools 模块
排列
import itertools mylist = list(itertools.permutations([‘A‘,‘B‘,‘C‘,‘D‘],4)) # 全排列 print(mylist) mylist1 = list(itertools.permutations([‘A‘,‘B‘,‘C‘,‘D‘],3)) # 4个里面选3个排列 print(mylist1) #5!=1*2*3*4*5 #0!=1 #M个选N个 M!/(M-N)! #4 1 4!/3!=4 #4 2 4!/2!=3*4=12 #4 3 4!/1!=24
组合
import itertools mylist = list(itertools.combinations([‘A‘,‘B‘,‘C‘,‘D‘],4)) # 组合 print(mylist) mylist1 = list(itertools.combinations([‘A‘,‘B‘,‘C‘,‘D‘],3)) # 4个里面选3个组合 print(mylist1) #[‘A‘,‘B‘,‘C‘,‘D‘],3) 4个取3个,无序 #M!/N!(M-N)!
可以重复的排序(类似密码)
import itertools # product 可以重复的排序 # mylist1 = list(itertools.product("0123456789",repeat=4)) 参数表示可以重复的从前面的0到9里面取出4个数字来 # print(mylist1) mylist=(["".join(x) for x in itertools.product("0123456789",repeat=4) ]) print(mylist) print(len(mylist))
利用生成器可以跌代的生产密码,节约内存
#百度云,输入密码 _ _ _ _ import itertools # product 可以重复的排序 mylist=("".join(x) for x in itertools.product("0123456789",repeat=4)) print(next(mylist)) print(next(mylist)) print(next(mylist)) print(next(mylist))
原文地址:https://www.cnblogs.com/sea-stream/p/10805146.html
时间: 2024-10-09 19:20:03