这个类代表树中的一个节点。我已经链接它的实例来生成一棵如下所示的树:
class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = None
self.right = None
# Chaining the nodes to represent a tree
root = Node(1)
child1 = Node(2, Node(4), Node(5))
child2 = Node(3)
root.left = child1
root.right = child2
Run Code Online (Sandbox Code Playgroud)
这也可以通过使用字典来表示为图形:
tree = {1: [2, 3], 2: [4, 5], 3: [], 4: [], 5: []}
Run Code Online (Sandbox Code Playgroud)
我假设列表中的第一个元素是左节点,第二个元素是右节点。
然而,我遇到的所有博客和书籍都使用树类和图字典。我只是想知道其中的原因。
对此有一些困惑.考虑一下这段代码.
>>> g=[[10]*3]*3
>>> f=[[10,10,10]]*3
>>> id(g)==id(f)
False
>>> id(g[0][0])==id(f[0][0])
True
Run Code Online (Sandbox Code Playgroud)
另外,请考虑这段代码.
>>> g=[['Aamir']*3]*3
>>> f=[['Aamir','Aamir','Aamir']]*3
>>> id(g)==id(f)
False
>>> id(g[0][0])==id(f[0][0])
True
Run Code Online (Sandbox Code Playgroud)
如果f和g是不同的对象,那么如何才能自己内心的元素指向同一个内存位置?
这是一个小程序,可用作算术计算器.我在这里读过以前的问题,但仍有疑问.在我的代码中,我在while循环中使用了'is'而不是==,但我的循环并没有停止.这有点出乎意料,因为如果用户在被要求输入时按'n',则变量ask将被新对象分配.如果有人可以查看代码并提供帮助,我将不胜感激.
def Add(x,y):
add = x+y
print("Answer:",add)
def Sub(x,y):
sub = x-y
print("Answer:",sub)
def Mult(x,y):
product = float(x*y)
print("Answer:",product)
def Div(x,y):
if y!=0:
div=float(x/y)
print("Answer:",div)
else:
print("Invalid input!")
ask='y'
while(ask is 'y' or 'Y'):
x=float(input("\nEnter x:"))
y=float(input("Enter y:"))
print("\nCALCULATOR:")
print("\nPlease select any of the following options:")
print("1.Add")
print("2.Subtract")
print("3.Multiplication")
print("4.Division")
opt=int(input("\nYour option:"))
if(opt is 1):
Add(x,y)
elif(opt is 2):
Sub(x,y)
elif(opt is 3):
Mult(x,y)
elif(opt is 4):
Div(x,y)
else:
print("Invalid option!")
ask=input("\nDo you want to continue?(y/n or Y/N)")
Run Code Online (Sandbox Code Playgroud)