簡體   English   中英

如何更快地迭代所有字符的組合?

[英]How can I iterate over combinations of all characters faster?

我有一個簡單的 function 使用 itertools 迭代所有字符的組合。 我已經計算出,對於 4 個字符的字符串,它需要 94 秒。 但是對於 7 來說,它已經需要大約 3600 小時或 157 天。 我嘗試過在有和沒有 cuda 的情況下使用 numba 的 jit,但它不起作用,因為 itertools 與 numba 不兼容。 我也嘗試過線程,但沒有奏效。 我這樣做了:

def test(j):
    pass

def start():
    start_time = time.time()
    for i in range(2, 3):
        for j in map(''.join, itertools.product(myLetters, repeat = i)):
            t = Thread(target = test, args = j)
            t.start() 

但它只是向我發送垃圾郵件“ThreadN 中的異常異常等。有人可以幫我讓這段代碼運行得更快嗎?提前致謝

這是你想要做的嗎? 此代碼將字符串的字符重新排列為所有排列。 對於 7 個字符,它基本上是瞬時的。

import itertools

word = '1234567'
word = list(word)

# Create all permutation of numbers that will be the indeces of the characters
all_permutations = list(itertools.permutations(range(len(word))))

# For each permutation create a string that has each of its characters repositioned to new index
for permutation in all_permutations:
    new_word = ''.join([word[i] for i in permutation])
    print(f'new_word = {new_word}')

這將為您提供所有組合(通俗地說),而無需一次將它們存儲在 memory 中:

import itertools

def get_next_combination(iterable):
    for i in range(1, len(iterable)+1):
        yield from map("".join, itertools.product(iterable, repeat=i))


for combination in get_next_combination("abc"):
    print(combination)
    # if hash_algorithm(combination) == known_hash: print("Password found!")

Output:

a
b
c
aa
ab
ac
ba
bb
bc
ca
cb
cc
aaa
aab
aac
aba
abb
abc
aca
acb
acc
baa
bab
bac
bba
bbb
bbc
bca
bcb
bcc
caa
cab
cac
cba
cbb
cbc
cca
ccb
ccc

它可以在約 3 秒內處理 7 個字符串,不用擔心。

如果您實際上是在嘗試破解密碼,我建議您只使用 hashcat,或者至少使用大量已知密碼進行字典攻擊。

使用多線程實際上可能不會加快速度,因為 [參考實現] Python 一次只會執行一個 Python 字節碼。 雖然我相信 itertools 是用 C 編寫的,但它可能會發布 GIL。 盡管如此,您通常需要利用multiprocessing來改進受 CPU 限制的 Python 程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM