const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.on("line", (line) => { const arr = [...line]; console.log(lisp(arr)); }); function lisp(arr) { const stack = []; const opers = []; for (let i = 0; i < arr.length; i++) { if (arr[i] === ")") { const fragment = stack.splice(opers.pop()); fragment.shift(); // 把截取出来的片段的头部"("去掉 const [op, p1, p2] = fragment.join("").split(" "); const res = operate(op, p1 - 0, p2 - 0); if (res === "error") return "error"; stack.push(...String(res)); } else { if (arr[i] === "(") opers.push(stack.length) stack.push(arr[i]); } } return stack.join(""); } function operate(op, p1, p2) { switch (op) { case "add": return p1 + p2; case "sub": return p1 - p2; case "mul": return p1 * p2; case "div": return p2 === 0 ? "error" : Math.floor(p1 / p2); } } 转换为PYTTHON语言
时间: 2024-04-16 12:28:05 浏览: 184
在Python中,你可以使用以下代码将给定的JavaScript代码转换为Python代码:
```python
def lisp(arr):
stack = []
opers = []
i = 0
while i < len(arr):
if arr[i] == ")":
fragment = stack[opers.pop():]
fragment.pop(0) # 把截取出来的片段的头部"("去掉
op, p1, p2 = "".join(fragment).split(" ")
res = operate(op, int(p1), int(p2))
if res == "error":
return "error"
stack.extend(str(res))
else:
if arr[i] == "(":
opers.append(len(stack))
stack.append(arr[i])
i += 1
return "".join(stack)
def operate(op, p1, p2):
if op == "add":
return p1 + p2
elif op == "sub":
return p1 - p2
elif op == "mul":
return p1 * p2
elif op == "div":
return "error" if p2 == 0 else p1 // p2
line = input()
arr = list(line)
print(lisp(arr))
```
这是将给定的JavaScript代码转换为等效的Python代码的过程。请注意,这只是一个简单的转换,可能需要根据实际情况进行修改和优化。
阅读全文