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

Bob Gailer bgailer at alum.rpi.edu
Sat Jul 21 06:00:24 CEST 2007


tpc247 at gmail.com wrote:
> 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.
Take advantage of slicing:
    def create_grid(self):
        table = []
        for i in range(0, len(self.total_num_of_items), 
self.max_num_of_items_per_row):
          table.append(tuple(self.total_num_of_items[i : i + 
self.max_num_of_items_per_row]))
        return table


-- 
Bob Gailer
510-978-4454 Oakland, CA
919-636-4239 Chapel Hill, NC




More information about the Tutor mailing list