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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With