Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python蛮力算法_Python_Algorithm_Brute Force - Fatal编程技术网

Python蛮力算法

Python蛮力算法,python,algorithm,brute-force,Python,Algorithm,Brute Force,我需要生成从给定字符集到给定范围的所有可能组合。 像 而输出应该是, [a,b,c,d..................,zzzzzzzzzy,zzzzzzzzzz] 我知道我可以使用已经在用的库来实现这一点。但我需要知道它们是如何工作的。如果有人能给我一个Python或任何可读的编程语言的这种算法的注释代码,我将非常感激 如果你真的想对它施暴,试试这个,但这会花费你很多时间: your_list = 'abcdefghijklmnopqrstuvwxyz' complete_list =

我需要生成从给定字符集到给定范围的所有可能组合。 像

而输出应该是,

[a,b,c,d..................,zzzzzzzzzy,zzzzzzzzzz]

我知道我可以使用已经在用的库来实现这一点。但我需要知道它们是如何工作的。如果有人能给我一个Python或任何可读的编程语言的这种算法的注释代码,我将非常感激

如果你真的想对它施暴,试试这个,但这会花费你很多时间:

your_list = 'abcdefghijklmnopqrstuvwxyz'
complete_list = []
for current in xrange(10):
    a = [i for i in your_list]
    for y in xrange(current):
        a = [x+i for i in your_list for x in a]
    complete_list = complete_list+a
在一个较小的示例中,其中list='ab',我们只增加到5,这将打印以下内容:

['a', 'b', 'aa', 'ba', 'ab', 'bb', 'aaa', 'baa', 'aba', 'bba', 'aab', 'bab', 'abb', 'bbb', 'aaaa', 'baaa', 'abaa', 'bbaa', 'aaba', 'baba', 'abba', 'bbba', 'aaab', 'baab', 'abab', 'bbab', 'aabb', 'babb', 'abbb', 'bbbb', 'aaaaa', 'baaaa', 'abaaa', 'bbaaa', 'aabaa', 'babaa', 'abbaa', 'bbbaa', 'aaaba','baaba', 'ababa', 'bbaba', 'aabba', 'babba', 'abbba', 'bbbba', 'aaaab', 'baaab', 'abaab', 'bbaab', 'aabab', 'babab', 'abbab', 'bbbab', 'aaabb', 'baabb', 'ababb', 'bbabb', 'aabbb', 'babbb', 'abbbb', 'bbbbb']
使用,结合将各种长度组合在一起:

from itertools import chain, product
def bruteforce(charset, maxlength):
    return (''.join(candidate)
        for candidate in chain.from_iterable(product(charset, repeat=i)
        for i in range(1, maxlength + 1)))
演示:

>>> list(bruteforce('abcde', 2))
['a', 'b', 'c', 'd', 'e', 'aa', 'ab', 'ac', 'ad', 'ae', 'ba', 'bb', 'bc', 'bd', 'be', 'ca', 'cb', 'cc', 'cd', 'ce', 'da', 'db', 'dc', 'dd', 'de', 'ea', 'eb', 'ec', 'ed', 'ee']
这将有效地使用输入集生成越来越大的单词,最大长度为maxlength

不要试图生成长度不超过10的26个字符的内存列表;相反,迭代生成的结果:

for attempt in bruteforce(string.ascii_lowercase, 10):
    # match it against your password, or whatever
    if matched:
        break

itertools
非常适合以下情况:

itertools.chain.from_iterable((''.join(l)
                               for l in itertools.product(charset, repeat=i))
                              for i in range(1, maxlen + 1))
试试这个:

import os
import sys

Zeichen=["a","b","c","d","e","f","g","h"­,"i","j","k","l","m","n","o","p","q­","r","s","­;t","u","v","w","x","y","z"]
def start(): input("Enter to start")
def Gen(stellen): if stellen==1: for i in Zeichen: print(i) elif stellen==2: for i in Zeichen:    for r in Zeichen: print(i+r) elif stellen==3: for i in Zeichen: for r in Zeichen: for t in Zeichen:     print(i+r+t) elif stellen==4: for i in Zeichen: for r in Zeichen: for t in Zeichen: for u in Zeichen:    print(i+r+t+u) elif stellen==5: for i in Zeichen: for r in Zeichen: for t in Zeichen: for u in    Zeichen: for o in Zeichen: print(i+r+t+u+o) else: print("done")

#*********************
start()
Gen(1)
Gen(2)
Gen(3)
Gen(4)
Gen(5)

使用递归的解决方案:

def brute(string, length, charset):
    if len(string) == length:
        return
    for char in charset:
        temp = string + char
        print(temp)
        brute(temp, length, charset)
用法:

brute("", 4, "rce")

我发现了另一种使用itertools创建词典的非常简单的方法

generator=itertools.combinations_with_replacement('abcd', 4 )
这将遍历“a”、“b”、“c”和“d”的所有组合,并创建总长度为1到4的组合。即a、b、c、d、aa、ab………、dddc、dddd。生成器是一个itertool对象,您可以像这样正常循环

for password in generator:
        ''.join(password)
每个密码都是tuple类型的,您可以像平常一样使用它们。

