0

I am trying to recursively obtain all subsequences for an input string. While I am getting the said subsequences, another element keeps getting added as well. I cannot figure out what is producing this element.

**CODE: **

class Solution:
    
    def subs(self,word,index,cs,arr=[]):
        if(len(word)==index):
            return cs
        else:
                l=word[index]
                arr.append(self.subs(word,index+1,cs,arr))
                arr.append(self.subs(word,index+1,cs+l,arr))
        
        return arr  

    def numMatchingSubseq(self, s: str):
        x=self.subs(s,0,'')
        print(x)
    
x=Solution()
x.numMatchingSubseq('ab')

MY OUTPUT: ['', 'b', [...], 'a', 'ab', [...]]

EXPECTED OUTPUT: ['', 'b', 'a', 'ab']

Swifty
  • 2,630
  • 2
  • 3
  • 21
  • You're appending a list to itself. Python displays recursive lists as `[...]` instead of trying to print an infinitely long string. – Brian61354270 Aug 25 '23 at 15:46
  • See also ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/q/1132941/11082165). `arr` is referencing the same list in every call to `subs`, not a newly constructed list on each invocation. – Brian61354270 Aug 25 '23 at 15:47
  • TL;DR: you likely want to replace `arr=[]` in the parameter list with `arr=None`, and add `if arr is None: arr = []` in the method body. – Brian61354270 Aug 25 '23 at 15:48
  • Got it, thanks a lot! – Khushi Saxena Aug 26 '23 at 07:58
  • Now i get this as output: [['', 'b'], ['a', 'ab']] Can i edit this code to somehow get all subsequences in a single list? @Brian61354270 – Khushi Saxena Aug 26 '23 at 08:07

0 Answers0