[英]Single Linked List search in Python
我想在鏈接列表中搜索值/字符並返回值/字符在鏈接列表中的次數。 如果我僅使用遞歸而不是尾部遞歸,還會更容易嗎?
class MyList():
__slots__=('head','size')
class Empty():
__slots__=()
class NonEmpty():
__slots__=('data','next')
def mkMyList():
lst = MyList()
lst.head = mkEmpty()
lst.size = 0
return lst
def mkEmpty():
return Empty()
def mkNonEmpty(data,lst):
node = NonEmpty()
node.data = data
node.next = lst
return node
def count(l, value, c = 0):
l = mkMyList()
if l.head != value:
l.head = l.head.next
if l.head == value:
return count(l.head.next, value, c + 1)
if l.size == 0:
return c
當我嘗試對其進行測試時,我得到了:
count(s,'s',c= 0)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
count(s,'s',c= 0)
File "C:\Users\Qasim\Desktop\Linked Lists.py", line 30, in count
l.head = l.head.next
AttributeError: 'Empty' object has no attribute 'next'
\\
我將使用迭代器模式,而不是使用遞歸。 這是解決您的問題的一種方法:
class LinkedList(object):
class Node(object):
__slots__ = ('prev', 'next', 'value')
def __init__(self, prev=None, next=None, value=None):
self.prev = prev
self.next = next
self.value = value
def __init__(self, iterable=[]):
self.head = LinkedList.Node() # dummy node
self.tail = self.head
self.size = 0
for item in iterable:
self.append(item)
def __iter__(self):
current = self.head
while True:
if current.next is not None:
current = current.next
yield current.value
else:
raise StopIteration
def append(self, value):
self.tail.next = LinkedList.Node(prev=self.tail, value=value)
self.tail = self.tail.next
self.size += 1
def pop(self):
if self.size > 0:
value = self.tail.value
self.tail = self.tail.prev
self.tail.next = None
self.size -= 1
return value
else:
raise IndexError('pop from empty list')
def count(self, value):
cumsum = 0
for item in self:
if item == value:
cumsum += 1
return cumsum
通過定義Python特殊方法 __iter__
,可以按以下方式順序訪問LinkedList
的元素:
l = LinkedList([1, 2, 3, 3, 3, 4, 5])
for value in l:
print(value)
然后使所需的方法直接count
即可實施。
跟蹤代碼:
l = mkMyList() # => head = Empty()
if l.head != value: # True since head is Empty()
l.head = l.head.next # Empty does not have a ".next" attribute
這就是Traceback告訴您的。
編輯:還有兩件事:(1)當您的意圖是在函數args中將其傳遞給列表l時,我不確定為什么count甚至調用mkMyList。 (2)我猜您想將size-check if語句放在此函數的頂部:
if l.size == 0:
return c
我看到的問題是, count
列表從未正確初始化。 在mkMyList()
, head
元素設置為和Empty
,沒有next
屬性。 在count()
,僅使用mkMyList()
。 這意味着l.head
是Empty
,並且不可能擁有next
屬性。 為了解決這個問題,我建議使用給定的輸入實例化列表l
。
關於遞歸問題:不,在組成尾遞歸函數和規則遞歸函數方面幾乎沒有什么區別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.