我的countInt
函数有问题。此外,它被标记为countINT,我在其中放入'-'
作为参数。我测试了我的链接列表的创建,它似乎工作正常。所以我觉得我可以安全地排除这个问题。但是,对于NoneType对象没有属性值错误,我不确定哪里出错了。有人能帮我找出错误并指导我改正错误吗?非常感谢您!在
输出:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "linked_list.py", line 63, in <module>
print countInt(r,1)
File "linked_list.py", line 25, in countInt
countInt(head.next,n)
File "linked_list.py", line 25, in countInt
countInt(head.next,n)
File "linked_list.py", line 25, in countInt
countInt(head.next,n)
File "linked_list.py", line 25, in countInt
countInt(head.next,n)
File "linked_list.py", line 25, in countInt
countInt(head.next,n)
File "linked_list.py", line 25, in countInt
countInt(head.next,n)
File "linked_list.py", line 25, in countInt
countInt(head.next,n)
File "linked_list.py", line 25, in countInt
countInt(head.next,n)
File "linked_list.py", line 25, in countInt
countInt(head.next,n)
File "linked_list.py", line 25, in countInt
countInt(head.next,n)
File "linked_list.py", line 25, in countInt
countInt(head.next,n)
File "linked_list.py", line 25, in countInt
countInt(head.next,n)
File "linked_list.py", line 23, in countInt
if head.next.value == n:
AttributeError: 'NoneType' object has no attribute 'value'
预期产量:
^{pr2}$我的代码:
class Node:
def __init__(self,value):
self.next = None
self.value = value
def createLinkedList(root, node):
if root.next is None:
root.next = node
else:
createLinkedList(root.next, node)
def countInt(head, n, count= 0): #create a dictionary with keys as the values of the linked list and count up if the value occurs again
count = 0
if head.value is None:
return None
else:
if head.next.value == n:
count += 1
countInt(head.next, n, count)
return count
# root
r = Node(1)
# nodes
a = Node(4)
b = Node(1)
c = Node(5)
d = Node('-')
e = Node(4)
f = Node(1)
g = Node(2)
h = Node('-')
i = Node(8)
j = Node(9)
k = Node(8)
l = Node(3)
createLinkedList(r,a)
createLinkedList(r,b)
createLinkedList(r,c)
createLinkedList(r,d)
createLinkedList(r,e)
createLinkedList(r,f)
createLinkedList(r,g)
createLinkedList(r,h)
createLinkedList(r,i)
createLinkedList(r,j)
createLinkedList(r,k)
createLinkedList(r,l)
print countInt(r,1)
print countInt(r,'-')
换行:
到
^{pr2}$该行的目的是知道列表何时应该停止,此时下一个节点将是
None
。存储在节点中的值与此无关:最后一个节点仍然有一个值(相反,您可能希望将值None
存储在列表的前面)。在作为一个单独的问题,您的函数将始终返回0。行
countInt(head.next, n, count)
实际上并没有对变量count
执行任何操作:Python按值传递整数,因此传递的变量不会递增。即使您修复了这个问题,您总是检查head.next
这一事实意味着您将跳过列表中的第一个元素。您应该将函数设置为:这实际上让您摆脱了在列表中向下传递
count
(这是实现递归的一种笨拙方法)。在相关问题 更多 >
编程相关推荐