Sentinel Loop Python

时间:2014-02-21 17:33:09

标签: python loops python-2.7 sentinel

我应该如何在python中设置一个sentinel循环,只有当新输入的数字大于旧的输入数字时,循环才会继续运行?

这就是我现在所拥有的,但我知道这是不对的。

    totalScore = 0
    loopCounter = 0
    scoreCount = 0
    newScore = 0
    oldscore = newscore - 1
    print("Enter the scores:")
    score = (raw_input("Score 1"))
    while newScore >= oldScore:
        newScore = int(raw_input("Score " ) + (loopCounter + 1))
        scoreTotal = scoreTotal+newScore+oldScore
        scoreCount = scoreCount + 1
        loopCounter = loopCounter + 1
    averageScore = scoreTotal / scoreCount
    print "The average score is " + str(averageScore)

4 个答案:

答案 0 :(得分:2)

事实上处理此问题的方法是使用列表而不是每次丢弃个别分数。

scores = [0] # a dummy entry to make the numbers line up
print("Enter the scores: ")
while True: # We'll use an if to kick us out of the loop, so loop forever
    score = int(raw_input("Score {}: ".format(len(scores)))
    if score < scores[-1]:
        print("Exiting loop...")
        break
        # kicks you out of the loop if score is smaller
        # than scores[-1] (the last entry in scores)
    scores.append(score)
scores.pop(0) # removes the first (dummy) entry
average_score = sum(scores) / len(scores)
# sum() adds together an iterable like a list, so sum(scores) is all your scores
# together. len() gives the length of an iterable, so average is easy to test!
print("The average score is {}".format(average_score))

答案 1 :(得分:1)

您希望不断向用户询问新输入,而每次输入的数字更大。您可以使用列表来记录每个分数,然后使用sum built-in function为您完成工作:

scores = []
while True:
   current_size = len(scores)
   score = int(raw_input("Score %s" % (current_size + 1)))
   # Check if there's any score already entered and then if the new one is 
   # smaller than the previous one. If it's the case, we break the loop
   if current_size > 0 and score < scores[-1]:
       break
   scores.append(score)

# avg = total of each scores entered divided by the size of the list
avg = sum(scores) / len(scores)
print "The average score is %s" % avg

答案 2 :(得分:1)

您的代码存在各种问题,甚至无法运行。这是一个大概与您想要的相似的工作版本。

使用while循环管理旧值和新值是编码中常见的习惯,值得练习。

编辑:我自己错误地修改了代码行的顺序。代码现在给出了正确的平均值。

scoreTotal = 0
loopCounter = 0
scoreCount = 0
newScore = 0
oldScore = 0
print("Enter the scores:")
newScore = int(raw_input("Score 1: "))
while newScore >= oldScore:
    scoreTotal += newScore
    scoreCount += 1
    loopCounter += 1
    oldScore = newScore
    newScore = int(raw_input("Score " + str(loopCounter + 2) + ": "))
averageScore = float(scoreTotal) / float(scoreCount)
print scoreTotal, scoreCount
print "The average score is " + str(averageScore)

答案 3 :(得分:1)

根据Raymond Hettinger的演讲和Amir的博客文章http://blog.amir.rachum.com/blog/2013/11/10/python-tips-iterate-with-a-sentinel-value/

In [1]: def loop():
   ...:     old = 0
   ...:     while True:
   ...:         new = raw_input("gimme")
   ...:         yield new > old
   ...:         old = new
   ...:         

In [2]: l = loop()

In [4]: list(iter(l.next, False))
gimme1
gimme2
gimme0
Out[4]: [True, True]