[Tutor] don't repeat yourself; question about code optimization

tpc247 at gmail.com tpc247 at gmail.com
Sat Jul 21 05:33:37 CEST 2007


dear fellow Python enthusiasts:

in the last year I have been experimenting with Python, and I set out to
create a function that, given a number of items and a maximum number of
items per row, would generate a table of rows of items.  However, there is
one part where I believe I violate the prime directive of coding, which is
not to repeat yourself:

class Table_Creator(object):
    def __init__(self, given_num_of_items, max_num_of_items_per_row):
        self.total_num_of_items = range(given_num_of_items)
        self.max_num_of_items_per_row = max_num_of_items_per_row

    def create_grid(self):
        table = []
        row = []
        count = 0
        while self.total_num_of_items:
            row.append(self.total_num_of_items.pop(0))
            count += 1
        if (not self.total_num_of_items) or (count ==
self.max_num_of_items_per_row):
                table.append(tuple(row))
                row = []
                count = 0
        return table

as you can see, I repeat the expressions "row = []" and "count = 0", and I
would like to know if there is something I can do to avoid repetition in
this case.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070720/0cc35666/attachment.htm 


More information about the Tutor mailing list