This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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