如何在python的递归函数中添加计数器

时间:2019-01-30 08:36:16

标签: python recursion

在整个递归中,计数器x保持为1,而不是递增。

我的代码

def square(l):
    if len(l) > 0:
        x=0
        print("square of element ", x+1 , ": ", l[0] ** 2)
        square(l[1:])


b = (-2,3,11)
square(b)

输出

  

元素1的平方:4

     

元素1的平方:9

     

元素1的平方:121

有没有办法解决这个问题? 预先感谢

3 个答案:

答案 0 :(得分:0)

将功能更改为此:

def square(l, x=0):
   if len(l) > 0:
       print("square of element ", x+1 , ": ", l[0] ** 2)
       x= x+1
       square(l[1:], x)

然后:

b = (-2,3,11)
square(b)

结果将是:

square of element  1 :  4
square of element  2 :  9
square of element  3 :  121

答案 1 :(得分:0)

您的代码中的

x=0定义了一个局部变量;即为函数的每个实例提供一个新变量,当递归调用square时,嵌套的被调用函数将创建自己的x

一种解决方案是使用全局变量:

x = 0

def square(l):
    if len(l) > 0:
        global x
        x = x+1
        print("square of element ", x , ": ", l[0] ** 2)
        square(l[1:])

答案 2 :(得分:0)

每次调用函数x时,x=0下的该行if都设置为零。您需要更改代码。您可以按照以下过程进行操作:

x = 0
def square(l):
    global x
    if len(l) > 0:
        x += 1
        print("square of element ", x, ": ", l[0] ** 2)
        square(l[1:])
b = (-2, 3, 11)
square(b)
  

元素1的平方:4

     

元素2的平方:9

     

元素3的平方:121

相关问题