D0nK3Y_D0nK D0nK3Y_D0nK - 1 year ago 154
Python Question

Error: object of type 'int' has no len()

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()


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])


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"]

for name in name_list:
    print name

Prints out

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download