[英]n-dimensional traverse
I'm implementing the longest common subsequence for n dimensions. 我正在实现n维的最长公共子序列。 Current problem: how do I traverse the n strings?
当前问题:如何遍历n个字符串? Simply nesting
for
loops won't work anymore, because I need n of them. 简单地嵌套
for
循环将不再起作用,因为我需要n个。 What's the nice solution for that problem? 这个问题的解决方案是什么? Loops + recursion, I suppose, but how exactly?
我想,循环+递归,但究竟是怎么回事? I'm not asking for the complete algorithm, but only how to generate all combinations for the dynamic programming algorithm.
我不是要求完整的算法,而只是如何生成动态编程算法的所有组合。 Example in 2D:
二维示例:
for position, char in word0:
for position1, char1 in word1:
# code here
If you don't want to do it by recursion, you can implement n
nested "for" loops, like this (the "for" loops aren't literally for loops any more, though): 如果您不想通过递归进行操作,则可以实现
n
嵌套的“ for”循环,如下所示(“ for”循环实际上不再是for循环):
i
is the array of indices. i
是指数数组。
m
is the array of upper limits of each i
m
是每个i
的上限的数组
ii
is the index of the i
indices ( range(n)
) ii
是第i
索引的索引( range(n)
)
n=4 # just an example
m=[3 for ii in range(n)] # just an example
i=[0 for ii in range(n)]
while True:
print " ".join(["%2d"%x for x in i])
for ii in range(n-1,-1,-1):
i[ii] +=1
if i[ii]<m[ii]: break # index i[ii] has not yet reached its individual max. value
i[ii] = 0
if sum(i)==0: break # all indices have counted to max. value
This is similar to counting, say, from 0000 up to 9999, which would correspond to four words ten letters each: 0000->0001->0002->...->0009->0010->... At each stage you increase the last digit, and when it rolls over you increase the preceding one, etc, until when the first digit would roll over you're done. 这类似于计数,例如,从0000到9999,对应于四个单词,每个十个字母:0000-> 0001-> 0002 - > ...-> 0009-> 0010 - > ...在每个阶段你增加最后一个数字,当它翻过来你增加前一个数字等,直到第一个数字翻转你完成。
Here's one way you could encapsulate the counting in an iterator: 这是在迭代器中封装计数的一种方法:
def count(limits):
idcs = [0] * len(limits)
while True:
yield tuple(idcs)
for n in range(len(limits)-1, -1, -1):
idcs[n] += 1
if idcs[n] != limits[n]:
break
elif n == 0:
raise StopIteration
else:
idcs[n] = 0
words = ['foo', 'bar', 'xyzzy']
for idcs in count(map(len, words)):
chars = map(lambda w, i: w[i], words, idcs)
print idcs, chars
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.