簡體   English   中英

n維遍歷

[英]n-dimensional traverse

我正在實現n維的最長公共子序列。 當前問題:如何遍歷n個字符串? 簡單地嵌套for循環將不再起作用,因為我需要n個。 這個問題的解決方案是什么? 我想,循環+遞歸,但究竟是怎么回事? 我不是要求完整的算法,而只是如何生成動態編程算法的所有組合。 二維示例:

for position, char in word0:
  for position1, char1 in word1:
    # code here

如果您不想通過遞歸進行操作,則可以實現n嵌套的“ for”循環,如下所示(“ for”循環實際上不再是for循環):

i是指數數組。
m是每個i的上限的數組
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 

這類似於計數,例如,從0000到9999,對應於四個單詞,每個十個字母:0000-> 0001-> 0002 - > ...-> 0009-> 0010 - > ...在每個階段你增加最后一個數字,當它翻過來你增加前一個數字等,直到第一個數字翻轉你完成。

這是在迭代器中封裝計數的一種方法:

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.

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