首页 > 解决方案 > 使用随机模块避免重复值

问题描述

下面是一个“蛮力”单词猜测......事情。即使知道使用蛮力的字符数,我也不会向我的兄弟姐妹证明找到密码需要多长时间。在让它运行了几个小时但没有成功之后,我认为他明白了这一点。现在我想把它背后的一些逻辑放在我的生活中,我无法弄清楚。我在网上找到了与我想要的类似的东西,但我不知道如何使其适应我的代码。

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

我认为我需要一个变量来跟踪所有猜测的选择,并将其与新字符串进行比较并设置它们,使它们不能相等,但老实说我不知道​​。

任何帮助都是很好的帮助。

标签: pythonpython-2.7randombrute-force

解决方案


如果有人要系统地尝试所有不同的密码,那么他需要遍历所有可能的组合,而不是两次尝试相同的组合。这是在 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))

推荐阅读