gpt4 book ai didi

python - 类型错误 : Can't convert 'node' object to str implicitly

转载 作者:太空宇宙 更新时间:2023-11-03 11:00:59 25 4
gpt4 key购买 nike

对于下面的代码——

Reg_Stack = ['R5', 'R4', 'R3', 'R2', 'R1', 'R0']
Temp_Stack = ['T5', 'T4', 'T3', 'T2', 'T1', 'T0']
operator_precedence = {'(' : 0, ')' : 0, '+' : 1, '-' : 1, '*' : 2, '/' : 2}

def gen_code(n):
if(n.left == None and n.right == None):
print("MOV " + n.value + "," + Reg_Stack[-1])
else:
if(n.right.label == 0):
gen_code(n.left)
print(operator(n.value) + " " + n.right.value + "," + Reg_Stack[-1])

elif((n.left.label < n.right.label) and (n.left.label < len(Reg_Stack))):
swap()
gen_code(n.left)
R = Reg_Stack.pop()
gen_code(n.left)
print(operator(n.value) + " " + n.left.value + "," + Reg_Stack[-1])
Reg_Stack.append(R)
swap()

elif((n.right.label < n.left.label) and (n.right.label < len(Reg_Stack))):
gen_code(n.left)
R = Reg_Stack.pop()
gen_code(n.right)
print(operator(n.value) + " " + n.right.value + "," + Reg_Stack[-1])
Reg_Stack.append(R)

else:
gen_code(n.right)
T = Temp_Stack.pop()
print("MOV " + Reg_Stack[-1] + "," + T)
gen_code(n.left)
Temp_Stack.append(T)
print(operator(n.value) + " " + T + "," + Reg_Stack[-1])

def operator(v):
if(v == "+"):
return "ADD"
if(v == "-"):
return "SUB"
if(v == "*"):
return "MUL"

def swap():
a1 = Reg_Stack.pop()
b1 = Temp_Stack.pop()
Reg_Stack.append(b)
Temp_Stack.append(a)

class node(object):
def __init__(self, value='', lvalue=0, node1 = None, node2 = None):
self.value = value
self.left = node1
self.right = node2
self.label = lvalue


a = node('a', 1)
b = node('b', 1)
c = node('c', 1)
d = node('d', 0)

q1 = node('*', 1, c, d)
q2 = node('-', 2, b, q1)
root = node('+', 0, a, q2)
gen_code(root)

我遇到了错误-

C:\Python33>python main.py
Traceback (most recent call last):
File "main.py", line 67, in <module>
gen_code(root)
File "main.py", line 15, in gen_code
gen_code(n.left)
File "main.py", line 7, in gen_code
print("MOV " + n.value + "," + Reg_Stack[-1])
TypeError: Can't convert 'node' object to str implicitly

gen_code() 函数的输入是一棵带标签的树。我尝试过不同的树并且代码有效。但只有在这种情况下,我才会收到上述错误。我做错了什么?

最佳答案

这个问题主要是因为你的 swap() 函数 -

def swap():
a1 = Reg_Stack.pop()
b1 = Temp_Stack.pop()
Reg_Stack.append(b)
Temp_Stack.append(a)

您正在从 Reg_StackTemp_Stack 中删除 strings,然后将 node 附加到它。所以当你这样做之后 -

Reg_Stack[-1]

您从 swap() 函数中取回您附加的 node 对象。这会导致您在尝试将其添加(连接)到 str 时看到的错误。

您应该添加节点的值,而不是节点本身。示例-

def swap():
a1 = Reg_Stack.pop()
b1 = Temp_Stack.pop()
Reg_Stack.append(b.value)
Temp_Stack.append(a.value)

在这个改变之后我得到的结果是 -

MOV a,b
MOV a,R1
ADD a,R1

但不确定其他逻辑是否正确。

关于python - 类型错误 : Can't convert 'node' object to str implicitly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32499598/

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