[英]Evaluating a function at a specific point
I am trying to write a Python function called term_output that can evaluate what a single term equals at a value of x . 我正在尝试编写一个称为term_output的Python函数,该函数可以评估x的值等于一个术语。
For example, when x=2
, the term 3x^2 = 3*2^2=12
. 例如,当
x=2
,项3x^2 = 3*2^2=12
。 I've been told to represent 3x^2
in code as (3, 2), and: term_output((3, 2), 2)
should return 12
. 有人告诉我在代码中将
3x^2
表示为(3,2),并且: term_output((3, 2), 2)
应该返回12
。
I am trying to use solely functions (and functions of functions) 我正在尝试仅使用功能(以及功能的功能)
def term(x,y):
return x**y
def term_output(term,z):
return term*z
My end result is (3, 2, 3, 2)
. 我的最终结果是
(3, 2, 3, 2)
。
But I have tried many options and i expect the output to return 12 但是我尝试了很多选项,我希望输出返回12
term
is a pair, not a number, and multiplying any tuple duplicates it. term
是一对,而不是数字,并且将任何元组相乘都会复制它。
>>> (1,2) * 3
(1, 2, 1, 2, 1, 2)
>>> (1,2) * 4
(1, 2, 1, 2, 1, 2, 1, 2)
You need to take apart the pair. 您需要拆开一对。
I think simultaneous assignment is convenient (and it documents the intent better than indexing): 我认为同时分配很方便(它比索引更好地记录了意图):
>>> a = (3,2)
>>> a
(3, 2)
>>> x,y = a
>>> x
3
>>> y
2
Putting it in a function: 把它放在一个函数中:
def term_output(term,z):
coefficent, exponent = term
return coefficient * z ** exponent
Simply as: 简单如下:
x = 2
y = 2
z = 3
xy = [x,y]
def term(xy):
return xy[0]**xy[1]
def term_output(xy,z):
return term(xy)*z
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.