Created
January 23, 2015 09:53
-
-
Save okin/893260a22e3d42448189 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/python3 | |
# vim:ft=python ts=4 sw=4 sts=4 et | |
# table.py - Simple python script that dynamically formats an ascii art table where | |
# each table cell holds an integer number (incremented, per cell). | |
# This is a typical excercise task coding lesson for new workers and I just | |
# wanted to see how bad I perform on this task. | |
# Written by Armin (Github: netzverweigerer) | |
# Thu Jan 22 16:15:24 CET 2015 | |
# Forked by Niko (Github: okin) | |
# Fri Jan 23 10:53:03 CET 2015 | |
class Table(object): | |
def __init__(self, rows, columns): | |
self.columns = int(columns) | |
self.rows = int(rows) | |
self._lines = [] | |
self._maxlength = len(str(self.rows * self.columns)) | |
self._maxlinelength = 0 | |
def _buildresultlines(self): | |
self._buildtable() | |
self._updatemaxlengthofline() | |
yield self._getheader() | |
lineGenerator = (line for line in self._lines) | |
previousElement = None | |
comingElement = None | |
seperator = self._getseperator() | |
while True: | |
if comingElement: | |
yield comingElement | |
previousElement = comingElement | |
try: | |
comingElement = next(lineGenerator) | |
except StopIteration: | |
break | |
if previousElement: | |
yield seperator | |
yield self._getfooter() | |
def _buildtable(self): | |
self._lines = [self._buildrow(row) for row in range(0, self.rows)] | |
def _buildrow(self,row): | |
def pad(number): | |
return format(number, str(self._maxlength)) | |
return '|{0}|'.format('|'.join([" {0} ".format(pad(number + (row * (self.columns)))) for number in range(1, self.columns + 1)])) | |
# go through all lines and update the maximum length of line variable | |
def _updatemaxlengthofline(self): | |
self._maxlinelength = max(len(l) for l in self._lines) | |
# returns a nicely formatted header | |
def _getheader(self): | |
return ',{0}.'.format('-' * (self._maxlinelength - 2)) | |
# returns a nicely formatted horizontal seperator line | |
def _getseperator(self): | |
return '-' * self._maxlinelength | |
# returns a nicely formatted footer | |
def _getfooter(self): | |
return '`{0}´'.format('-' * (self._maxlinelength - 2)) | |
def __str__(self): | |
return '\n'.join(line for line in self._buildresultlines()) | |
a = Table(input("Please enter number of rows: "), input("Please enter number of columns: ")) | |
print(str(a)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment