简体   繁体   中英

Need Help on using map for functions in python

So I have written a function f(a, b). The structure is:

def f(a, b):
    global result

    def g(a, b):
        global result
        return result

    deg h(a):
        return a  # an updated a

    g(a, b)
    a = h(a)
    g(a, b)
    a = h(a)
    g(a, b)
    a = h(a)
    g(a, b)
    return result
  • You can see that I have two sub-functions g(a, b) and h(a) in f(a, b) .
  • I need to run g(a, b) to get the partial result
  • Then I updated the a
  • So that I can run g(a, b) again, to update the result.
  • After 4 runs of g(a, b) , I got the full piece of result and return the value.

There must be a way to structure the process here that looks simpler and clearer.

I also tried:

g(a, b)
g(h(a), b)
g(h(h(a), b)
g(h(h(h(a), b)

And that looks hideous as well.

I need some suggestion to simply to structure here, maybe to use the map() or other high order functions? But I just couldn't figure it out.

Thanks!

First off you should use arguments and return values, and not side effects (ie returning or modifying global variables). I find that the use of global result makes your code unreadable, but I think you are asking about dynamic function composition, which can be expressed like this:

def compose(*fv):
    return reduce(lambda f, g: lambda x: f(g(x)), fv)

And then used like this (note that the evaluation order is right-to-left, which is common):

def add1(x): return x + 1
def mul2(x): return x * 2

>>> compose(add1, add1, add1)(1)
4
>>> compose(mul2, add1, add1, add1)(1)
8

This is common in functional languages, but I find that when you want this pattern in python, you're not making things simple enough.

If what you want to do is something like that:

g(a, b)
a = h(a)
g(a, b)
a = h(a)
g(a, b)
a = h(a)
g(a, b)

You can do:

for i in range(4):
    g(a, b)
    a = h(a)
g(a, b)

a bit more compact

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