2016-09-07 65 views
1

在理解字符串排列及其在python中的实现(关于this post)时,我偶然发现了使用range()for循环中的某些内容,我只是不明白。Python - 范围()在递归时变异变量值吗?

看看下面的代码:

def recursion(step=0): 
    print "Step I: {}".format(step) 
    for i in range(step, 2): 
     print "Step II: {}".format(step) 
     print "Value i: {}".format(i) 

     print "Call recursion" 
     print "\n-----------------\n" 

     recursion(step + 1) 

recursion() 

这让下面的输出:

[email protected]:~# python range_test.py 

Step I: 0 
Step II: 0 
Value i: 0 
Call recursion 

----------------- 

Step I: 1 
Step II: 1 
Value i: 1 
Call recursion 

----------------- 

Step I: 2 
Step II: 0 <---- WHAT THE HECK? 
Value i: 1 
Call recursion 

----------------- 

Step I: 1 
Step II: 1 
Value i: 1 
Call recursion 

----------------- 

Step I: 2 
[email protected]:~# 

正如你可以看到变量step使用range()一定for循环运行后得到一个新值 - 见标记WHAT THE HECK

任何想法来解除雾?

+3

'range(2,2)'为空。它不会进入'for'循环。因此,它会打印“Step I:2”,然后返回,带有'range(1,2)'的前一个函数然后也完成了它的1次迭代,然后您又回到'step'为0的位置。 –

+0

[ 'itertools.permutations'](https://docs.python.org/2/library/itertools.html#itertools.permutations) – GingerPlusPlus

回答

1

您的结论是不正确step值不会通过使用range更改。 这可以被验证为:

def no_recursion(step=0): 
    print "Step I: {}".format(step) 
    for i in range(step, 2): 
     print "Step II: {}".format(step) 
     print "Value i: {}".format(i) 

no_recursion(step=2) 

产生的输出:

Step I: 2 

它自range(2,2)返回[]预期。

step其值改变为0来,因为函数recursion(称为与step=2)返回它打印Step I: 2后,则控制返回到功能recursion(称为与step=1),它立即返回自for loop已经终止的错觉,然后控制返回到recursion(调用step=0)继续,因为它有1次迭代,并且打印Step II: 0到控制台,这并不意外。这可以是简单的,如果我们修改代码一点点(加入函数入口和出口记录)来观察和观察输出:

def recursion(step=0): 
    print "recursion called with [step = {}]".format(step) # add entry logging 
    print "Step I: {}".format(step) 
    for i in range(step, 2): 
     print "Step II: {}".format(step) 
     print "Value i: {}".format(i) 

     print "Call recursion" 
     print "\n-----------------\n" 

     recursion(step + 1) 
    print "--> returned recursion [step = {}]".format(step) # add exit logging 

recursion() 

由此代码生成的输出是:

recursion called with [step = 0] 
Step I: 0 
Step II: 0 
Value i: 0 
Call recursion 

----------------- 

recursion called with [step = 1] 
Step I: 1 
Step II: 1 
Value i: 1 
Call recursion 

----------------- 

recursion called with [step = 2] 
Step I: 2 
--> returned recursion [step = 2] 
--> returned recursion [step = 1] 
Step II: 0 
Value i: 1 
Call recursion 

----------------- 

recursion called with [step = 1] 
Step I: 1 
Step II: 1 
Value i: 1 
Call recursion 

----------------- 

recursion called with [step = 2] 
Step I: 2 
--> returned recursion [step = 2] 
--> returned recursion [step = 1] 
--> returned recursion [step = 0] 

我们可以清楚地看到递归展开的顺序,并观察到step的值在每个步骤中都是一致的。

+0

非常感谢,这是一个非常棒的清晰解释! –

+0

@RalfMarmorglatt很高兴帮助! –