[英]How to call an index value from an itertools permutation without converting it to a list?
我需要創建這些字符的所有組合:
'0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM. '
即 100 個字母長,例如:
'0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001'
我目前正在使用此代碼:
import itertools
babel = itertools.product(k_c, repeat = 100)
此代碼有效,但我需要能夠在某個索引處返回組合,但是itertools.product
不支持索引,將產品轉換為列表會產生 MemoryError,並遍歷產品直到達到某個值需要價值超過十億的時間太長了。
謝謝你的幫助
64 個字符和 100 個字母將有 64^100 種組合。 對於第一個字母的每個值,其余字母將有 64^99 種組合,然后是 64^98、64^97 等。
這意味着您的第 N 個組合可以表示為以 64 為基數的 N,其中每個“數字”代表字符串中字母的索引。
一個簡單的解決方案是通過逐步確定每個 position 的索引並獲取字符串的 rest 以及 N 的其余部分來遞歸地構建字符串:
chars = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM. '
def comboNumber(n,size=100):
if size == 1: return chars[n]
return comboNumber(n//len(chars),size-1)+chars[n%len(chars)]
output:
c = comboNumber(123456789000000000000000000000000000000000000123456789)
print(c)
# 000000000000000000000000000000000000000000000000000000000000000000000059.90jDxZuy6drpQdWATyZ8007dNJs
c = comboNumber(1083232247617211325080159061900470944719547986644358934)
print(c)
# 0000000000000000000000000000000000000000000000000000000000000000000000Python.Person says Hello World
相反,如果您想知道特定字符串位於哪個組合索引處,可以通過組合每個 position 處的字符索引(數字)來計算 base64 值:
s = "Python.Person says Hello World" # leading zeroes are implied
i = 0
for c in s:
i = i*len(chars)+chars.index(c)
print(i) # 1083232247617211325080159061900470944719547986644358934
您現在更接近於理解 base64 編碼,這與應用於 4 個字符(即 3 個二進制字節 --> 4 個字母數字字符)或其任何變體編碼的 24 位數字相同
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.