Tuples: index out of range - recursion

0

I'm having 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 within a tuple with elements of any type. Could someone help me with this error?

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='')
    
asked by anonymous 06.09.2017 / 02:59

1 answer

1

I will not be able to say exactly what is wrong, because I just can not understand the logic you have implemented. If you edit the question and comment on your code, it may make the process easier.

In any case, the function seems to have much unnecessary 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 tupla element is of type list or tuple , scroll 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 check the number of occurrences of string in its value, increasing total . At the end, return the value of total .

  

See working at Ideone .

If you just convert the tupla to string and check the number of occurrences of string in it will work perfectly as well. See example .

    
06.09.2017 / 13:12