Home > Blockchain >  Finding max value from list without using max function. Must return none if list empty?
Finding max value from list without using max function. Must return none if list empty?

Time:10-01

Basically I am trying to use to find the max of the list of values without calling the max function. The code I have works but the problem is there is a stipulation that if list is empty, the function should return none. Currently I get an error out of range since I'm using an index to get my largest value from the sorted list.

SURVEY_RESULTS = [25,30,100,88,56]

def maximum(x):
    response_list = []
    for response in x:
        LifeExp = response
        response_list.append(LifeExp)
    response_list.sort()
    max_val = response_list[-1]
    return max_val
        
maximum(SURVEY_RESULTS)

CodePudding user response:

Use an if-statement.

SURVEY_RESULTS = [25,30,100,88,56]

def maximum(x):
    if len(x) != 0:
        response_list = [] 
        for response in x: 
            LifeExp = response 
            response_list.append(LifeExp) 
        response_list.sort() 
        max_val = response_list[-1] 
        return max_val
    else:
        return "none"

maximum(SURVEY_RESULTS)

CodePudding user response:

SURVEY_RESULTS = [25,30,100,88,56]

def maximum(x):
    return  sorted(x)[0] if len(x) > 0 else None

maxium(SURVEY_RESULTS)

  • Related