Skip to content

Instantly share code, notes, and snippets.

@NobodyXu
Last active March 28, 2019 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NobodyXu/002d404f8ef21e9a4caade8e802edb12 to your computer and use it in GitHub Desktop.
Save NobodyXu/002d404f8ef21e9a4caade8e802edb12 to your computer and use it in GitHub Desktop.
challenges -- A place where I save the solutions to challenges which I think is beautiful
#!/usr/bin/env python3
import sys
# rowList is a list who the first and last element is 0(which will not be printed)
def print_pascal_triangle_row(row):
print(" ".join([str(each) for each in row[1 : -1]]))
# @parm n denotes how many rows should it print
def print_pascal_triangle(n):
row = [0, 1, 0]
for _ in range(n):
print_pascal_triangle_row(row)
# Calculate next row
for i in range(len(row) - 1):
row[i] += row[i + 1]
# Add the zero at front to maintain invariant
row.insert(0, 0)
if len(sys.argv) < 2:
print("Not enough arguments.")
elif len(sys.argv) > 2:
print("Too many arguments.")
else:
try:
print_pascal_triangle(int(sys.argv[1]) + 1)
except ValueError:
print("Invalid argument.")
#!/usr/bin/env python3
# This program will not be possible without this post:
# https://stackoverflow.com/questions/18551558/how-to-use-terminal-color-palette-with-curses
import curses
import random
star = "*"
space = " "
sleeptime = 500 # Unit: milliseconds(ms)
# curses support 3 visibility:
# 0 for completely invisible
# 1 for between invisible and visible(often curses in this state is
# represented as "_")
# 2 for visible(often represented as a block)
#
# This routine will set visibility as low as possible.
def hide_curs_if_possible():
visibility = 0
while visibility <= 2:
try:
curses.curs_set(visibility)
break
except curses.error:
visibility += 1
# Initialize color support and return a tuple denoting the begin and the end of
# the range of the color available.
## Note not all terminal does support A_BLINK
def init_color(stdscr):
curses.start_color()
curses.use_default_colors()
for i in range(0, curses.COLORS):
curses.init_pair(i + 1, i, -1)
return 1, curses.COLORS + 2
# Return attr based on the return value of 3 calls to random.random().
# Some terminal emulator may not support some attr well.
def rand_attr(color_begin, color_end):
attr = curses.A_NORMAL
# First decide brightness
randNum = random.random()
if randNum <= 0.5:
attr |= curses.A_DIM
elif randNum > 0.8:
attr |= curses.A_BOLD
# Then decide whether they blink
if random.random() <= 0.7:
attr |= curses.A_BLINK
# Finally, decied color
## Exclude the black color(since the bg is black)
randNum = random.randint(color_begin, color_end - 1)
attr |= curses.color_pair(randNum)
return attr
def main(stdscr):
# Do not update cursor position.
# As a side effect, it will make the cursor invisible if possible
stdscr.leaveok(True)
# Hide cursor(since leaveok alone can't achieve the goal)
hide_curs_if_possible()
# There will be no need to optimize for input since the program don't need
# any user input
curses.typeahead(-1)
# Enable line insertion/deletion
stdscr.idlok(True)
# Initialize and get color range
(color_beg, color_end) = init_color(stdscr)
# Get height and width of the screen
(height, width) = stdscr.getmaxyx()
# Erase the screen and repaint it since we don't know we is there.
stdscr.clear()
while True:
stdscr.move(0, 0)
# All the operation below will not be performed until doupdate()
## Insert one new line under the curser
## If the last line go off the screen, it is erased.
stdscr.insertln()
## Use curses addstr directly instead of manipulating list in python,
## then copy it into stdscr using addstr
for _ in range(random.randint(0, width // 8)):
stdscr.addstr(0, random.randint(0, width - 1), star,
rand_attr(color_beg, color_end))
## Update the data structure representing the desired state of the
## window, but does not force an updte of the physical screen.
stdscr.noutrefresh()
## curses.napms is better than time.sleep here.
## It handles SIGWINCH(terminal resizing) signal and reenter the
## state of sleeping.
curses.napms(sleeptime) # Unit: milliseconds(ms)
# Update the screen!
curses.doupdate()
# curses.wrapper call initscr, cbreak, noecho, enable terminal keypad and color
# before calling main(stdscr) (stdscr is the return value of initscr)
# After main exit, either normally or by exception, all the effect will be
# reversed.
try:
curses.wrapper(main)
except KeyboardInterrupt:
# If <ctrl + c> is passed, exit the program
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment