Python實現(xiàn)的排列組合、破解密碼算法示例
本文實例講述了Python實現(xiàn)的排列組合、破解密碼算法。分享給大家供大家參考,具體如下:
排列組合(破解密碼)
1.排列
itertools.permutations(iterable,n)
參數(shù)一:要排列的序列,
參數(shù)二:要選取的個數(shù)
返回的是一個迭代對象,迭代器中的每一個元素都是一個元組
import itertools #概念:從n個不同元素中取出m(m≤n)個元素,按照一定的順序排成一列,叫做從n個元素中取出m個元素的一個排列(Arrangement)。特別地,當m=n時,這個排列被稱作全排列(Permutation) ''' 1 2 3 4 假設從中取出3個數(shù)字 123 132 213 231 321 312 ''' #需求:從[1,2,3,4]4個數(shù)中隨機取出3個數(shù)進行排列 mylist = list(itertools.permutations([1,2,3,4], 3)) print(mylist) print(len(mylist)) ''' 規(guī)律總結(jié): 4 - 3 24 4 - 2 12 4 - 1 4 排列的可能性次數(shù):n! / (n-m)! '''
2.組合
itertools.combinations(iterable,n)
參數(shù)一:可迭代對象
參數(shù)二:要選取的個數(shù)
返回值:返回一二迭代器,迭代器中的每一個元素都是一個元組
import itertools #概念:從m個不同的元素中,任取n(n≤m)個元素為一組,叫作從m個不同元素中取出n個元素的進行組合 ''' 1 2 3 4 5 中選4個數(shù)的組合方式有幾種? ''' mylist = list(itertools.combinations([1,2,3,4,5], 4)) print(mylist) print(len(mylist)) ''' 規(guī)律總結(jié): m n 5 - 5 1 5 - 4 5 5 - 3 10 5 - 2 10 5! 120/120(m-n)! 120/24(m-n)! 120/6(m-n)! m!/(n!x(m-n)!) '''
3.排列組合
itertools.product(iterable,repeat=1)
參數(shù)一:可迭代對象,參數(shù)二:重復的次數(shù),默認為1
import itertools ''' _ _ _ _ _ ''' mylist = list(itertools.product("0123456789QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm", repeat=6)) #可以嘗試10,有可能電腦會卡住 #多線程也不行,電腦內(nèi)存不夠,咋處理都白搭 #print(mylist) print(len(mylist))
擴展:現(xiàn)在但凡涉及到密碼,一般都會進行加密處理,常用的加密方式有MD5,RSA,DES等
4.瘋狂破解密碼
傷敵一千自損一萬的破解方式
import time import itertools #mylist = list(itertools.product("0123456789", repeat=10)) passwd = ("".join(x) for x in itertools.product("0123456789QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm", repeat=6)) #print(mylist) #print(len(mylist)) while True: #先直接實現(xiàn),然后再添加異常 try: str = next(passwd) time.sleep(0.5) print(str) except StopIteration as e: break
更多關于Python相關內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)學運算技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
anaconda?部署Jupyter?Notebook服務器過程詳解
這篇文章主要為大家介紹了anaconda?部署Jupyter?Notebook服務器過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09