Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Generator behaviour
#1
Hello,

encountered this smart piece of breadth-first traversal:

def bfs(root):
    yield root
    for n in bfs(root):
        yield n.left
        yield n.right
but am confused about pythons behaviour here.

If you omit the first yield, the (recursive?) generator call on line 3 is
empty and this results in endless recursion, so behaves like a function
call. (One would expect it to not get executed at all).

But with the first yield, the non-empty generator gets iterated over.
Looks like the call behaves like a function in one case and a generator in
the other?
Reply
#2
I cannot get the code to work. When I call bcs() it traverses the tree level by level, but eventually left or right will be None, and that results in trying to get None.left and None.right. If I only yield left and right in n is not None, that fixes the attribute error, but then it hits the recursion limit. Maybe I am making the wrong kind of tree.

If you remove "yield root", bcs() cannot yield a result. There is no way to get past the internal bcs(root) call to yield n.left or yield n.right. bcs(root) calls bcs(root) which calls bcs(root) and nothing is ever generated.
Reply
#3
Hi, thanks. Just wanted to discuss the code a bit.
This looks deceptively simply, but is quite nifty.

Normally, bfs is done with a queue.
But, can bfs done with pure recursion?
If you don't count the state inherent in generators,
this demonstrates it.

Drawback of this solution is suboptimal complexity.

Has anyone else wrapped their head around it?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  logger behaviour setdetnet 1 895 Apr-15-2023, 05:20 AM
Last Post: Gribouillis
  can someone explain this __del__ behaviour? rjdegraff42 1 727 Apr-12-2023, 03:25 PM
Last Post: deanhystad
  Asyncio weird behaviour vugz 2 1,261 Apr-09-2023, 01:48 AM
Last Post: vugz
  Weird behaviour using if statement in python 3.10.8 mikepy 23 3,640 Jan-18-2023, 04:51 PM
Last Post: mikepy
  Inconsistent behaviour in output - web scraping Steve 6 2,564 Sep-20-2021, 01:54 AM
Last Post: Larz60+
  Adding to the dictionary inside the for-loop - weird behaviour InputOutput007 5 2,724 Jan-21-2021, 02:21 PM
Last Post: InputOutput007
  Behaviour of 2D array SimonB 6 2,842 Jan-21-2021, 01:29 PM
Last Post: SimonB
  strange behaviour- plotting nathan_Blanc_Haifa 0 1,506 Dec-27-2020, 01:37 PM
Last Post: nathan_Blanc_Haifa
  OOP behaviour problem JohnB 3 2,435 Aug-18-2020, 07:51 PM
Last Post: JohnB
  understanding basic loop behaviour vinci 5 2,918 Feb-11-2020, 09:53 PM
Last Post: vinci

Forum Jump:

User Panel Messages

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