KaziJehangir
KaziJehangir

Reputation: 305

Python if else statement in recursive function getting stuck:

so I'm making a function that takes a string and the number of gaps that i need to insert in it, and i want it to output a list of strings of all possible combinations where those gaps are inserted.

I have written a recursive function for that, but the stopping if condition is not being activated no matter what i do. Even printing the expression in itself gives the proper answer but the if condition doesn't follow that expression.

I hope you guys can help with this, even though it's probably a very simple error on my part, i just cant seem to find it.

Thanks in advance.

f = open("bonusoutput.txt",'w')

sequence1 = raw_input("Sequence 1:")
sequence2 = raw_input("Sequence 2:")

l1 = int(len(sequence1))
l2 = int(len(sequence2))

#---------------Function that has problem-----------------------------

def insertBlanks(numGap,string):
    if (numGap <= 0):
        return [string]
    else:
        outSeq = []

        for cp in range(0,len(string)+1):
            outSeq.append(string[:cp] + "_" + string[cp:])
        for seq in outSeq:
            outSeq += (insertBlanks(numGap-1,seq))

        return outSeq
#-------------------------------------------------------------

nGap1 = l2
nGap2 = l1

outSeq2 = insertBlanks(nGap1,sequence2)
f.write(str(outSeq2))
print outSeq2

Upvotes: 0

Views: 277

Answers (1)

Jason S
Jason S

Reputation: 13779

While looping for seq in outSeq, you are appending items to outSeq. You're returning a list of at least one item each time (base case returns [string] therefore you will add at least 1 item for each item you visit, so you have an infinite loop. Consider adding your output to a new list (or using a list comprehension, like [insertBlanks(numGap - 1, seq) for seq in outSeq]

Upvotes: 1

Related Questions