需要时只打印一个 False 或一个 True

Print only one False or one True when needed

我正在编写一个接受分数列表的函数,当 j 数字大于它之前所有数字的平均值时,至少一次,它 returns True, 否则它 returns False.

我唯一的问题是,当我输入 [1,1,1,9999] 时,它 returns False False True,我只想要一个没有 Falses 的 True。又比如输入[1,1,2,2,3] returns 4次False,我只需要一次False。我该怎么做?

我的代码:

def Outstanding_Scores(scores):
    
    for j in range(0,len(scores)-1):
        if sum(scores[j::-1])//len(scores[j::-1]) < scores[j+1]:
            print('True')
            break
        else:
            print('False')
             
            
scoresInput = input().split(',')
scoreslist = [int(i) for i in scoresInput]

Outstanding_Scores(scoreslist)

编辑:我的代码

def Outstanding_Scores(scores):
    
    for j in range(0,len(scores)-1):
        return True if (sum(scores[j::-1])//len(scores[j::-1]) < scores[j+1]) else False
            
scoresInput = input().split(',')
scoreslist = [int(i) for i in scoresInput]

suspicious_income(scoreslist)

您应该在 for 循环之后使用 print(True)return True,而不是在 else

def Outstanding_Scores(scores):
    
    for j in range(0,len(scores)-1):
        if sum(scores[j::-1])//len(scores[j::-1]) < scores[j+1]:
            return True

    # --- after loop ---

    return False

# --- main ---

print( Outstanding_Scores([1,1,1,9999]) )  # True
print( Outstanding_Scores([1,1,2,2,3]) )   # True

编辑:

我认为您的代码中还有其他错误。

def Outstanding_Scores(scores):

    # --- before loop ---

    if len(scores) < 2:
        return False

    # --- loop ---
    
    for j in range(1, len(scores)):
        
        current  = scores[j]
        previous = scores[:j]
        
        average = sum(previous) / len(previous)

        print(f'j: {j:2} | val: {current:5} | average: {average:5} | previous: {previous} | {current > average}')
        
        if current > average:
            return True

    # --- after loop ---

    return False

print( Outstanding_Scores([1,1,1,9999]) )  # True
print( Outstanding_Scores([1,1,2,2,3]) )   # True
print( Outstanding_Scores([1,1,1,1]) )     # False

结果:

j:  1 | val:     1 | average:   1.0 | previous: [1] | False
j:  2 | val:     1 | average:   1.0 | previous: [1, 1] | False
j:  3 | val:  9999 | average:   1.0 | previous: [1, 1, 1] | True
True
j:  1 | val:     1 | average:   1.0 | previous: [1] | False
j:  2 | val:     2 | average:   1.0 | previous: [1, 1] | True
True
j:  1 | val:     1 | average:   1.0 | previous: [1] | False
j:  2 | val:     1 | average:   1.0 | previous: [1, 1] | False
j:  3 | val:     1 | average:   1.0 | previous: [1, 1, 1] | False
False