来自随机导入选项
from random import choice

sl = 4  #start length
ml = 8 #max length 
ls = '9876543210qwertyuiopasdfghjklzxcvbnm' # list
g = 0
tries = 0

file = open("file.txt",'w') #your file

for j in range(0,len(ls)**4):
    while sl <= ml:
        i = 0
        while i < sl:
            file.write(choice(ls))
            i += 1
        sl += 1
        file.write('\n')
        g += 1
    sl -= g
    g = 0
    print(tries)
    tries += 1


file.close()
sl=4#起始长度 ml=8#最大长度 ls='9876543210QWERTYUIOPASDSFGHJKLZXCVBNM'#列表 g=0 尝试=0 file=open(“file.txt”,“w”)#您的文件 对于范围(0,len(ls)**4)内的j:
如果你真的想要一个bruteforce算法,不要在你的计算机内存中保存任何大的列表,除非你想要一个缓慢的算法,它会因为内存错误而崩溃

您可以尝试使用itertools.product,如下所示:

from string import ascii_lowercase
from itertools import product

charset = ascii_lowercase  # abcdefghijklmnopqrstuvwxyz
maxrange = 10


def solve_password(password, maxrange):
    for i in range(maxrange+1):
        for attempt in product(charset, repeat=i):
            if ''.join(attempt) == password:
                return ''.join(attempt)


solved = solve_password('solve', maxrange)  # This worked for me in 2.51 sec
itertools.product(*iterables)
返回您输入的iterables的笛卡尔乘积

[i for i in product('bar',(42),)]
返回例如
[('b',42),('a',42),('r',42)]

repeat
参数允许您精确地执行您的请求:

[i for i in product('abc', repeat=2)]
返回

[('a', 'a'),
 ('a', 'b'),
 ('a', 'c'),
 ('b', 'a'),
 ('b', 'b'),
 ('b', 'c'),
 ('c', 'a'),
 ('c', 'b'),
 ('c', 'c')]
注意

你想要一个蛮力算法,所以我给了你。现在,当密码开始变大时,这是一个非常长的方法,因为它呈指数增长(找到“已解决”一词需要62秒)。

使用itertools和字符串模块的简单解决方案 我通过管道将输出传输到一个文件以保存ram,并使用了输入函数,以便您可以将字符限制设置为类似“hiiworld”的内容。下面是相同的脚本,但使用字母、数字、符号和空格的字符集更加流畅

import itertools, string

maxChar = int(input('Character limit for password: '))
output_file = open('insert filepath here', 'a+')

x = list(map(''.join, itertools.permutations(string.printable, maxChar)))
x.write(str(x))
x.close()

你试过什么?这是家庭作业吗?这应该不会太难。
list(map(str,“abc…”)
是有史以来最无用的代码。这是~2PB的数据。我认为您不想强行执行此操作。旁白:
list()
返回一个列表
map()
也返回一个列表。如果您的输入确实需要是一个列表(我对此表示怀疑),请使用
charset=list(string.lowercase)
这将占用大约1.6 PB的ram。以每毫秒10次的速度对它进行迭代大约需要11000年的时间。你所说的荒谬的时间是指它很难处理,并且在完成之前会耗尽内存,对吗?除非你的计算机内存远远超过4410270 GB,否则它也会崩溃。用python 3中的del语句消耗的内存会更少吗?顺便说一句,我知道这很古老。@Madushan:老实说,你选择的答案不是我给老师看的代码。@Madushan:我的方法的核心是
itertools.product
方法,它在文档中列出了一个实现,因此你可以理解我们如何轻松地生成所有可能的组合。我喜欢什么?生成如此数量的数据时,您确实需要像这样使用生成器。请不要使用纯代码发布答案,还要添加文本以说明您的解决方案如何解决问题。这不适合创建密码,因为itertools会跳过可能的结果。示例:查找“ab”之间的所有组合,例如,应为4<代码>aa
ba
ab
bb
。现在,itertools将只返回3个可能的组合,其中包含替换('ab',2),例如:
aa
ab
bb
import string, itertools

    #password = input("Enter password: ")

    password = "abc"

    characters = string.printable

    def iter_all_strings():
        length = 1
        while True:
            for s in itertools.product(characters, repeat=length):
                yield "".join(s)
            length +=1

    for s in iter_all_strings():
        print(s)
        if s == password:
            print('Password is {}'.format(s))
            break
# modules to easily set characters and iterate over them
import itertools, string 

# character limit so you don't run out of ram
maxChar = int(input('Character limit for password: '))  

# file to save output to, so you can look over the output without using so much ram
output_file = open('insert filepath here', 'a+') 

# this is the part that actually iterates over the valid characters, and stops at the 
# character limit.
x = list(map(''.join, itertools.permutations(string.ascii_lowercase, maxChar))) 

# writes the output of the above line to a file 
output_file.write(str(x)) 

# saves the output to the file and closes it to preserve ram
output_file.close() 
import itertools, string

maxChar = int(input('Character limit for password: '))
output_file = open('insert filepath here', 'a+')

x = list(map(''.join, itertools.permutations(string.printable, maxChar)))
x.write(str(x))
x.close()