Search code examples
pythonpython-3.xrecursionglobal-variables

Passing the value of variables inside Python function under recursion


image

I want to enumerate the binary series generated with the code below (just copy-paste to see what I'm trying to do), I used Global var but still cannot find the way to pass the value of counters (nn,nx,ny). Please don't mind how to make the same series in a better way, I just want to know how to pass the value of the counters thru these recursions in order to enumerate the output as in the image at the head of this post. Thanks.

def ConcatenateString(saccum,nn):
    if len(saccum)<4:
        biset=[1,0]
        for a in biset:
            if a==1:
                prevstring = saccum
                newsaccum = saccum+str(a)
                nx=nn+1
                print(nx,newsaccum)
                ConcatenateString(newsaccum,nx)
            else:
                newsaccum = prevstring+str(a)
                ny=nx+1
                print(ny,newsaccum)
                ConcatenateString(newsaccum,ny)
        nn=ny
        return (nn)

##MAIN
newstring=str("")
nc=0
ConcatenateString(newstring,nc)

Solution

  • You should send nn to function and get it back to continue counting

    nn = ConcatenateString(newsaccum, nn)
    

    def ConcatenateString(saccum,nn):
        if len(saccum)<4:
            biset=[1,0]
            for a in biset:
                if a==1:
                    prevstring = saccum
                    newsaccum = saccum+str(a)
                    nn += 1
                    print(nn, newsaccum)
                    nn = ConcatenateString(newsaccum, nn)
                else:
                    newsaccum = prevstring+str(a)
                    nn += 1
                    print(nn,newsaccum)
                    nn = ConcatenateString(newsaccum, nn)
        return nn
    
    ConcatenateString("", 0)
    

    EDIT: Reduced version.

    def ConcatenateString(saccum,nn):
        if len(saccum)<4:
            biset=[1,0]
            for a in biset:
                if a == 1:
                    prevstring = saccum
                    newsaccum = saccum + str(a)
                else:
                    newsaccum = prevstring + str(a)
                nn += 1
                print(nn, newsaccum)
                nn = ConcatenateString(newsaccum, nn)
        return nn
    
    ConcatenateString("", 0)