首页 > 解决方案 > 分级机未正确计算输出

问题描述

我目前正在解决 edX Python 课程中的问题,目标是创建一个像“Scrambler”这样的游戏。我在“playHand”这一步,这基本上是与玩家/用户的交互,在每个单词作为输入之后输出一个分数。

我已经编写了整个过程,它可以在在线编译器(python 导师)中完美运行。但是,当我在课程网站上的 IDE 中输入相同的代码时,它应该对我的答案进行评分并测试它自己的示例,正​​确的结果仅在第一次测试时出现(分数与预期匹配)。当第二次测试通过时,分数会累积在前一次测试的分数上,因此比需要的要大。


# some of the helper functions are dropped out from this code (but can be provided if needed)

# worldList is the list of words that are valid


single_period=["."]
score=0
def playHand(hand, wordList, n):

    while calculateHandlen(hand) > 0:
        global score

        if n<calculateHandlen(hand):
            print("n should be bigger than number of letters in the hand")
            break

        print("Current Hand: ",end =" ")
        displayHand(hand)

        word = input("Enter word, or a " + '"." ' + "to indicate that you are finished: ")

        if word in single_period:
            print("Goodbye! Total score: "+str(score)+" points") 
            break
        else:
            if isValidWord(word, hand, wordList)!=True:
                print("Ivalid word, please try again.")
                print('')  
            else:
                word_score=getWordScore(word, n)
                score=score+getWordScore(word, n)
                print("'"+str(word)+"'"+" earned "+str(word_score)+" points."+" Total: "+str(score)+" points")
                hand=updateHand(hand, word)
        if calculateHandlen(hand)==0:
            print("Run out of letters. Total score: "+str(score)+" points.")

例如,第一个测试是:

Function call: playHand({i: 1, k: 1, l: 1, m: 1})'<edX internal wordList>', 4

我的输出是(正确):

Current Hand:  k i m l 
Enter word, or a "." to indicate that you are finished: milk
'milk' earned 90 points. Total: 90 points
Run out of letters. Total score: 90 points.
None

第二个测试是:

Function call: playHand({a: 1, z: 1})'<edX internal wordList>', 2

我的输出是(不正确的过度累积):

Current Hand:  z a 
Enter word, or a "." to indicate that you are finished: zo
Ivalid word, please try again.

Current Hand:  z a 
Enter word, or a "." to indicate that you are finished: za
'za' earned 72 points. Total: 162 points
Run out of letters. Total score: 162 points.
None

*** ERROR: Failing on scoring the word.
Expected '" za " earned 72  points. Total:  72  points'
Got ''za' earned 72 points. Total: 162 points' ***

因此,正如所见,该测试从前一次测试中获取分数(90),而不是“归零”,将其用作第二次测试的新基础(90+72=162)等等......

有没有人上过这门课程或知道如何解决这个问题?

标签: pythonedx

解决方案


看起来他们不希望你在手牌上积累积分。

我猜 IDE 调用playHand了多次,您将手分数保留在 score 变量中,该变量是全局变量 ( global score),仅在您的函数之外设置为 0 一次。

您可以解决以下问题:

print("'"+str(word)+"'"+" earned "+str(word_score)+" points."+" Total: "+str(score)+" points")

这:

print("'"+str(word)+"'"+" earned "+str(word_score)+" points."+" Total: "+str(word_score)+" points")

score或在开头重置为 0 playHand


推荐阅读