python - 使用随机模块避免重复值
问题描述
下面是一个“蛮力”单词猜测......事情。即使知道使用蛮力的字符数,我也不会向我的兄弟姐妹证明找到密码需要多长时间。在让它运行了几个小时但没有成功之后,我认为他明白了这一点。现在我想把它背后的一些逻辑放在我的生活中,我无法弄清楚。我在网上找到了与我想要的类似的东西,但我不知道如何使其适应我的代码。
import string
import random
def make_random():
return''.join([random.choice(string.ascii_uppercase) for n in xrange(3)])
while True:
random2=make_random()
if random2 != "AAA":
print(random2)
if random2 == "AAA":
print("AAA")
print("Found")
break
我认为我需要一个变量来跟踪所有猜测的选择,并将其与新字符串进行比较并设置它们,使它们不能相等,但老实说我不知道。
任何帮助都是很好的帮助。
解决方案
如果有人要系统地尝试所有不同的密码,那么他需要遍历所有可能的组合,而不是两次尝试相同的组合。这是在 Python 中执行此操作的一种方法:
import itertools
import string
real_pass = 'AAC'
def find_num_iterations_to_guess_password(pass_length):
all_letters = string.ascii_uppercase
iterations = 0
for i in itertools.product(all_letters, repeat=pass_length):
guess = ''.join(i)
if guess == real_pass:
print(f'the real password is {guess} and was guessed after {iterations}')
break
iterations += 1
find_num_iterations_to_guess_password(len(real_pass))
推荐阅读
- r - R:如何正确地为 ggmap 地理编码/谷歌地理编码 API 准备一个国际地址?
- python - DJANGO:创建一个允许下载 zip 文件的按钮
- mysql - 如何在mysql中替换JSON键的值
- java - 在java中使用try和catch查找元素数组
- mongodb - 将 mongo 连接到 mlab 时出现问题(登录失败)
- linux - Linux命令`ps ao args`中的`args`是什么意思?
- javascript - 嵌套的 const JSX
- batch-file - 提取 windows server 中所有本地组中的所有用户
- ms-access - MS Access:根据日期字段计算下一季度的第一天
- java - 如果我在 64 位系统中安装 32 位 Android Studio,它会正常工作吗?