0

I have a recursive function that generates subwords of a word


def subWords(word, arr=[]):
        if word=="":
            return arr
        currWord="#"
        if not arr:
            currWord = ""
        for i in word:
            currWord+=i
            arr.append(currWord)
        return subWords(word[1:], arr)

When I call it one time with the word "nothuman" it prints out:

print(subWords("woman"))

the output is :

['w', 'wo', 'wom', 'woma', 'woman', '#o', '#om', '#oma', '#oman', '#m', '#ma', '#man', '#a', '#an', '#n']

But when I use anopther call befoire it:

print(subWords("man"))
print(subWords("woman"))

the outputs are respectively:

['m', 'ma', 'man', '#a', '#an', '#n']
['m', 'ma', 'man', '#a', '#an', '#n', '#w', '#wo', '#wom', '#woma', '#woman', '#o', '#om', '#oma', '#oman', '#m', '#ma', '#man', '#a', '#an', '#n']

Why does this happen?

  • in short, do `arr=None` in function argument, and add a condition in function where if `if arr is None: arr = []` – sahasrara62 Dec 06 '22 at 10:48

0 Answers0