Last active
March 12, 2024 15:15
-
-
Save MayankFawkes/9c26882cea0fce086eeac689c418a0fa to your computer and use it in GitHub Desktop.
Generate data table in program
This file contains hidden or 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
| ''' | |
| A simple table generator | |
| +--------------------------+-----------------+---------+ | |
| | NAME | CLASS | NERD | | |
| +--------------------------+-----------------+---------+ | |
| | Mayank Gupta | 12th science | Yes | | |
| | Pradhumn Singh Parmar | 12th science | - | | |
| | Prakhar Dwivedi | - | - | | |
| +--------------------------+-----------------+---------+ | |
| t = Table(("Name", "Class", "Nerd"), margin=5) | |
| t.add_row("Mayank Gupta", "12th science", "Yes") | |
| t.add_row("Pradhumn Singh Parmar", "12th science") | |
| t.add_row("Prakhar Dwivedi", "") | |
| print(t.to_string()) | |
| ''' | |
| class Table: | |
| COLUMN_SEP = '|' | |
| ROW_SEP = '-' | |
| EDGE_SEP = '+' | |
| def __init__(self, titles: tuple, margin: int = 0): | |
| self.titles = [title.upper() for title in titles] | |
| self.margin = margin | |
| self.width = len(titles) | |
| self.column_widths = [len(title) for title in self.titles] | |
| self.rows = [] | |
| def _display_line(self): | |
| row_str = self.EDGE_SEP | |
| for width in self.column_widths: | |
| row_str += self.ROW_SEP * (width + self.margin) + self.EDGE_SEP | |
| return row_str | |
| def _display_row(self, row): | |
| row_str = self.COLUMN_SEP | |
| for width, item in zip(self.column_widths, row): | |
| row_str += f'{item or "-":^{width + self.margin}}' + self.COLUMN_SEP | |
| return row_str | |
| def to_string(self): | |
| lines = [ | |
| self._display_line(), | |
| self._display_row(self.titles), | |
| self._display_line() | |
| ] + [self._display_row(row) for row in self.rows] | |
| lines.append(self._display_line()) | |
| return '\n'.join(lines) | |
| def display(self): | |
| print(self.to_string()) | |
| def add_row(self, *items): | |
| if len(items) < self.width: | |
| items += ('',) * (self.width - len(items)) | |
| for i, item in enumerate(items): | |
| self.column_widths[i] = max(self.column_widths[i], len(str(item))) | |
| self.rows.append(items) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment