-1

我的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'

预期输出:

2
2

我的代码:

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,'-')
4

1 回答 1

2

换行:

if head.value is None:

if head.next is None:

该行的目的是知道列表何时应该停止,此时下一个节点将是None. 存储在节点中的值与此无关:最后一个节点仍然有一个值(相反,您可能希望将值存储None在列表的前面)。


作为一个单独的问题,您的函数将始终返回 0。该行countInt(head.next, n, count)实际上对变量没有任何作用count:Python 按值传递整数,因此您传递的变量不会递增。即使你解决了这个问题,你总是检查的事实head.next意味着你正在跳过列表中的第一个元素。您应该将您的功能设置为:

def countInt(head, n):
    count = 0
    if head.value == n:
        count = 1
    if head.next is None:
        return count
    return count + countInt(head.next, n)

这实际上可以让您摆脱count通过列表向下传递(这是实现递归的一种尴尬方式)。

于 2013-10-11T05:05:44.987 回答