Python Beginner, function is supposed to sort according to string EX 'asc'. Function does not sort double digits correctly EX 23 is between 2 and 3

Viewed 22

I am attaching the code below, I know there are some ways to clean it up or make it more efficient and would appreciate those tips as well, but I am mainly just struggling figuring out why double digit numbers in the list are not being sorted accordingly. 23 is between 2 and 3 for example, single digits work fine. Thank you for your time.

## Creating a function that takes in two strings and returns a list in a specific orientation depending on what string is entered

## Couldn't figure out how to make double digits go in order

def sort_list(list, string):
    if string == 'desc':
        list = sorted(list.split(), reverse = True)
        return list                     ## First section returns list in opposite order if 'desc'
    elif string == 'asc':
        list = sorted(list.split())
        return list                     ## Second retuns list in ascending order if 'asc' 
    elif string == 'none':
        list = list.split()
        return list                    ## Third returns list in same order if 'none' is chosen

    
def main():

    list = input('Please input numbers with spaces in between to create a list:\n')

    string = input('Please enter what order you would like your list returned to you:\n')


    print(sort_list(list,string))


main()

1 Answers

A few pointers

  • Don't use names like list, string which are reserved words in python.
  • Avoid code duplication. You are calling split on the same list multiple times which can be avoided
  • Sorted will sort even strings and in your code you are sorting strings. Instead you want to sort integers. So you have to convert the strings into integers by using int().
def sort_list(numbers_list, sort_order):
    numbers_list = [int(item) for item in numbers_list.split(" ") if item]
    if sort_order == 'desc':
        numbers_list = sorted(numbers_list, reverse=True)
    elif sort_order == 'asc':
        numbers_list = sorted(numbers_list)
    return numbers_list


def main():
    numbers_list = input(
        'Please input numbers with spaces in between to create a list:\n')
    sort_order = input(
        'Please enter what order you would like your list returned to you:\n')
    print(sort_list(numbers_list, sort_order))

Here in the below line I am doing a list comprehension. numbers_list = [int(item) for item in numbers_list.split(" ") if item]

This can be replaced with a basic for loop if you want as well.

new_num_list = []
for item in numbers_list.split(" "):
    if item:
        new_num_list.append(int(item))
    
Related