0

所以我正在开发一个程序来创建portmanteaus。我有我需要的代码和功能,我把它们放在一起。

这是代码:

def portmanteauscore(start, mid, end):
    totallen = len(start) + len(mid) + len(end)
    return totallen - abs((len(start)/totallen) - len(start)) - abs((len(mid)/totallen) - len(mid)) - abs((len(end)/totallen) - len(end))


def portmanteaugenerator(word1, word2, words):
    mid = longest_common_substring(word1, word2)
    start = word1[:word1.index(mid)]
    end = word2[len(mid):]
    if start + mid in words and mid + end in words:
        return start, mid, end


def natalie(words):
    "Find the best Portmanteau word formed from any two of the list of words."
    wordpermutations = list(itertools.permutations(words))
    maxscore, bestnatalie = 0, ''
    for perm in wordpermutations:
        start, mid, end = portmanteaugenerator(perm[0], perm[1], words)
        if portmanteauscore(start, mid, end) > maxscore:
            bestnatalie, maxscore = start + mid + end, portmanteauscore(start, mid, end)
    print bestnatalie
    return bestnatalie


def longest_common_substring(s1, s2):
    m = [[0] * (1 + len(s2)) for i in xrange(1 + len(s1))]
    longest, x_longest = 0, 0
    for x in xrange(1, 1 + len(s1)):
        for y in xrange(1, 1 + len(s2)):
            if s1[x - 1] == s2[y - 1]:
                m[x][y] = m[x - 1][y - 1] + 1
                if m[x][y] > longest:
                    longest = m[x][y]
                    x_longest = x
            else:
                m[x][y] = 0
    return s1[x_longest - longest: x_longest]

但是当我运行代码时,我不断收到此错误消息,

Traceback (most recent call last):
 File "vm_main.py", line 33, in <module>
  import main
   File "/tmp/vmuser_ijxrjleuxj/main.py", line 107, in <module>
   print test_natalie()
  File "/tmp/vmuser_ijxrjleuxj/main.py", line 87, in test_natalie
assert natalie(['adolescent', 'scented', 'centennial', 'always', 'ado']) in        ('adolescented','adolescentennial')
  File "/tmp/vmuser_ijxrjleuxj/main.py", line 67, in natalie
     start,mid,end=portmanteaugenerator(perm[0],perm[1],words)
 TypeError: 'NoneType' object is not iterable

当我返回 portmanteau 生成器的 start、mid 和 end 变量时,就会发生这种情况。当给出一个单词列表时,它应该从两个单词中返回一个 portmanteau,根据 portmanteau 分数是最好的。

但由于某种原因,我不断收到这种类型的错误。我试过制作开始,中间,结束一个列表,但它仍然无法运行。你能帮我么?

4

1 回答 1

6

最有可能的是,start+mid in words and mid+end in words返回False等函数,而不是通过if-statement,返回None(因为如果一个函数不返回某些东西,它默认为None)。

然后你试图做类似的事情:

start,mid,end = None

python 试图做的是拆分None这三个变量。就像这样做:

one, two, three = (1, 2, 3)

但你不能,因为None它不是可迭代的。

于 2013-07-09T05:04:42.240 回答