0

I am writing a code to take user input and sort it in descending order. This is my code so far.

array = []
array=input().split()

for i in range(len(array)):
    max_index = i
    for j in range(i+1, len(array)):
        if int(array[j]) > int(array[max_index]):
            max_index = j
    array[i],array[max_index] = array[max_index],array[i]

    print(array)

The input is

50 40 20 10 30

The output I get is

['50', '40', '20', '10', '30']
['50', '40', '20', '10', '30']
['50', '40', '30', '10', '20']
['50', '40', '30', '20', '10']
['50', '40', '30', '20', '10']

What I need is

   [50, 40, 20, 10, 30]
   [50, 40, 20, 10, 30]
   [50, 40, 30, 10, 20]
   [50, 40, 30, 20, 10]
   [50, 40, 30, 20, 10]
    

How do I remove the apostrophes and include a new line on the end? I'm new to programming (Have only been learning for roughly 4 weeks.

  • It seems that your `input().split()` is returning `['10', '20', ..., '50']` and not `[10, 20, ..., 50]` like you suggested. I believe that changing `array=input().split()` to `array=[int(n) for n in input().split()]` should work as you want. – Felipe Whitaker Dec 23 '21 at 01:17
  • Use int inputs instead of string inputs. Your sort will work as expected and your print will work as desired. – erip Dec 23 '21 at 01:17

3 Answers3

0

Although your input is 10 20 30 40 50 which would make you believe that those are integers (int), Python's input returns a str. Thus transforming your input into integers will make your code work as you seem to expect.

array = [int(n) for n in input().split()]
print(array) # Out[0]: [10, 20, 30, 40, 50]
...
Felipe Whitaker
  • 470
  • 3
  • 9
0

You're input is outputting strings, so you should add the built-in int() function to each item in the input. This would look like this: array = [int(i) for i in input().split()]

To add an extra line to your output, you just need to print out a new line, using the \n escape sequence. Your final code should be something like this:

array = []
array = [int(i) for i in input().split()]

for i in range(len(array)):
    max_index = i
    for j in range(i+1, len(array)):
        if int(array[j]) > int(array[max_index]):
            max_index = j
    array[i],array[max_index] = array[max_index],array[i]

    print(array)
print('\n')

If you enter

50 40 20 10 30

you will get

[50, 40, 20, 10, 30]
[50, 40, 20, 10, 30]
[50, 40, 30, 10, 20]
[50, 40, 30, 20, 10]
[50, 40, 30, 20, 10]

krmogi
  • 2,588
  • 1
  • 10
  • 26
0
array = []
array = input().split()

array = [int(x) for x in array]

for i in range(len(array)):
    max_index = i
    for j in range(i + 1, len(array)):
        if int(array[j]) > int(array[max_index]):
            max_index = j
    array[i], array[max_index] = array[max_index], array[i]

    print(array)
Pylogmon
  • 1
  • 2