首页 > 解决方案 > 我怎么能不重复猜测?

问题描述

我怎样才能在不重复猜测的情况下暴力破解密码,也不导入其他任何东西?这是我到目前为止的代码

import random
import string
guessAttempts = 0
myPassword = input("Enter a password for the computer to try and guess: ")
passwordLength = len(myPassword)
while True:
    guessAttempts = guessAttempts + 1
    passwordGuess = ''.join([random.choice(string.ascii_letters + string.digits)for n in range(passwordLength)])
    if passwordGuess == myPassword:
        print(passwordGuess)
        print("Password guessed successfully!")
        print("It took the computer %s guesses to guess your password." % (guessAttempts))
        break

任何帮助,将不胜感激

标签: python

解决方案


取 的n-way 产品string.ascii_letters + string.digits并对其进行迭代。

from itertools import product


passwords = map(''.join, product(string.ascii_letters + string.digits, repeat=n))
for (guessAttempts, passwordGuess) in enumerate(passwords, start=1):
    ...

itertools位于标准库中,因此无论您选择使用与否,它都已安装:您不妨使用它。


推荐阅读