函数,该函数接受二维列表并查找列的最大值

2024-05-19 18:42:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个函数,该函数接受一个2d列表,查找列表中列中值最高的部分,并返回列表中包括行和列的部分

这是一道模拟拼字游戏的作业题。本质上,给函数一个字符列表,它返回一个基于该单词的值和值本身的字符的最佳单词列表

在这个问题中有一些全局变量:scrabbleScores(一个字符及其值的列表)和Dictionary(所有您可能生成的单词)

例如,如果给它一个list,['a'、's'、'm'、't'、'p'],它将首先调用另一个函数,返回从该列表中可以生成的所有单词及其值,然后它将使用该列表并返回一个具有最佳单词及其值的列表

所以,我已经有了一个我一直在处理的函数,但是每当我运行它时,IDE就会给我一个“int object is not subscriptable”错误:

scrabbleScores = \
   [ ['a', 1], ['m', 3], ['p', 3], ['s', 1], ['t', 1] ]

Dictionary = ['a', 'am', 'at', 'apple', 'bat', 'bar', 'babble', 'can', 'foo',
              'spam', 'spammy', 'zzyzva']
#implementation missing because it works just fine, so just ignore this function
def letterScore(letter, scoreList):
    ''' letter = string; scoreList = list in the form of [character, value]
        returns the value associated with letter in scoreList '''
#implementation missing because it works just fine, so just ignore this function
def wordScore(S, scoreList):
    ''' S = string; scoreList = list in the form of [character, value]
        returns the sum of the values for each character in S '''

def scoreList(Rack):
    ''' Rack = list of lower-case characters
    returns a list of all of the words in the global Dictionary that can be made
    from those letters and the score for each word '''
    def scoreListHelper(Rack, Dictionary):
        if Dictionary == []:
            return []
        elif all(c in Rack for c in Dictionary[0]):
            return [[Dictionary[0], wordScore(Dictionary[0], scrabbleScores)]] + 
            scoreListHelper(Rack, Dictionary[1:])
        else:
            return scoreListHelper(Rack, Dictionary[1:])
    return scoreListHelper(Rack, Dictionary)

#this is the function that's having issues
def bestWord(Rack):
    ''' Rack = list of lower-case characters
    returns a list of the highest possible scoring word from Rack and the score 
    of the word '''
    def bestWordHelper(L):
        if L == []:
            return []
        elif len(L) == 1:
            return [L[0], L[0][0]]
        else:
            if L[1][1] > L[0][1]:
                return bestWordHelper(L[1:])
            else:
                return bestWordHelper(bestWordHelper(L[0:1]) + 
                bestWordHelper(L[1]))

    return bestWordHelper(scoreList(Rack))

print(bestWord(['a', 's', 'm', 't', 'p']))

scoreList()返回“[['a',1],['am',4],['at',2],['spam',8]]”,bestWord()应该返回“['spam',8]]”,但是它仍然不断地给我这个错误

如果你们能给我一些建议,我将不胜感激。最后,如果您提供了一个解决方案,它应该递归地工作/不使用循环。不管出于什么原因,我们都不允许在这个任务中使用循环。 另外,我知道我的'scoreList()'函数有一个循环,但我稍后会修改它,看看我是否可以使用递归来工作。现在,不要理会我的虚伪第


Tags: ofthe函数in列表dictionaryreturndef
1条回答
网友
1楼 · 发布于 2024-05-19 18:42:24

代码是复杂的,但我发现了一些错误,解决了错误的问题

bestWordHelper()需要2D list,但问题是[]在某些地方和+在list的元素之间,所以有时它会创建1D list而不是2D list,然后当您使用L[0][1]时它无法获得第二维度,最后您得到的是integer[0]而不是list[0],所以您会得到错误消息"int object is not subscriptable"


第一:你忘了[1]

 return [L[0][1], L[0][0]]

就像我说的bestWordHelper()需要2D列表,但要保持一致

 return bestWordHelper(bestWordHelper(L[0:1]) + bestWordHelper(L[1]))

你有L[1],这是1D列表。应该有相当的L[1:]

同一行中的另一个问题是+,它连接到1D列表并创建1D列表,但它必须创建2D列表

 return bestWordHelper( [bestWordHelper(L[0:1]), bestWordHelper(L[1L])] )

Finally代码(带有一些print()用于调试信息)

我还将listscrabbleScores转换为dictionary,因为它在这段代码中更有用。有了字典,获得letterScorewordScore就容易多了

scrabbleScores = [['a', 1], ['m', 3], ['p', 3], ['s', 1], ['t', 1]]

scrabbleScores = dict(scrabbleScores)
print(scrabbleScores)
#scrabbleScores = {'a': 1, 'm': 3, 'p': 3, 's': 1, 't': 1}

Dictionary = ['a', 'am', 'at', 'apple', 'bat', 'bar', 'babble', 'can', 'foo',
              'spam', 'spammy', 'zzyzva']

#implementation missing because it works just fine, so just ignore this function
def letterScore(letter, scoreList):
    ''' letter = string; scoreList = list in the form of [character, value]
        returns the value associated with letter in scoreList '''
    return scoreList[letter]

#implementation missing because it works just fine, so just ignore this function
def wordScore(S, scoreList):
    ''' S = string; scoreList = list in the form of [character, value]
        returns the sum of the values for each character in S '''
    return sum(scoreList[letter] for letter in S)

def scoreList(Rack):
    ''' Rack = list of lower-case characters
    returns a list of all of the words in the global Dictionary that can be made
    from those letters and the score for each word '''
    def scoreListHelper(Rack, Dictionary):
        if Dictionary == []:
            return []
        elif all(c in Rack for c in Dictionary[0]):
            return [[Dictionary[0], wordScore(Dictionary[0], scrabbleScores)]] + scoreListHelper(Rack, Dictionary[1:])
        else:
            return scoreListHelper(Rack, Dictionary[1:])
    return scoreListHelper(Rack, Dictionary)

#this is the function that's having issues
def bestWord(Rack):
    ''' Rack = list of lower-case characters
    returns a list of the highest possible scoring word from Rack and the score 
    of the word '''
    def bestWordHelper(L):
        print('input:', L)
        if not L:
            print('empty')
            return []
        elif len(L) == 1:
            print('one:', L, '->', [L[0][1], L[0][0]])
            return [L[0][1], L[0][0]]
        else:
            print('many:', L)
            if L[1][1] > L[0][1]:
                return bestWordHelper(L[1:])
            else:
                return bestWordHelper([bestWordHelper(L[0:1]), bestWordHelper(L[1:])])

    result = scoreList(Rack)
    print('result:', result)
    return bestWordHelper(result)

print(bestWord(['a', 's', 'm', 't', 'p']))

相关问题 更多 >