0

So in my class the professor gave us this insertion-based sorting code, but I need it to sort lists that have numbers and text.

I've already tried using if isinstance conditions, but it seems the problem is in the while loop

def insertion_sort(vector):
    print(vector)
    for i in range(1,len(vector)):
        actual=vector[i]
        j=i
        while j>0 and actual<vector[j-1]: #This is where the problem seems
            vector[j]=vector[j-1]         #to be.
            j=j-1
        vector[j]=actual
    return vector

This is the output error message:

Traceback (most recent call last):
  File "F:\Python\sortactivity.py", line 53, in <module>
    print(insertion_sort(text))
  File "F:\Python\sort.py", line 9, in insertion_sort
    while j>0 and actual<vector[j-1]:
TypeError: '<' not supported between instances of 'int' and 'str'

The testing list that I have is:

lst=['s9','d5',9,5,1,24,12,'test',21]
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
Nin
  • 1
  • 2
    So, what should the order be? ascending `int`s first, then strings in lexicographic order? Or mixed, where the integers are treated like strings, and the whole thing is sorted lexicographically? In other words, what's the desired output? – Paul M. Nov 09 '19 at 21:12
  • 1
    Did your teacher explain what it means for a string to be "less than" a number? An array is only in ascending sorted order if elements on the left are less than or equal to elements on the right. For example, `[1, 29, 334, 563]` Clearly, 1 is less than 29. So, is the string '"test"' less than `21`? `21` less than `"test"`? Are `"test"` and `21` equal? – Toothpick Anemone Nov 09 '19 at 21:21
  • Well, the output I want is just the list sorted, I can reverse() it if the user in my example wants an ascending or descending order. He also gave us a bubble-sort code, but I've already managed it to sort strings with ints (I think...) and it sorts first the ints and then the strings, so I guess that's what I want as an output. – Nin Nov 09 '19 at 21:49

0 Answers0