0

I am trying to write a function which takes as argument a list of integers from the user input and sorts them.

I am getting some issues, because if I convert the integers to strings (I thought it could be the best way, because of the commas in the input) and append them in an empty list, I get an error.

Here the function:

def sort_integers(x):
    lst = []
    for i in x:
        lst.append(i)
        sorted_list = sorted(lst)
    print(sorted_list)
    
sort_integers(str(input("Enter some numbers: ")))

But if I enter 10, 9, 8 as integers, this is what I get as output:

[',', ',', '0', '1', '8', '9']

Expected output would be: 8,9,10. I have tried to use sort_integers(int(input("Enter some numbers: "))) but I get this error:

ValueError: invalid literal for int() with base 10: '10,9,8'

What am I doing wrong?

mkrieger1
  • 14,486
  • 4
  • 43
  • 54
  • 2
    Have you studied `split` yet? If not, do so. Google "Python split string". You need to split the input string and then turn the resulting list of strings into a list of numbers. – John Coleman Sep 17 '20 at 09:48
  • 1
    Does this answer your question? [How to read an array of integers from single line of input in python3](https://stackoverflow.com/questions/18332801/how-to-read-an-array-of-integers-from-single-line-of-input-in-python3) – mkrieger1 Sep 17 '20 at 09:50
  • Use input in a loop and append them as int in new list. Then sort() that list.. – TechieViN Sep 17 '20 at 09:51
  • @TechieViN That doesn't solve the problem of reading multiple numbers separated with commas from a single line. – mkrieger1 Sep 17 '20 at 09:52
  • 2
    Try `sort_integers(map(int, input("...").split(',')))`, i.e. `split` the string by `,`, then `map` each substring to `int` – tobias_k Sep 17 '20 at 09:53

3 Answers3

1

You are only interested in digits and when you use for loop you state the that for each symbol in my string add it to a list, , and ( space ) is a symbol to Python.

Using str.split() on a string returns a list with the elements from the string, have a read on it. split() accepts an argument that you want to split your string on, in your case its ,.

To achieve your result you can use the following:

def sort_integers(x):
    return sorted([x for x in x.split(',') if x.isdigit()])

I am returning the sorted list which is built from the string you pass to your function and taking only digits using str.isdigit() built-in method.

Also, you do not need to use str(input() because input() always returns a string no matter what you pass to it.

Jonas Palačionis
  • 3,922
  • 4
  • 16
  • 35
1

Try this:

def sort_integers(x):
    x = x.split(',')
    sorted_list = sorted([int(i) for i in x])
    print(sorted_list)

sort_integers(str(input("Enter some numbers: ")))

Or this (minimal change in your existing code)

def sort_integers(x):
    x = x.split(',')
    lst = []
    for i in x:
        lst.append(int(i))
        sorted_list = sorted(lst)
    print(sorted_list)


sort_integers(str(input("Enter some numbers: ")))

Output:

 Enter some numbers: 10,9,8
 [8, 9, 10]
Grayrigel
  • 3,112
  • 5
  • 13
  • 25
0

So I'm assuming your input was: 0,1,89

When you loop through this string one character at a time:

x = "0,1,89"
for i in x:
    print(i)

your output will be

0
,
1
,
8
9

when looping through a string, you get a single character at a time. Your problem is that you are also appending the , into the list.

First Solution:

def sort_integers(x):
    lst = []
    for i in x:
        if(i != ","):       # Only append to list of the character is not a comma
            lst.append(i)

    sorted_list = sorted(lst)    # You shouldn't sort the list in a loop, only after you have everything in the list already
    print(sorted_list)
    
sort_integers(str(input("Enter some numbers: ")))

Second Solution: (Recommended)

def sort_integers(x):
    lst = []
    for i in x:
        try:
            int(i)          # Try to convert the string to a number, 
                            # if it works the code will go on 
                            # otherwise it will be handled by except below
            lst.append(i)
        except ValueError:
            print("This is not a number so skipping")

    sorted_list = sorted(lst)    # You shouldn't sort the list in a loop, only after you have everything in the list already
    print(sorted_list)
    
sort_integers(str(input("Enter some numbers: ")))
dr_nyt
  • 177
  • 2
  • 8