[英]How to call an index value from an itertools permutation without converting it to a list?
I need to create all combinations of these characters:我需要创建这些字符的所有组合:
'0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM. '
That are 100 letters long, such as:即 100 个字母长,例如:
'0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001'
I'm currently using this code:我目前正在使用此代码:
import itertools
babel = itertools.product(k_c, repeat = 100)
This code works, but I need to be able to return the combination at a certain index, however itertools.product
does not support indexing, turning the product into a list yields a MemoryError, and iterating through the product until I reaches a certain value takes too long for values over a billion.此代码有效,但我需要能够在某个索引处返回组合,但是
itertools.product
不支持索引,将产品转换为列表会产生 MemoryError,并遍历产品直到达到某个值需要价值超过十亿的时间太长了。
Thanks for any help谢谢你的帮助
With 64 characters and 100 letters there will be 64^100 combinations. 64 个字符和 100 个字母将有 64^100 种组合。 For each value of the first letter, there will be 64^99 combinations of the remaining letters, then 64^98, 64^97, and so on.
对于第一个字母的每个值,其余字母将有 64^99 种组合,然后是 64^98、64^97 等。
This means that your Nth combination can be expressed as N in base 64 where each "digit" represents the index of the letter in the string.这意味着您的第 N 个组合可以表示为以 64 为基数的 N,其中每个“数字”代表字符串中字母的索引。
An easy solution would be to build the string recursively by progressively determining the index of each position and getting the rest of the string with the remainder of 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: output:
c = comboNumber(123456789000000000000000000000000000000000000123456789)
print(c)
# 000000000000000000000000000000000000000000000000000000000000000000000059.90jDxZuy6drpQdWATyZ8007dNJs
c = comboNumber(1083232247617211325080159061900470944719547986644358934)
print(c)
# 0000000000000000000000000000000000000000000000000000000000000000000000Python.Person says Hello World
Conversely, if you want to know at which combination index a particular string is located, you can compute the base64 value by combining the character index (digit) at each position:相反,如果您想知道特定字符串位于哪个组合索引处,可以通过组合每个 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
You are now this much closer to understanding base64 encoding which is the same thing applied to 24bit numbers coded over 4 characters (ie 3 binary bytes --> 4 alphanumeric characters) or any variant thereof您现在更接近于理解 base64 编码,这与应用于 4 个字符(即 3 个二进制字节 --> 4 个字母数字字符)或其任何变体编码的 24 位数字相同
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.