简体   繁体   English

排列生成器代码中的条件和递归

[英]conditionals and recursion in permutations generator code

def genperm(perm,n):
    if len(perm)==n:
3         print('output',perm)
          return
    for i in range(n):
          print('i',i)
7         if i not in perm:
                perm.append(i)
                print('appended',perm)
                genperm(perm,n)
11            print('to pop',perm)
                    perm.pop()
genperm([],2)O

So I have this code that outputs permutations with out repetitions. 因此,我有这段代码可以输出没有重复的排列。 It works but I don't understand how. 它有效,但我不知道如何。 So I put some unnecessary prints to see how they are generated. 因此,我放置了一些不必要的打印件以查看它们是如何生成的。

For the sake of this example n=2 which are values (0,1) and so the output should be 0,1 and 1,0. 出于本示例的考虑,n = 2是值(0,1),因此输出应为0,1和1,0。 Once run, it prints: 运行后,将打印:

i 0 
appended [0]
i 0
i 1
appended [0, 1]
3  output [0, 1]
11 to pop [0, 1]
to pop [0]
i 1
appended [1]
i 0
appended [1, 0]
output [1, 0]
to pop [1, 0]
i 1
to pop [1]

So let's say we get to a state where perm=[0,1] and so line 3 prints it, but then it jumps to line 11. My question is how does it enters the conditional in line 7 if at that point, all possibles values of i are in perm and so it is false. 假设我们进入了perm = [0,1]的状态,因此第3行将其打印出来,但是随后它跳到了第11行。我的问题是,如果到那时,所有可能的情况,它将如何进入第7行的条件i的值在烫发中,所以它是错误的。

It goes into the recursive function at line 10. This means it runs the function again from the start at this point. 它进入第10行的递归函数。这意味着它会从头开始再次运行该函数。 So it is jumping from line 10 to line 2, not jumping to line 11. It then prints at line 3 (Where perm=[0,1] )and returns , which ends the recursive function at line 10. So it continues on to line 11, where it pops 1 before going to line 7 again for the next i , 1. Which is True. 因此它从第10行跳到第2行,而不是跳到第11行。然后在第3行打印(其中perm=[0,1] )并返回 ,从而在第10行结束递归函数。因此,它继续进行到第11行,在弹出下一个i之前的第7行之前,它会弹出1。这是对的。

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

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