Live data from Hacker News

Unconditional loops are unconditionally awesome

brson.github.io

11–13 of 13 posts

Re: Unconditional loops are unconditionally awesome

#11
One thing I don't know how to do in Python is using while loops to collect results of some other loop that runs at the same time.

For example, within the same script, I would have a simulate_magic_numbers function with a loop that produces a sequence of magic numbers continuously for a few hours and returns them once done. Below, I would like to have a while loop that grabs the magic numbers every 10 minutes and plots them.

I know how to do it with two separate scripts and saving intermediate numbers to a file, but it would be great to be able to do it within a single Jupiter notebook. However, there doesn't seem to be a straight-forward way of doing it.

Re: Unconditional loops are unconditionally awesome

#12

One thing I don't know how to do in Python is using while loops to collect results of some other loop that runs at the same time. For example, within the same script, I would have a simulate_magic_numbers function with a loop that produces a sequence of magic numbers continuously for a few hours and returns them once done. Below, I would like to have a while loop that grabs the magic numbers every 10 minutes and plot…

You could use a co-routine to generate the magic numbers. Something like this:

  def gen_magic_nums():
     for i in range(100):
        yield i**2

  for num in gen_magic_nums():
     add_to_plot(num)

Re: Unconditional loops are unconditionally awesome

#13

One thing I don't know how to do in Python is using while loops to collect results of some other loop that runs at the same time. For example, within the same script, I would have a simulate_magic_numbers function with a loop that produces a sequence of magic numbers continuously for a few hours and returns them once done. Below, I would like to have a while loop that grabs the magic numbers every 10 minutes and plot…

Seems like you just want a global variable that is shared between two cells?

    current_items = None

    def generate_numbers():
        global current_items
        items = []
        current_items = items
        while True:
            items.append(my_item)
        return items

    def view_current_plot():
        plot(current_items)
Note that you probably want to run `generate_numbers()` in a different thread or a different async coroutine so the Jupyter kernel would not block for the duration of it.
Post reply on HN