【问题标题】:Obtain a function expression that is product between two other functions expressions获得一个函数表达式,它是两个其他函数表达式之间的乘积
【发布时间】:2016-06-02 22:52:11
【问题描述】:

我有一个计算 x^2 的函数和另一个计算 x^3 的函数。我想通过将其他两个函数相乘得到x**5的表达式。

这是我一直在尝试做的事情:

def pol1(x):
    f=x**2
    return f
def pol2(x):
    f=x**3
    return f
def new(f,g,x):
    n=f*g
    return n

neo=new(pol1, pol2, 2)
print(neo)

【问题讨论】:

  • 我会考虑添加一些标签,以便人们在选择问题时知道他们将要查看的内容。
  • 您不能将函数相乘,但是您可以将两个函数的 result 相乘,我想指出您当前版本的 new 甚至没有使用x 参数,因此应该立即表明您做错了一件事。

标签: python function multiplication


【解决方案1】:

您将 x 传递给新函数,那么为什么不在分配 n 时使用它:

def new(f,g,x):
    n=f(x)*g(x)
    return n

【讨论】:

  • 实际上,我需要函数表达式,以便我可以在另一个函数中使用它,即整合函数表达式。这就是为什么价值不是我想要的。
【解决方案2】:

您的代码只是缺少在new 函数中为fg 传递参数x

def pol1(x):
    f=x**2
    return f
def pol2(x):
    f=x**3
    return f
def new(f,g,x):
    n=f(x)*g(x)
    return n

neo=new(pol1, pol2, 2)
print(neo)

【讨论】:

  • 实际上,我需要函数表达式,以便我可以在另一个函数中使用它,即整合函数表达式。这就是为什么价值不是我想要的。
【解决方案3】:

您正在传递未使用的 x 参数。并且函数对象在python中是不能相乘的。

这是你想要的:

def new(f, g, x):
    n = f(x) * g(x)
    return n

neo = new(pol1, pol2, 2)
print(neo)
# 32

【讨论】:

  • 实际上,我需要函数表达式,以便我可以在另一个函数中使用它,即整合函数表达式。这就是为什么价值不是我想要的。
猜你喜欢
  • 2023-03-31
  • 2021-05-16
  • 2011-04-13
  • 1970-01-01
  • 1970-01-01
  • 2020-08-02
  • 2021-09-05
  • 1970-01-01
  • 2019-10-30
相关资源
最近更新 更多