Python 函数、返回和公式
我是通过《python的艰难之路》一书开始学习python的,我被困在了任务#21(): 该任务的代码段如下所示:Python 函数、返回和公式,python,Python,我是通过《python的艰难之路》一书开始学习python的,我被困在了任务#21(): 该任务的代码段如下所示: def add(a, b): print "ADDING %d + %d" % (a, b) return a + b def substract(a, b): print "ADDING %d - %d" % (a, b) return a - b def multiple(a, b): print "ADDING %d * %d" %
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
def substract(a, b):
print "ADDING %d - %d" % (a, b)
return a - b
def multiple(a, b):
print "ADDING %d * %d" % (a, b)
return a * b
def divide(a, b):
print "ADDING %d / %d" % (a, b)
return a / b
print "Let's do some math with just functions!"
age = add(20, 6)
height = substract(200, 20)
weight = multiple(40, 2)
iq = divide(190, 2)
print "age: %d, height: %d, weight: %d, iq: %d" % (age, height, weight, iq)
what = add(age,multiple(iq, substract(weight, divide(height,4))))
#this is my current solution
first_step = divide(height,4)
two_step = substract(weight, first_step)
three_step = multiple(iq, two_step)
four_step = add(age, three_step)
print four_step
#end of my current solution
print "That becomes:", what, "Can you do it by hand?"
要获得如下输出:
Let's do some math with just functions!
ADDING 30 + 5
SUBTRACTING 78 - 4
MULTIPLYING 90 * 2
DIVIDING 100 / 2
Age: 35, Height: 74, Weight: 180, IQ: 50
Here is a puzzle.
DIVIDING 50 / 2
MULTIPLYING 180 * 25
SUBTRACTING 74 - 4500
ADDING 35 + -4426
That becomes: -4391 Can you do it by hand?
我的问题:
如何以一种更通俗的方式来解决这个问题呢?这个问题的措辞很糟糕,但以下是我的解释: 假设“减法”实际上是“减法” 实现以下公式:
what = age + iq * (weight - height/4)
要尝试的公式:“24+34/100-1023”
//首先,我错误地解释为:
24 + 34
----------
100 - 1023
必须是这样的:
what = divide(add(24,34), substract(100, 1013))
因此,这是一个理解什么叫做何时的练习。。
(首先调用参数,然后使用参数执行函数)
编辑:那里没有家长
但是,由于运算符的优先级,该问题相当于24+(34/100)-1023
应该是的
what = add(24, substract(divide(34, 100), 1023))
作为函数,按照操作顺序,它看起来是这样的。我首先将每个操作放入一个变量中,以使事情变得更简单
q = divide(34, 100)
s = add(24, quo)
d = subtract(sum, 1023)
接下来,我用变量名替换函数名,得到一个等式:
result = subtract(add(24, divide(32, 100))), 1023)
print result
我希望这对你有用 查看等式的解析树可能会有所帮助。(不要担心解析树的确切定义。) 使用
操作符
模块中的函数(只是为了避免定义我自己的函数),可以将上面每个操作符的左、右子代作为参数传递给相应的函数。例如,由于34和100是上面树中/
的子级,因此调用是div(34100)
从树的顶部开始,可以看到sub
应该包含两个参数,一个加法和1023。因此,从部分答案开始
answer = sub(add(??), 1023)
接下来,加法有参数24和除法。现在你的答案看起来像
answer = sub(add(24, div(??)), 1023)
最后,该司有第34和100条论据
from operator import add, sub, div
answer = sub(add(24, div(34, 100)), 1023)
另一个LPTHW的受害者。我很想帮忙,但我不明白确切的问题是什么。如果问题是
(24+34)/(100-1023)
,你的答案是正确的。但是,由于运算符的优先级,该问题相当于24+(34/100)-1023
,因为除法的优先级高于加法(afaik)。然后,您的解决方案应该是减(add(24,divide(34100)),1023)。
answer = sub(add(24, div(??)), 1023)
from operator import add, sub, div
answer = sub(add(24, div(34, 100)), 1023)