简体   繁体   English

在递归函数中进行循环?

[英]For loop in recursive function?

When the for loop runs, why does it print all permutations of ABC instead of all 'A's? 当for循环运行时,为什么它打印ABC的所有排列而不是所有'A'?

def perm(l, n, str_a):
    if len(str_a) == n:
        print str_a
    else:
        for c in l:
            perm(l, n, str_a+c)


perm("ABC", 3, "")

Prints: 打印:

AAA AAB AAC ABA ABB ABC ACA ACB ACC BAA BAB BAC BBA BBB BBC BCA BCB...
  1. When you call perm("ABC", 3, "") , the else clause is executed (because len("") != 3 ). 当您调用perm("ABC", 3, "") ,执行else子句(因为len("") != 3 )。
  2. This result in the calls perm("ABC", 3, "A") , perm("ABC", 3, "B") and perm("ABC", 3, "C") . 这导致调用perm("ABC", 3, "A")perm("ABC", 3, "B")perm("ABC", 3, "C") Let's see what happens with the first one: 让我们看看第一个发生了什么:
  3. Again, the else is executed, resulting in the function calls perm("ABC", 3, "AA") , perm("ABC", 3, "AB") and perm("ABC", 3, "AC") . 同样,执行else ,导致函数调用perm("ABC", 3, "AA")perm("ABC", 3, "AB")perm("ABC", 3, "AC")
  4. The same thing happens with the other function calls from step 2 (you get the idea). 步骤2中的其他函数调用也会发生相同的事情(您知道了)。
  5. Let's look at perm("ABC", 3, "AA") : When called, the else is executed yet again --> perm("ABC", 3, "AAA") , perm("ABC", 3, "AAB") and perm("ABC", 3, "AAC") . 让我们看一下perm("ABC", 3, "AA") :被调用时, else将再次执行-> perm("ABC", 3, "AAA")perm("ABC", 3, "AAB")perm("ABC", 3, "AAC")
  6. In these calls, the expression len(str_a) finally is == 3 , which means that str_a will be printed. 在这些调用中,表达式len(str_a)最后是== 3 ,这意味着将打印str_a
  7. And so on, until CCC . 依此类推,直到CCC为止。

It does not keep printing 'A's, because, after 3 recursions, it will have formed the string "AAA". 它不会一直打印'A',因为经过3次递归后,它将形成字符串“ AAA”。 Then, the line print str_a will be executed, as the condition len(str_a) == n will be verified. 然后,将执行行print str_a ,因为将验证条件len(str_a) == n

After that, the execution will go back to the callee function, which was inside the c loop. 之后,执行将返回到c循环内的被调用函数。 c had value "A". c值为“ A”。 At the following iteration, c will get value "B", and perm("ABC", 3, "AAB") will be invoked, printing "AAB", and so on. 在下面的迭代中, c将获得值“ B”,并且将调用perm("ABC", 3, "AAB") ,并打印“ AAB”,依此类推。

Maybe the recursion graph could clearen things up (it's incomplete, because it's big) 也许递归图可以解决问题(它不完整,因为它很大) 递归图(不完整)

I have no idea what you are trying to do, but maybe a little bit of debug output would help you figure it out. 我不知道您要做什么,但是也许一点点调试输出会帮助您弄清楚。 Try this: 尝试这个:

def perm(iter, l, n, str_a):
    print "starting iteration {0}: l='{1}', n='{2}', str_a='{3}'".format(
        iter, l, n, str_a)
    if len(str_a) == n:
        print str_a
    else:
       for c in l:
           perm(iter+1, l, n, str_a+c)

perm(1, "ABC", 3, "")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM