Python暴力破解密码:计数器异常与内存错误问题求助
Hey there! Let's fix the two issues in your code—counter inaccuracy and memory errors—step by step.
1. Why Your Counter Isn't Working Correctly
Look at your code structure: you wrapped everything in an infinite while True loop, and inside that loop, you redefine the Generator function every time. When you find the correct password, you break out of the for loop, but the while True loop just restarts the whole process! This means your counter keeps incrementing through permutations over and over again until you manually stop the program, which is why you see the same large number every time (it's the total number of permutations multiplied by how many times the loop ran before you stopped it).
The fix here is simple: remove the while True loop entirely—you don't need it. The permutations generator will iterate through all possible guesses once, and we can break out of that single loop when we find the password.
2. Why You're Getting Memory Errors
Even though you tried using a generator with yield, you defeated its purpose by first converting all permutations to a list with guess_storage = [''.join(p) for p in permutations(characters, len(user_pw))]. Lists store every element in memory at once, and for longer passwords, the number of permutations is astronomically large (e.g., 26 letters for a 5-character password gives 26×25×24×23×22 = 7,893,600 permutations—way more for longer lengths).
The solution is to use the permutations generator directly instead of converting it to a list. permutations already generates one combination at a time, so we can join each permutation to a string on the fly without storing everything in memory.
Fixed Code
Here's the revised version of your code that addresses both issues:
import string from itertools import permutations characters = string.ascii_letters user_pw = input('Set your PW: ') attempts = 0 for p in permutations(characters, len(user_pw)): guess = ''.join(p) attempts += 1 if guess == user_pw: print('SUCCESS:') print('Password:', guess) break print('Attempts:', attempts)
Key Improvements:
- Removed the unnecessary
while Trueloop and nestedGeneratorfunction—this stops the counter from incrementing infinitely. - Directly iterates over
permutationsinstead of converting it to a list, so only one permutation is generated and stored in memory at a time, eliminating the memory error. - Simplified the logic by removing the
doneflag (we justbreakthe loop immediately when the password is found).
Bonus Notes
- Keep in mind that permutations don't allow repeated characters (e.g., "aab" won't be guessed if you use
permutations). If you want to allow repeated characters (which is common in real passwords), useitertools.productinstead, withrepeat=len(user_pw). - For even moderately long passwords, brute-forcing is impractical—this is just a great learning exercise to understand generators and permutations!
内容的提问来源于stack exchange,提问作者Thilo G

