D0nK3Y_D0nK - 11 months ago 67

Python Question

I have a function that is supposed to take an array and sort it from the smallest string size to the largest and then print it by using injection sort.

On the line:

`while (j >=0) and (len(b[j]) > key):`

I get this error:

object of type 'int' has no len()

Code:

`def list_sort(b):`

for i in range(1, len(b)):

key = len(b[i])

j = i - 1

while (j >=0) and (len(b[j]) > key):

b[j+1] = b[j]

j = j - 1

b[j+1] = key

for i in range( len(b) ):

print (b[i])

list_sort(name)

Answer Source

I am not sure how you generated the error to begin with, since the input of `["alice", "bob", "sally"]`

didn't crash, but it does generate numbers.

That's probably because you assign `b_list[j+1] = keyValue`

, where `keyValue = len(b_list[i])`

, which will be an int, and so, if you ever hit that element again, and try to `len()`

on it, that's the error you are seeing.

Now, re-implementing this from the Wikipedia pseudo-code

```
def insertion_sort(A):
for i in range(1, len(A)):
j = i
s1 = A[j-1]
s2 = A[j]
while j > 0 and len(s1) > len(s2):
# swap A[j] and A[j-1]
tmp = A[j-1]
A[j-1] = A[j]
A[j] = tmp
j = j - 1
name_list = ["alice", "bob", "sally"]
insertion_sort(name_list)
for name in name_list:
print name
```

Prints out

```
bob
alice
sally
```