【问题标题】:Implementing recursive function with __iter__ method in a Python class在 Python 类中使用 __iter__ 方法实现递归函数
【发布时间】:2014-12-27 11:14:28
【问题描述】:

所以我正在解决一个问题,我要创建一个 Python 类来生成列表的所有排列,我遇到了以下问题:

  1. 我可以使用简单的递归函数轻松完成此操作,但作为一个类,我似乎想使用 iter 方法。我的方法调用了一个与我的iter 几乎相同的递归函数(list_all),这非常令人不安。如何修改我的递归函数以符合 iter 的最佳做法?
  2. 我写了这段代码,看到它有效,我感觉我没看懂!我尝试在测试用例中逐行跟踪代码,但在我看来,列表中的第一个元素每次都被冻结,而列表的其余部分则被打乱。相反,输出以意想不到的顺序出现。我有些不明白!

谢谢!

class permutations():
  def __init__(self, ls):
    self.list = ls

  def __iter__(self):
    ls = self.list
    length = len(ls)
    if length <= 1:
      yield ls
    else:
      for p in self.list_all(ls[1:]):
        for x in range(length):
          yield p[:x] + ls[0:1] + p[x:]  

  def list_all(self, ls):
    length = len(ls)
    if length <= 1:
      yield ls
    else:
      for p in self.list_all(ls[1:]):
        for x in range(length):
          yield p[:x] + ls[0:1] + p[x:]

【问题讨论】:

  • 如果你的函数运行良好,你为什么要把它挤进一个类?如果要延迟生成排列,只需在函数中使用yield
  • 我同意这一点。问题中特别说明了类这个词,所以我试图考虑如何使它成为一个与 iter 方法接口的可迭代类。

标签: python recursion iteration generator


【解决方案1】:

只需从__iter__ 拨打self.list_all

class permutations():
  def __init__(self, ls):
    self.list = ls

  def __iter__(self):
    for item in self.list_all(self.list):
      yield item

  def list_all(self, ls):
    length = len(ls)
    if length <= 1:
      yield ls
    else:
      for p in self.list_all(ls[1:]):
        for x in range(length):
          yield p[:x] + ls[0:1] + p[x:]

【讨论】:

  • 这是学习过程中苦乐参半的时刻之一。很高兴我能得到想要的结果。很生气我没有早点建立这种联系。谢谢!
猜你喜欢
  • 2015-07-03
  • 1970-01-01
  • 1970-01-01
  • 2017-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多