lambda 関数を用いて、以下のような処理をしたいと考えています。
実現したい処理
- 文字列 s を解析して、対応する無名関数を返す関数
calc(s)
を定義して実行 - 文字列
x+3
を受け取りf=calc("x+3")
とする(入力はx+[1桁の整数]
or[1桁の整数]+x
の形式(+
の部分には+, -, *, /
のいずれかが入る)とする) f(1)
の値を実際に計算してみる
やったこと
次のようなコードを書いたのですが、 TypeError: unsupported operand type(s) for +: 'function' and 'int'
となってしまい、 lambda
と int
の計算は型が合わないためできないとなってしまいます。
原因は分かっているのですが、このような処理を実行するために適切なコードの書き方が分かりません。教えていただけると助かります。
python
1def calculator(x, op, y): 2 if op == "+": 3 return x + y 4 elif op == "-": 5 return x - y 6 elif op == "*": 7 return x * y 8 else: 9 return x // y 10 11def read_char(c): 12 if c == "x": 13 return lambda x: x 14 else: 15 return int(c) 16 17def calc(s): 18 lf = read_char(s[0]) 19 op = s[1] 20 rf = read_char(s[2]) 21 def func(x): 22 return calculator(lf, op, rf) 23 return func
実行結果
>>> f = calc("x+3") >>> f(1) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () ----> 1 f(1) in func(x) 20 rf = read_char(s[2]) 21 def func(x): ---> 22 return calculator(lf, op, rf) 23 return func in calculator(x, op, y) 1 def calculator(x, op, y): 2 if op == "+": ----> 3 return x + y 4 elif op == "-": 5 return x - y TypeError: unsupported operand type(s) for +: 'function' and 'int'
回答3件
あなたの回答
tips
プレビュー