简体   繁体   中英

Python: Substituting for global variables

I am trying to generate the sigma-algebra of an Ω. I am looking how to replace the global variable. Here Ω=[1,2,3].

global sigma
sigma=[[]]
def buildDTree(sofar, todo):
    global sigma
    sal=[]
    if len(todo)==0:
        return binaryTree(sofar)
    else:
        withelt=buildDTree(sofar + [todo[0]],todo[1:])
        withoutelt=buildDTree(sofar, todo[1:])
        here=binaryTree(sofar)
        here.setLeftBranch(withelt)
        here.setRightBranch(withoutelt)
        sal+=(here.getLeftBranch().getValue())
        sigma+=[sal]
        return here
buildDTree([], [1,2,3])
print sigma

The simplest way would be to add a keyword argument to your recursive function, and returning the resulting sigma:

def buildDTree(sofar, todo, sigma=None):
    if sigma is None:
        sigma = [[]]
    sal = []
    if not todo:
        return sigma, binaryTree(sofar)
    else:
        _, withelt = buildDTree(sofar + [todo[0]], todo[1:], sigma)
        _, withoutelt = buildDTree(sofar, todo[1:], sigma)
        here = binaryTree(sofar)
        here.setLeftBranch(withelt)
        here.setRightBranch(withoutelt)
        sal += here.getLeftBranch().getValue()
        sigma += [sal]
        return sigma, here

sigma, _ = buildDTree([], [1,2,3])

This at least makes sigma 'local' to the recursive call.

A better approach is to make a class:

class DTreeBuilder(object):
    def __init__(self):
        self.sigma = [[]]

    def buildDTree(self, sofar, todo):
        sal = []
        if len(todo) == 0:
            return binaryTree(sofar)
        else:
            withelt = buildDTree(sofar + [todo[0]], todo[1:])
            withoutelt = buildDTree(sofar, todo[1:])
            here = binaryTree(sofar)
            here.setLeftBranch(withelt)
            here.setRightBranch(withoutelt)
            sal += here.getLeftBranch().getValue()
            self.sigma += [sal]
            return here

and use it like:

builder = DTreeBuilder()
builder.build([], [1,2,3])
print builder.sigma

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM