簡體   English   中英

沒有循環或迭代工具的遞歸排列

[英]Recursive permutation without loops or itertools

搜索了整個 web 的解決方案,找不到任何東西。
需要一些幫助來找出算法,通過重復獲得所有排列。
我不允許使用循環或任何其他幫助程序庫。

def func(num):
    # The solution 

num ,表示每個節點長度的個數。

例如,如果num=1 ,解決方案將是['a', 'b', 'c']
或者如果num=2 ,則['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']

謝謝

您可以使用遞歸生成器 function:

vals = ['a', 'b', 'c']
def combos(d, n, c = ''):
   if len(c) == n:
       yield c
   else:
       def _range(x=0):
          if x < len(d):
              yield from combos(d, n, c=c+d[x])
              yield from _range(x+1)
       yield from _range()

print([*combos(vals, 2)])

Output:

['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']

我們可以編寫接受任何可迭代tcombinations來計算任何 integer 大小n - 的固定長度組合

def combinations(t, n):
  if n <= 0:
    yield ()
  elif not t:
    return
  else:
    for x in combinations(t, n - 1):
      yield (t[0], *x)
    yield from combinations(t[1:], n)

任何可迭代對象都可以用作輸入。 在這種情況下,組合將"abc"等同於["a", "b", "c"] -

for x in combinations("abc", 2):
  print(x)
('a', 'a')
('a', 'b')
('a', 'c')
('b', 'b')
('b', 'c')
('c', 'c')

它適用於n的所有正 integer 值 -

for x in combinations("abc", 1):
  print(x)
('a',)
('b',)
('c',)

n = 0n < 0 -

for x in combinations("abc", 0):
  print(x)
()

使用元組作為累加器, combinations不僅限於基於字符串的組合。 如果需要,調用者可以輕松地加入元組以創建兩個字符的字符串 -

for x in combinations("abc", 2):
  print("".join(x))
aa
ab
ac
bb
bc
cc

請試試這個(你可以更改 len(輸入)的數字 3。我不知道如何計算列表中的元素 - 我沒有 python 來測試它。對不起。

輸入 = ['a','b','c']

元素=3

Output = []

定義樂趣(t):

    Global input

    Global output

    If t==1:

       Output=input

       Print(input)

    If t>1:

       Func1(0,0)

       Input=output

       Fun(t-1)

定義函數1(x,y):

   Global input

   Global output

   If y+1<Elements+1:

      Output.append(input[x]+input[y])

      Func1(x,y+1)

   If y+1>Elements and x+1<Elements:

      Func(x+1,0)

   Return input[x]

好玩(2)

暫無
暫無

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

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