Articles
Screencasts
Exercises
Python
Tips
Tools
Python Pastebin
Online Python REPL
strptime
undataclass
Python Glossary
Python Jumpstart
/
Sign Up
Sign In
Print expanding Sierpiński triangle and reset once blank
"""Print expanding Sierpiński triangle and reset once blank""" from collections import deque from math import ceil from shutil import get_terminal_size from time import sleep def make_centered_bits(number, max_bit_length): """Turn number into bits, truncating beginning and end to fit.""" bits = bin(number)[2:] bits = f"{bits:0^{max_bit_length}}" # Center everything if leftover := ceil((len(bits)-max_bit_length)/2): # If bits are wider than screen, zoom in on them bits = bits[leftover:-leftover] return [b != "0" for b in bits] def print_from_bits(bits): """Print a fun shape for 1 or space for 0.""" print(*( "🬶" if bit else " " for bit in bits ), sep="") cols, rows = get_terminal_size() x = 1 last_full_screen = deque([1], maxlen=cols*rows) while any(last_full_screen): # Stop once whole screen is blank bits = make_centered_bits(x, cols) print_from_bits(bits) last_full_screen.extend(bits) x = x ^ (x << 1) # This line is the real math magic sleep(0.04)
540 views
Copy
Code copied
pym.dev/p/3cmma/
URL copied
Need to share some Python code?
New Python snippet