Home > Back-end >  Where to place sort()
Where to place sort()

Time:04-07

I'm currently working on this code. I need to extract the min and max value in the list, but for some reason they are extracting the first inputted value and the last inputted value as the max. I want to add the sort() function to sort the values in the list from lower to higher, but I don't really know where to put it. Code's below. The list is called ages.

def getAges():
    agesAmount= int(input("How many ages do you want to evaluate: "))
    while agesAmount!= 0:
        ages= []
        numAge= 1
        for i in range(agesAmount):
            ages.append(input("Enter age " str(numAge) ": "))
            numAge = 1
        agesAmount //= 10

Any help would be appreciated.

CodePudding user response:

Convert your ages to integer

ages.append(int(input("Enter age " str(numAge) ": ")))

moreover you don't need numAge

while agesAmount!= 0:
    ages= []
    for i in range(agesAmount):
        ages.append(int(input("Enter age " str(i) ": ")))
    ages.sort()
    print(ages)

CodePudding user response:

What I can suggest to you is what follows:

def getAges():
    agesAmount= int(input("How many ages do you want to evaluate: "))
    while agesAmount!= 0:
        ages= []
        numAge= 1
        for i in range(agesAmount):
            ages.append(input("Enter age " str(numAge) ": "))
            numAge = 1
        agesAmount //= 10
    return(sorted(ages, key=lambda x: int(x)))

Example output

How many ages do you want to evaluate: 5
Enter age 1: 5
Enter age 2: 4
Enter age 3: 3
Enter age 4: 1
Enter age 5: 2
['1', '2', '3', '4', '5']

sorted takes two arguments (mostly just one, but you can always consider adding a key argument to make a pattern for sorting). The former is an iterable object and the latter, as said before, is a pattern for sorting. If you are explicitly interested in just using sort function, follow the next snippet:

def getAges():
    agesAmount= int(input("How many ages do you want to evaluate: "))
    while agesAmount!= 0:
        ages= []
        numAge= 1
        for i in range(agesAmount):
            ages.append(input("Enter age " str(numAge) ": "))
            numAge = 1
        agesAmount //= 10
    ages.sort(key=lambda x: int(x))
    return(ages)

Note that, sort function in List objects use variable by reference, so you will just need to call it on the variable without assigning its output to any other variable. It will do the job for you. The output of the code above would be the same as the first code snippet.

  • Related