计算迭代工具的第n个结果。product()

本教程将介绍计算迭代工具的第n个结果。product()的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

计算迭代工具的第n个结果。product() 教程 第1张

问题描述

我正在尝试计算迭代工具的第n个结果。product()

test = list(product('01', repeat=3))
print(test)

desired_output = test[0]
print(desired_output)

所以不是得到:

[('0', '0', '0'), ('0', '0', '1'), ('0', '1', '0'), ('0', '1', '1'), ('1', '0', '0'), ('1', '0', '1'), ('1', '1', '0'), ('1', '1', '1')]

我正在尝试获取:

('0', '0', '0')

但是,正如您可能已经猜到的那样,它不能很好地伸缩。这就是我尝试只计算第n个值的原因。

我通读了
Nth Combination但我需要产品()提供的重复功能

提前谢谢!

推荐答案

repeat功能很容易模拟。这里是this博客文章中描述的Ruby代码的一个Python版本。

def product_nth(lists, num):
 res = []
 for a in lists:
  res.insert(0, a[num % len(a)])
  num //= len(a)

 return ''.join(res)

将此函数调用为

>>> repeats = 50
>>> chars = '01'
>>> product_nth([chars] * repeats, 12345673)
'00000000000000000000000000101111000110000101001001'

以下是它测试的一些时间:

repeat = 50
idx = 112345673

%timeit i = product_nth(['01'] * repeat, idx)
%%timeit
test = product('01', repeat=repeat)
one = islice(test, idx, idx+1)
j = ''.join(next(one))

2.01 s ± 22.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
36.5 µs ± 201 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

print(i == j)
True

另一个答案具有误导性,因为它歪曲了islice的功能。例如,请参阅:

def mygen(r):
 i = 0
 while i < r:
  print("Currently at", i)
  yield i
  i += 1

list(islice(mygen(1000), 10, 11))

# Currently at 0
# Currently at 1
# Currently at 2
# Currently at 3
# Currently at 4
# Currently at 5
# Currently at 6
# Currently at 7
# Currently at 8
# Currently at 9
# Currently at 10
# Out[1203]: [10]

islice将单步执行,在指定索引之前丢弃结果。对product的输出进行切片时也会发生同样的情况-该解决方案对大N无效。

好了关于计算迭代工具的第n个结果。product()的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。