【问题标题】:Reverse method for recursively defined list class递归定义列表类的反向方法
【发布时间】:2012-04-21 22:53:04
【问题描述】:

我一直在研究 Python 中递归定义的列表类,我在编写 reverse() 方法以递归运行时遇到问题。这是课程的基础。

class RecList:
  def __init__(self):
    self._head = None
    self._rest = None

基本情况是 self._head,它是列表中的第一个条目,然后是递归情况,它本质上是另一个列表,其中包含要启动的自己的 self._head,然后递归定义。这一直持续到self._headself._rest = None 的底层。有没有一种简单的方法可以为这样定义的列表编写反向方法?

【问题讨论】:

  • 请发布您的类的使用示例,包括 RecList 的构造和创建实例的“打印”。
  • 为什么不简单地使用 collections.deque?它以链表的形式实现,并用 C 编码,因此比任何纯 Python 解决方案都要快。
  • 我有点犹豫要不要实际发布源代码。严格来说,这不是我的,这是学校的作业。我真的很不想把整个来源都拿出来让教授找到它。

标签: python list recursion reverse


【解决方案1】:

试试这个:

class RecList:
  def __init__(self, head=None, rest=None):
    self._head = head
    self._rest = rest
  def __str__(self):
    if self._rest is None:
        return str(self._head)
    return str(self._head) + ' ' + self._rest.__str__()
  def reverse(self):
    return self._reverse_aux(None)
  def _reverse_aux(self, acc):
    if self._rest is None:
        return RecList(self._head, acc)
    return self._rest._reverse_aux(RecList(self._head, acc))

lst = RecList(1, RecList(2, RecList(3, None)))
print lst
> 1 2 3
print lst.reverse()
> 3 2 1

【讨论】:

  • 非常感谢,这让我知道了如何解决这个问题。
【解决方案2】:
class RecList:
  def __init__(self, head, tail):
    self.head = head
    self.tail = tail

def foldr(f, acc, xs):
    head = xs.head
    tail = xs.tail

    if tail:
        return foldr(f, f(head, acc), tail)
    else:
        return f(head, acc)

testList = RecList(1, RecList(2, RecList(3, None)))
test = foldr(lambda x, a: RecList(x, a), RecList(None, None), testList)

print test.head
print test.tail.head

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    • 2013-03-04
    • 1970-01-01
    相关资源
    最近更新 更多