2015-09-27 55 views
3
def a_function(n, a, b, c): 
    if n == 1: 
     print((a,b)) 
else: 
    a_function(n-1, a, c, b) 
    print((a,b)) 
    a_function(n-1, c, b, a)  

a_function(3, 1, 2, 3) 

如何使函數返回一個元組而不是上面的輸出? ((1,2),(1,3),(2,3),(1,2),(3,1),(3,2),(1,2)的情況下, ))將輸出更改爲元組[python]

+0

請妥善修理壓痕。 – Gogo

回答

3

您可以返回元組的元組,並在遞歸調用返回時保持連接它們。示例 -

def a_function(n, a, b, c): 
    if n == 1: 
     return ((a,b),) 
    else: 
     x = a_function(n-1, a, c, b) 
     return x + ((a,b),) + a_function(n-1, c, b, a) 

演示 -

>>> def a_function(n, a, b, c): 
...  if n == 1: 
...   return ((a,b),) 
...  else: 
...   x = a_function(n-1, a, c, b) 
...   return x + ((a,b),) + a_function(n-1, c, b, a) 
... 
... 
>>> a_function(3, 1, 2, 3) 
((1, 2), (1, 3), (2, 3), (1, 2), (3, 1), (3, 2), (1, 2)) 
1

您可以使用yield

def gx(n, a, b, c): 
    if n == 1: 
     yield a, b 
    else: 
     for sub in gx(n - 1, a, c, b): 
      yield sub 
     yield a, b 
     for sub in gx(n - 1, c, b, a): 
      yield sub 

print tuple(gx(3, 1, 2, 3)) 

((1, 2), (1, 3), (2, 3), (1, 2), (3, 1), (3, 2), (1, 2)) 
1

試圖用另一種方法。

lis=[] 
    def a_function(n, a, b, c): 
     if n == 1: 
      lis.append((a,b)) 
     else: 
      a_function(n-1, a, c, b) 
      lis.append((a,b)) 
      a_function(n-1, c, b, a) 

    a_function(3, 1, 2, 3) 
    print tuple(lis)