3

So I only want to re-run code from this repo: https://github.com/dennybritz/reinforcement-learning/blob/master/MC/MC%20Prediction%20Solution.ipynb

My focus is on the print's part:

 for i_episode in range(1, num_episodes + 1):
        # Print out which episode we're on, useful for debugging.
        if i_episode % 1000 == 0:
            print "\rEpisode {}/{}.".format(i_episode, num_episodes)
            sys.stdout.flush()

He is using sys.stdout.flush() to create a simple "progress" output. You can see the output from his repo it only show the last Episode iteration 10000/10000 because using sys.stdout.flush()

But when I try to run it in my jupyter notebook (I run using cmd command jupyter notebook) I think sys.stdout.flush() not works, it show every printed iterations, not overwrite the previous one:

Episode 1000/10000.
Episode 2000/10000.
Episode 3000/10000.
Episode 4000/10000.
Episode 5000/10000.
Episode 6000/10000.
Episode 7000/10000.
Episode 8000/10000.
Episode 9000/10000.
Episode 10000/10000.

Am I missing something when run jupyter to make it works?

malioboro
  • 3,097
  • 4
  • 35
  • 55
  • 1
    It's the `\r`s that cause the overwrite, not the `flush()` -- that just makes sure the content isn't stuck in-buffer. Since it focuses on something other than the key component, this is a bit confusing as presently written. – Charles Duffy Jan 27 '17 at 22:48
  • oh.. I don't aware about `\r` symbol there, thanks :) it makes clear now – malioboro Jan 27 '17 at 23:16

2 Answers2

1

Charless Duffy comment makes everything clear. The problem of overwriting is not on flush function buat in print function.

I found the solution is just edit the print format from:

print("\rEpisode {}/{}.".format(i_episode, num_episodes))

to

print("\rEpisode {}/{}.".format(i_episode, num_episodes), end="")

and the overwrite works now

malioboro
  • 3,097
  • 4
  • 35
  • 55
  • If your stdout were unbufered (rather than line-buffered, as is typically default for a TTY), this would work without `flush()` *at all*. Describing it as "the flush" that works or doesn't doesn't make much sense. – Charles Duffy Jan 27 '17 at 22:50
  • that's right, I think flush is the one which responsible about overwrite just by guessing, I was not aware about `\r` symbol there, thanks I will edit it – malioboro Jan 27 '17 at 23:18
  • 1
    or ```print "\rEpisode {}/{}.".format(i_episode, num_episodes),``` in case of python 2.x – kampta May 16 '17 at 09:04
0

Python program to print list without new line character

Declare a List
import time
listfruits = ['Apple', 'Banana', 'Orange', 'Mango']
Print list using for Loop
for fruit in listfruits:
    print('\r'+fruit, end=' ')
    time.sleep(3)
joanis
  • 10,635
  • 14
  • 30
  • 40