Python Forum
Recursive generator. I do not understand the step.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Recursive generator. I do not understand the step.
#1
Hi,

I use this website to visualize the step.

However, I cannot seem to understand the step 31 to 32 from the aforementioned website of the code below.
At step 31, the code is at the for loop in line 5 with i = 0. I thought it did not finish the loop.
Then at step 31 it just jumps to line 17 immediately without finishing the loop.

Could any please explain why it can jump out like that?

Thanks very much.

def heap_perm(n, A):
    if n == 1: 
        yield A
    else:
        for i in range(n-1):
            
            for hp in heap_perm(n-1, A): 
                yield hp
                
            if (n % 2) == 1: 
                j=0
            else:
                j=i
                
            A[j],A[n-1] = A[n-1],A[j]
            
        for hp in heap_perm(n-1, A): 
            yield hp
        
elements=["A","B","C"]

for k in heap_perm(len(elements),elements):
    print(k)
Reply
#2
The for i in range(n-1) runs only when i < n-1. In your case at step 31, one has n = 2, so this loops runs only for i = 0. That's why it jumps to line 17 after a single pass in the loop.
Reply
#3
(Nov-14-2018, 09:16 AM)Gribouillis Wrote: The for i in range(n-1) runs only when i < n-1. In your case at step 31, one has n = 2, so this loops runs only for i = 0. That's why it jumps to line 17 after a single pass in the loop.

Thanks very much!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Combine Two Recursive Functions To Create One Recursive Selection Sort Function Jeremy7 12 7,195 Jan-17-2021, 03:02 AM
Last Post: Jeremy7
  Don't Understand Recursive Function muzikman 9 3,576 Dec-03-2020, 05:10 PM
Last Post: muzikman
  list call problem in generator function using iteration and recursive calls postta 1 1,863 Oct-24-2020, 09:33 PM
Last Post: bowlofred
  receive from a generator, send to a generator Skaperen 9 5,423 Feb-05-2018, 06:26 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020