Skip to content

Instantly share code, notes, and snippets.

@duruyao
Last active October 8, 2022 08:29
Show Gist options
  • Save duruyao/969695a2f28c8b7814241c8dda18512c to your computer and use it in GitHub Desktop.
Save duruyao/969695a2f28c8b7814241c8dda18512c to your computer and use it in GitHub Desktop.
Print rectangles, squares and tables to the command line interface.
#!/usr/bin/env python3.9
r_w3_h2 = """\
┌─┐
└─┘"""
r_w5_h3 = """\
┌───┐
│ │
└───┘"""
r_w7_h4 = """\
┌─────┐
│ │
│ │
└─────┘"""
r_w9_h5 = """\
┌───────┐
│ │
│ │
│ │
└───────┘"""
t_n1_m2_w3_h2 = """\
┌─┬─┐
└─┴─┘"""
t_n2_m1_w3_h2 = """\
┌─┐
├─┤
└─┘"""
t_n2_m2_w3_h2 = """\
┌─┬─┐
├─┼─┤
└─┴─┘"""
t_n2_m3_w3_h2 = """\
┌─┬─┬─┐
├─┼─┼─┤
└─┴─┴─┘"""
t_n3_m2_w3_h2 = """\
┌─┬─┐
├─┼─┤
├─┼─┤
└─┴─┘"""
def rectangle(w: int = 2, h: int = 2) -> list[list[str]]:
w = max(2, w)
h = max(2, h)
r = [[' ' for x in range(w)] for y in range(h)]
r[0][0], r[0][w - 1] = '┌', '┐'
r[h - 1][0], r[h - 1][w - 1] = '└', '┘'
r[0] = [c.replace(' ', '─') for c in r[0]]
r[h - 1] = [c.replace(' ', '─') for c in r[h - 1]]
for cc in r[1:-1]:
cc[0] = cc[-1] = '│'
return r
def square(h: int = 2) -> list[list[str]]:
h = max(2, h)
w = 2 * h - 1
return rectangle(w, h)
def table(n: int = 1, m: int = 1, w: int = 3, h: int = 2) -> list[list[str]]:
w = max(2, w)
h = max(2, h)
w1 = m * w - (m - 1)
h1 = n * h - (n - 1)
t = [[' ' for x in range(w1)] for y in range(h1)]
t[0][0], t[0][w1 - 1] = '┌', '┐'
t[h1 - 1][0], t[h1 - 1][w1 - 1] = '└', '┘'
for i in range(h - 1, h1 - 1, h - 1):
t[i][0], t[i][-1] = '├', '┤'
for j in range(w - 1, w1 - 1, w - 1):
t[i][j] = '┼'
t[i] = [c.replace(' ', '─') for c in t[i]]
for j in range(w - 1, w1 - 1, w - 1):
t[0][j], t[-1][j] = '┬', '┴'
t[0] = [c.replace(' ', '─') for c in t[0]]
t[h1 - 1] = [c.replace(' ', '─') for c in t[h1 - 1]]
for cc in t[1:-1]:
for j in range(0, w1, w - 1):
cc[j] = cc[j].replace(' ', '│')
return t
def print_graphics(graphics: list[list[str]]):
for line in graphics:
print(''.join(line))
def main():
print_graphics(rectangle(w=5, h=7))
print_graphics(square(h=4))
print_graphics(table(n=3, m=4, w=3, h=2))
if __name__ == '__main__':
main()
@duruyao
Copy link
Author

duruyao commented Jul 29, 2022

$ python3 ./cli_graphics.py 
┌───┐
│   │
│   │
│   │
│   │
│   │
└───┘
┌─────┐
│     │
│     │
└─────┘
┌─┬─┬─┬─┐
├─┼─┼─┼─┤
├─┼─┼─┼─┤
└─┴─┴─┴─┘

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment