Home > Net >  Print only one False or one True when needed
Print only one False or one True when needed

Time:06-04

I am writing a function that accepts a list of scores and when the j number is bigger than the average of all the numbers before it, at least once, it returns True, otherwise it returns False.

My only problem is that when I enter for example [1,1,1,9999] it returns False False True, I want only one True without the Falses. And for example, entering [1,1,2,2,3] returns 4 times False, I only need False once. How do I do that?

My code:

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)

EDIT: My code

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)

CodePudding user response:

You should use print(True) or return True after for-loop, not in 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

EDIT:

I think you have other mistakes in your code.

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

Result:

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
  • Related