'int' object is not subscriptable error in recursion

Viewed 47

I'm trying to make a recursive function where it takes all odd numbers in a list, order them in an ascending way, and then comes the even numbers but descending.

For example:

lst = [1, 2, 3, 4, 6, 11, 13, 14, 15, 17, 18] would return [1, 3, 11, 13, 15, 17, 18, 14, 6, 4, 2]

This is my code:

def REC_fun(lst):
    lst2 , lst3 = [] , []
    
    if len(lst) == 1:
        return lst[0]
    temp = REC_fun(lst[1:])
    if temp[0]%2 == 1:
        lst2 += [temp[0]]
    else:
        lst3 += [temp[0]]
    return lst2 + lst3[::-1]

ls = [1, 2, 3, 6, 11, 13, 14, 15, 17, 18]
REC_fun(ls)

The problem is probably with temp, I want to check each time if the first number of the list is even or odd and add it accordingly to the empty lists (lst2 and lst3), but I don't know how.. I keep getting this error

~\AppData\Local\Temp/ipykernel_16808/3849482424.py in REC_fun(lst)
      7     if len(lst) == 1:
      8         return lst[0]
----> 9     temp = make_pyramid(lst[1:])
     10     if temp[0]%2 == 1:
     11         lst2 += [temp[0]]

~\AppData\Local\Temp/ipykernel_16808/3849482424.py in REC_fun(lst)
      8         return lst[0]
      9     temp = make_pyramid(lst[1:])
---> 10     if temp[0]%2 == 1:
     11         lst2 += [temp[0]]
     12     else:

TypeError: 'int' object is not subscriptable

EDIT -

I changed the first return from return lst[0] to return lst and the output is now [18].

1 Answers

Here is your Answer:

lst2, lst3 = [],[]
def REC_fun(lst):
 global lst2 ,lst3
 if lst[0]%2 == 1:
    lst2 += [lst[0]]
 else:
    lst3 += [lst[0]]

 if len(lst) == 1:
    return lst
 lst = REC_fun(lst[1:])

 return lst2 + lst3[::-1]
ls = [1, 2, 3, 4, 6, 11, 13, 14, 15, 17, 18]
print(REC_fun(ls))
Related