我开始学习python的基本编程,当我遇到排列时,我想看看我是否可以(为了好玩)强行用户输入..
它似乎适用于简短的PW,但我的计数器似乎有一个缺陷,或者我是否会错过一些关于排列的性质? ...对于任何相同长度的PW,计数器每次显示相同的数字......
此外,对于更长的PW来说存在内存错误,但我认为我通过使用生成器(yield)而不是列表来排除...或者不是我?
感谢您的帮助
import string
from itertools import permutations
characters = string.ascii_letters
user_pw = input('Set your PW')
attempts = 0
done = False
while True:
def Generator():
guess_storage = [''.join(p) for p in permutations(characters, len(user_pw))]
for current in guess_storage:
yield current
for guess in Generator():
attempts += 1
if guess == user_pw:
print('SUCESS: ')
print('Password: ', guess)
done = True
if done == True:
break
print('Attempts: ', attempts)
答案 0 :(得分:2)
我将从内存错误开始。通过做:
guess_storage = [''.join(p) for p in permutations(characters, len(user_pw))]
你正在粘合'将所有生成的排列重新放回单个列表中,然后迭代该列表。这是你内存不足的地方。相反,尝试使生成器迭代:
guess_storage = (''.join(p) for p in permutations(characters, len(user_pw)))
或者不使用生成器,只是join
每个排列都会产生(见下文)。
接下来,您将在while循环(包括生成器)中执行此操作,但这是不必要且低效的。只需构建一次Generator,然后当你循环生成器的每个猜测时,只要找到匹配就会爆发。
一种(较短的)写作我认为你想要的方式是:
def Generator():
for current in permutations(characters, len(user_pw)):
yield ''.join(current)
for guess in Generator():
print("Guessing", guess) # To show the guesses in action
attempts += 1
if guess == user_pw:
print('SUCCESS: ')
print('Password: ', guess)
print('Attempts: ', attempts)
break
您还可以使用以下方法避免手动跟踪尝试计数器:
for attempts, guess in enumerate(Generator()):