TypeError - 'int' object has no attribute '__getitem__' when iterating over list

0

Problem: Write a function that accepts a list of integers and return a list that is the drawn version (of ascending order) of the original list. (Original list should not be modified). You can not use the built-in sort () or sorted () function.

Here's my solution:

1 def func(i):
2     i_copy = []
3     for elem in i:
4         i_copy.append(elem)
5     for y in range(0, len(i_copy)):
6         for x in i_copy:
7             if x < i_copy[y]:
8                 aux = x
9                 i_copy[y] = x
10                 i_copy = aux
11     return i_copy

It gives the following error:

  

Error in evaluating function: TypeError at line 7   'int' object has no attribute ' getitem '

Does anyone help me solve the problem?

I do not understand why the __getitem__ attribute has to do with the problem or why I need it, and why this particular line is wrong.

    
asked by anonymous 21.02.2016 / 17:34

2 answers

1

getitem is a method that every python object possesses so you can dynamically call methods and collect attributes through a string. Ex.

>> to_upper = "string"
>> to_upper.__getattribute__("upper")()
STRING

The error of your code is when i_copy receives aux, aux is an integer, not a list, so i_copy is no longer a list and turns an integer, so when you try to get the next position of i_copy in if if x < i_copy[y]: , it accuses that it does not have the attribute responsible for the vector item.

Try to do so.

def func(i):
    i_copy = [x for x in i]

    for y in range(len(i)):
        for x in i_copy:
            if x < i[y]:
                i_copy[y] = x
    return i_copy
    
21.02.2016 / 17:59
0

What happens is that the first time your program runs line 10, the i_copy array receives the value of x . However, x is just a number taken from the same array (see line 6). So at the next iteration of the loop in line 6, you try to use i_copy , which now has become a number, as if it were an iterable structure, generating the exception.

All because on line 10 you forgot to reference a specific position in the i_copy array. And anyway the logic of your algorithm seems to be wrong. Here is my version of the same algorithm:

1   def func(i):
2       i_copy = []
3       for elem in i:
4           i_copy.append(elem)
5       for y in range(0, len(i_copy)):
6           for x in range(y + 1, len(i_copy)):
7               if i_copy[x] < i_copy[y]:
8                   aux = i_copy[x]
9                   i_copy[x] = i_copy[y]
10                  i_copy[y] = aux
11      return i_copy

Notice how in line 6 I'm not iterating over each element of the vector, but only about the indexes. And with these indexes I can perform the swapping of the elements when appropriate.

    
21.02.2016 / 17:56