Skip to content

Instantly share code, notes, and snippets.

@alexmojaki
Last active August 17, 2022 13:05
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 alexmojaki/572dcdc3aed5119a33267ba8c57d23e6 to your computer and use it in GitHub Desktop.
Save alexmojaki/572dcdc3aed5119a33267ba8c57d23e6 to your computer and use it in GitHub Desktop.
class Box(str):
def __new__(cls, s):
lines = s.split("\n")
width = max(len(line) for line in lines)
top_bottom = '-' * width
return super().__new__(cls, box_template.format(
top_bottom=top_bottom,
middle="\n".join(f"| {line:{width}} |" for line in lines)))
def __add__(self, other):
lines1 = self.split("\n")
lines2 = other.split("\n")
width1 = max(len(line) for line in lines1)
width2 = max(len(line) for line in lines2)
return "\n".join(
f'{line1:{width1}} {"+" if i == 2 else " "} '
f'{line2:{width2}}'
for i, (line1, line2) in enumerate(zip(lines1, lines2))
)
def __radd__(self, other):
return type(self).__add__(other, self)
box_template = """
+-{top_bottom}-+
{middle}
+-{top_bottom}-+
"""
cat = """
|\---/|
| o_o |
\_^_/
"""
assert Box(3 * cat + Box(Box(cat) + 2 * cat)) == """
+-------------------------------------+
| |
| |\---/| +-----------------------+ |
| | o_o | + | | |
| \_^_/ | +---------+ |\---/| | |
| | | | + | o_o | | |
| |\---/| | | |\---/| | \_^_/ | |
| | o_o | | | | o_o | | | |
| \_^_/ | | \_^_/ | |\---/| | |
| | | | | o_o | | |
| |\---/| | +---------+ \_^_/ | |
| | o_o | | | |
| \_^_/ +-----------------------+ |
| |
+-------------------------------------+
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment