Skip to content

Instantly share code, notes, and snippets.

@nosada
Created May 2, 2019 12:54
Show Gist options
  • Save nosada/7e070b6988ea578430a3bdc72bf5e198 to your computer and use it in GitHub Desktop.
Save nosada/7e070b6988ea578430a3bdc72bf5e198 to your computer and use it in GitHub Desktop.
Show Fibonacci numbers in oneline, keeping to refresh stdout (You are not expected to see this; there are much more useful examples in the Internet)
#!/bin/env python
from time import sleep
import sys
def yield_fibonacci_nums(n):
a = b = 1
if n < 2:
yield b
for _ in range(n-1):
a, b = b, a + b
yield b
def print_in_oneline(string):
sys.stdout.write('\r')
sys.stdout.write(string)
sys.stdout.flush()
sleep(0.005)
def print_fibonacci_nums(n, padding=1):
func_tmpl = "fibonacci({n})"
padding = padding + len(func_tmpl.format(n=''))
tmpl = "{{func:{p}}}: {{result}}".format(p=padding)
for num in yield_fibonacci_nums(n):
func = func_tmpl.format(n=n)
string = tmpl.format(func=func, result=num)
print_in_oneline(string)
sys.stdout.write('\n')
if __name__ == "__main__":
try:
LIMIT = int(sys.argv[1])
except (ValueError, IndexError):
sys.stdout.write("Show until 100th Fibonacci numbers\n")
LIMIT = 100
PADDING = len(str(LIMIT))
for i in range(LIMIT+1):
print_fibonacci_nums(i, padding=PADDING)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment