Pass same parameter in Recursive function

D

Davy

Hi all,

Sometimes I need to pass same parameter in recursive function. From my
point of view, the style is redundant, and I don't what to use some
global style like self.A, self.B, Is there any other choice?

For example,

def func(self, x, y, A, B, C):
#x, y change in recursive call
#A, B, C change in the first layer function call, but did not change
in recursive call
if (...):
func(x, y, A, B, C)
else(...):
func(x, y, A, B, C)

Best regards,
Davy
 
C

Chris Rebert

Assuming the function is tail-recursive or the "unchanging" arguments
are immutable, just use a closure:

def func(self, x, y, A, B, C):
def _func(x,y):
return _func(g(A,B,C,x), h(A,B,C,y)) #recurse
return _func(x, y)

I'm unsure as to the performance impact of this though.

- Chris
 
D

Davy

Assuming the function is tail-recursive or the "unchanging" arguments
are immutable, just use a closure:
[SNIP]
Hi Chris,

Thank you :)
Perhaps I should clarify the problem.
1. the function is NOT tail-recursive
2. Yes, the arguments are immutable after I call the function the
first time.

I think the best description of the problem may be:
How to keep some argument constant and accessable in one function
(especially, recursive function). We know that we can use something
like self.parameter to keep the parameter constant and accessable in
one class.
 
D

Diez B. Roggisch

Davy said:
Assuming the function is tail-recursive or the "unchanging" arguments
are immutable, just use a closure:
[SNIP]
Hi Chris,

Thank you :)
Perhaps I should clarify the problem.
1. the function is NOT tail-recursive
2. Yes, the arguments are immutable after I call the function the
first time.

I think the best description of the problem may be:
How to keep some argument constant and accessable in one function
(especially, recursive function). We know that we can use something
like self.parameter to keep the parameter constant and accessable in
one class.


The same way chris showed you - using a closure, you can capture
variables outside, and only pass the changing params.

The tail-recursion property isn't needed for that.

Diez
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,123
Latest member
Layne6498
Top