我怎么能不重复猜测呢?

2024-04-20 16:07:48 发布

您现在位置: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
    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

任何帮助都将不胜感激


Tags: thetoimportforstring情况randompassword
1条回答
网友
1楼 · 发布于 2024-04-20 16:07:48

nstring.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在标准库中,因此无论您是否选择使用它,它都已经安装好了:您也可以使用它

相关问题 更多 >