Python 生成与上一个不同的随机字符串
我试图用Python制作一个密码破解程序作为练习,我注意到破解密码“嘿”平均需要586634次迭代。我认为它很高,因为它可以自由地生成一个可能已经检查过的随机字符串。例如,当它已经发现它不工作时,它可以生成以下内容并使用额外的时间来这样做Python 生成与上一个不同的随机字符串,python,Python,我试图用Python制作一个密码破解程序作为练习,我注意到破解密码“嘿”平均需要586634次迭代。我认为它很高,因为它可以自由地生成一个可能已经检查过的随机字符串。例如,当它已经发现它不工作时,它可以生成以下内容并使用额外的时间来这样做 a,h[j,jpc,o$w,01g,a5b,a!?,01g 那么,如何阻止Python一次又一次地生成相同的字符串呢 这是我的代码(它生成的长度由输入的长度决定): 试试看。它会生成所有可能的3个字母组合。你可以用你想要的任何长度替换2。还要注意,我将从pro
a代码>
,h[j
,jpc
,o$w
,01g
,a5b
,a!?
,01g
那么,如何阻止Python一次又一次地生成相同的字符串呢
这是我的代码(它生成的长度由输入的长度决定):
试试看。它会生成所有可能的3个字母组合。你可以用你想要的任何长度替换2。还要注意,我将从
product
生成的迭代器转换为list
。如果你只需要循环一次,最好不要先将其转换为list
,因为这会消耗更多的内存只需去掉list()
函数调用
import itertools
import string
letters = string.lowercase + string.uppercase + string.punctuation + string.digits
all_possible = list(itertools.product(letters, repeat=3))
test_pws = ['hey', 'h9!', '!!!']
for i,possible_pw in enumerate(all_possible):
pw = "".join(possible_pw)
if pw in test_pws:
print 'Found ', pw, ' at iteration ', i
print all_possible[:5]
print len(all_possible)
print len(set(all_possible))
print all_possible[-5:]
输出
您应该尝试生成所有可能的排列,而不是使用随机排列。
import itertools
import string
letters = string.lowercase + string.uppercase + string.punctuation + string.digits
all_possible = list(itertools.product(letters, repeat=3))
test_pws = ['hey', 'h9!', '!!!']
for i,possible_pw in enumerate(all_possible):
pw = "".join(possible_pw)
if pw in test_pws:
print 'Found ', pw, ' at iteration ', i
print all_possible[:5]
print len(all_possible)
print len(set(all_possible))
print all_possible[-5:]
Found hey at iteration 62252
Found h9! at iteration 70646
Found !!! at iteration 464412
[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'a', 'd'), ('a', 'a', 'e')]
830584
830584
[('9', '9', '5'), ('9', '9', '6'), ('9', '9', '7'), ('9', '9', '8'), ('9', '9', '9')]