Top level of a recursive function
Peter Otten
__peter__ at web.de
Thu Dec 15 03:39:54 EST 2022
On 13/12/2022 15:46, Michael F. Stemper wrote:
> It's easy enough -- in fact necessary -- to handle the bottom
> level of a function differently than the levels above it. What
> about the case where you want to handle something differently
> in the top level than in lower levels? Is there any way to tell
> from within a function that it wasn't invoked by itself?
>
> I've come up with a hack to support different processing, by
> use of an extra argument, as shown in this simplified example:
>
> def fred(cf,toplevel=True):
> x = cf[0]
> if len(cf)>1:
> if toplevel:
> return x + fred(cf[1:],False)
> else:
> return "(" + x + fred(cf[1:],False) + ")"
> else:
> if toplevel:
> return x
> else:
> return "(" + x + ")"
>
> Aside from being ugly, this lets the caller diddle with "toplevel",
> which shouldn't really be externally modifiable.
>
> Are there better ways to do this?
For adepts of functional programming the above is a "fold right"
operation, first hit for "foldr in python":
https://burgaud.com/foldl-foldr-python
With that
>>> from functools import reduce
>>> def foldr(func, items):
return reduce(lambda x, y: func(y, x), items[::-1])
your problem reduces ;) to
>>> foldr("{0}({1})".format, [1,2,3,4])
'1(2(3(4)))'
More information about the Python-list
mailing list