質問

I'm implementing the longest common subsequence for n dimensions. Current problem: how do I traverse the n strings? Simply nesting for loops won't work anymore, because I need n of them. 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
役に立ちましたか?

解決

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.

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

他のヒント

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):

i is the array of indices.
m is the array of upper limits of each i
ii is the index of the i indices (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 
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top