gpt4 book ai didi

python - 求值允许其运算符为复合表达式的组合

转载 作者:行者123 更新时间:2023-12-01 00:13:37 27 4
gpt4 key购买 nike

我在 sicp 中发现了计划的惊人力量

Exercise 1.4. Observe that our model of evaluation allows for combinations whose operators are compound expressions. Use this observation to describe the behavior of the following procedure:

 #+BEGIN_SRC scheme
(define (a-plus-abs-b a b)
((if (> b 0) + -) a b))
(a-plus-abs-b 9 4)
#+END_SRC

#+RESULTS:
: 13

我尝试模仿它,但不知道如何处理符号运算符

In [13]: 1 eval("+") 1                 
File "<ipython-input-13-74042a5242a6>", line 1
1 eval("+") 1
^
SyntaxError: invalid syntax


In [14]: 1 exec("+") 1
File "<ipython-input-14-deabdb544acb>", line 1
1 exec("+") 1
^
SyntaxError: invalid syntax

有没有像方案那样直接使用符号运算符“+”的解决方案?

最佳答案

在Python中,我们不能直接传递+-,我们需要将它们包装在函数中,因为它们是运算符而不是过程与Scheme中一样,因此解释器需要以不同的方式对待。

但是,我们可以非常简单地将Scheme 代码转换为Python,只需从 operator 导入正确的运算符即可。模块,并像任何普通函数一样调用它们:

from operator import add, sub

def a_plus_abs_b(a, b):
return (add if b > 0 else sub)(a, b)

a_plus_abs_b(9, 4)
=> 13

operator 模块“导出一组与 Python 内部运算符相对应的高效函数”。另一种(效率较低)的替代方案是使用 lambda:

my_add = lambda x, y: x + y
my_sub = lambda x, y: x - y

def a_plus_abs_b(a, b):
return (my_add if b > 0 else my_sub)(a, b)

a_plus_abs_b(9, 4)
=> 13

关于python - 求值允许其运算符为复合表达式的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59465403/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com