Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

One of the most fascinating uses of generators I've come across is a recursive generator

    >>> def count_binary():
    ...     yield "1"
    ...     for prefix in count_binary():
    ...         yield prefix + "0"
    ...         yield prefix + "1"
    ...
    >>> cb = count_binary()
    >>> next(cb)
    '1'
    >>> next(cb)
    '10'
    >>> next(cb)
    '11'
    >>> next(cb)
    '101'
[0] https://www.reddit.com/r/Python/comments/ovjubg/whats_the_mo...


They are particularly nice when processing a recursive datastructure such as a tree. The technique can make for some very short and readeable code.


I like them for building VMs quickly


Do you have any example code?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: