Python 我怎么能不重复猜测呢?

Python 我怎么能不重复猜测呢?,python,Python,我如何在不重复猜测、也不导入任何其他内容的情况下强行输入密码?这是到目前为止我的代码 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

我如何在不重复猜测、也不导入任何其他内容的情况下强行输入密码?这是到目前为止我的代码

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

任何帮助都将不胜感激

请使用
string.ascii_字母+string.digits
n
-way乘积并对其进行迭代

from itertools import product


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

itertools
位于标准库中,因此无论您是否选择使用它,它都已安装:您也可以使用它。

使用列表跟踪您的尝试使用
itertools
为您的pw方案生成所有可能组合的生成器。这有利于动态生成猜测,因此您不需要数十万个密码的列表——它会一个接一个地生成密码。我同意@Cheche,但使用
集(set
:)不要使用随机密码。暴力强制的要点是尝试所有可能的组合一次,而不是无限的随机填充你枚举可能的密码,而不是在可能的密码空间中随机跳跃。否则,您需要存储您已经尝试过的密码,这会占用(相当多)更多内存,并且无法解决生成重复密码的问题。