Tuples: index out of range - recursion

Asked

Viewed 148 times

0

I have a problem with index out of range in my tuple. The purpose of the code is to create a recursive function that finds a substring inside a tuple with elements of any kind. Someone could help me with this mistake?

The problem is in the recursive call of when I have a tuple inside another tuple. The program is returning index out of range:

def conta(tupla,string):
    if isinstance(tupla[0], list) or isinstance(tupla[0],tuple):
        return conta(tupla[0],string) + conta(tupla[1:],string)
    if(len(tupla)==1):
        if isinstance(tupla[0],str):
            if tupla[0].find(string)>=0:
                return 1

        return 0

    if not isinstance(tupla[0],str):
        return 0 + conta(tupla[1:],string)

    if tupla[0].find(string)>=0:
        return 1 + conta(tupla[1:],string)
    else:
        return 1 + conta(tupla[1:],string)

tupla1=("foi",)
tupla2=([1,2,3],[['onde',2.3], 'oi',78], ['a', 'b', 'c'])
tupla2=([1,2,3],(('onde',2.3), 'oi',78), ['a', 'b', 'c'])
tupla3=([1,2,3],(('onde', 'noiva',2.3), 'oi',78), ['a', 'b', 'c']) 
tupla4=(('MAO', 'MOA') , 13.8 , 'c' , 6 , [2,3]) 

resultado1=conta(tupla1,"oi")
resultado2=conta(tupla2,"oi")
resultado3=conta(tupla3,"oi")
resultado4=conta(tupla4,"oi")

print("\nRetorna ",resultado1,end='')
print("\nRetorna ",resultado2,end='')
print("\nRetorna ",resultado3,end='')
print("\nRetorna ",resultado4,end='')

1 answer

1


I can’t say exactly what’s wrong, because I just couldn’t understand the logic that you implemented. If you edit the question and comment on your code, it might ease the process.

Anyway, the function seems to have a lot of unnecessary things to do its purpose. An easier and faster way to implement this function would be:

def conta(tupla, string, total = 0):

    if type(tupla) in [list, tuple]:
        for item in tupla:
            total = conta(item, string, total)
    else:
        total += str(tupla).count(string)

    return total

That is, if the element tupla be the type list or tuple, traverse it by updating the value of total for each item of this object. Note that it is recursive, so if the list element is another list, it will work the same. If the element is not a list or tuple, convert it to string and checks the number of occurrences of string in its value, increasing total. In the end, return the value of total.

See working on Ideone.

If you just convert the tupla for string and check the number of occurrences of string in the same will work perfectly too. See a example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.