将输出更改为元组[python]

时间:2015-09-27 10:28:36

标签: python tuples

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)) )

3 个答案:

答案 0 :(得分: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 :(得分:1)

您可以使用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))

$('input').on('change keyup', function() {
  var fontsize = parseInt($(this).css('font-size'));
  var value = $(this).val();
  var length = value.length;
  $(this).width(fontsize*length))
});

答案 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)