簡體   English   中英

在 Python class 中用 __iter__ 方法實現遞歸 function

[英]Implementing recursive function with __iter__ method in a Python class

所以我正在解決一個問題,我要創建一個 Python Class 來生成列表的所有排列,我遇到了以下問題:

  1. 我可以使用簡單的遞歸 function 輕松完成此操作,但作為 class 似乎我想使用iter方法。 我的方法調用了一個遞歸的 function (list_all),它幾乎與我的iter相同,這非常令人不安。 如何修改我的遞歸 function 以符合iter的最佳實踐?
  2. 我寫了這段代碼,看到它起作用了,但我覺得我不明白,我試着在測試用例中逐行跟蹤代碼,但對我來說,列表中的第一個元素似乎每個都被凍結了時間。 並且列表的 rest 被洗牌。 相反,output 以意外的順序出現。 我有點不明白!

謝謝!

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:]

只需從__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:]

您的list_all方法已經是一個生成器,因此您可以直接在__iter__中返回它:

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

    def __iter__(self):
        return self.list_all(self.list)

    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:]

這既閱讀起來更清晰,執行速度也更快。

您還可以選擇在__iter__中定義list_all

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

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

時序permutations與我的permutations2給出了幾乎相同的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM