2015-04-23 49 views
3

我嘗試過在Python的功能來定義的乘法,僞代碼是這樣的:在Python中定義函數的乘法?

這將返回以x的函數,因爲F(X),G(X)

multiply_two_functions((f(x), g(x)) = f(x) * g(x) 

我可以爲此在Haskell像這樣:

mult :: (Num b) => (a -> b) -> (a -> b) -> (a -> b) 
mult f g = h 
    where h x = (f x) * (g x) 

你可能會問,爲什麼我會想這樣做 - 我的功能[F]的清單,我想減少這些用乘法。同樣,在Haskell:

reduce_mult list = foldl mult 1 list 

編輯:我如何使用它的蟒蛇,出於完整性:

def prod_reduce(f_list): 
    def identity(x): 
     return 1 
    def f_mult(f, g): 
     def multiplied(x): 
      return f(x) * g(x) 
     return multiplied 
    prod = identity 
    for f in f_list: 
     prod = f_mult(prod, f) 
    return prod 

沒有人有Python實現任何提示?

+0

如果您使用可調用的類(即實現['__call__'](https://docs.python.org/2/reference/data model.html#object .__ call__))而不是常規函數,您可以定義所需的任何乘法行爲(請參閱https://docs.python.org/2/reference/datamodel.html#emulating-numeric-types)。或者你問如何編寫'multiply_two_functions'函數?你能舉一個例子說明你如何在Python中使用它,對於我們這些不熟悉[tag:haskell]的人? – jonrsharpe

+0

@jonrsharpe我用我如何使用它的例子編輯了OP。 – Leon

回答

6

只寫返回,返回的其他功能的結果的產品新功能的功能:

def multiply_funcs(f, g): 
    def multiplied(x): 
     return f(x) * g(x) 
    return multiplied 
+0

非常感謝 - 非常完美。 – Leon

+1

@Leon請注意,這隻適用於採用單個參數的函數 – jonrsharpe

+0

我發現您的答案也是正確的(當然),但比我需要的要普遍得多。感謝您的回覆。 – Leon

5

你可以在Python中做幾乎相同的事情:返回一個乘以這兩個函數的lambda。

def multiply_two_functions(f, g): 
    return lambda x: f(x) * g(x) 

測試:

def a(x): 
    return 2 * x 

aa = multiply_two_functions(a, a) 
print(aa(0), aa(1), aa(2)) 

輸出:

(0, 4, 16) 
+0

感謝 - 明確的迴應(我不敢相信我沒有看到,但從來沒有真正想過在Python中返回匿名函數) – Leon

6

如果你問如何實現一個函數來創建一個新的函數倍數從目標函數的結果,它看起來是這樣的:

def multiply_two_functions(f, g): 
    """Return a new function for e.g. h(x) == f(x) * g(x).""" 
    def h(*args, **kwargs): 
     return f(*args, **kwargs) * g(*args, **kwargs) 
    return h 

注意使用*args, **kwargs處理任何位置和關鍵字參數(見例如What does ** (double star) and * (star) do for parameters?);唯一的限制是任何一對fg必須能夠處理將傳遞給h的相同參數。在使用中:

>>> def f(x): 
    return x + 1 

>>> def g(x): 
    return 2 * x 

>>> h = multiply_two_functions(f, g) 
>>> h(5) 
60 

如果你想真正讓h = f * g工作,你就必須實現與__call____mul__類:

class Func(object): 

    def __init__(self, func): 
     self.func = func 

    def __call__(self, *args, **kwargs): 
     return self.func(*args, **kwargs) 

    def __mul__(self, other): 
     def new_func(*args, **kwargs): 
      return self(*args, **kwargs) * other(*args, **kwargs) 
     return Func(new_func) 

這可以使用如下:

>>> f = Func(lambda x: x + 1) 
>>> g = Func(lambda x: 2 * x) 
>>> h = f * g 
>>> h(5) 
60