[Tutor] don't repeat yourself; question about code optimization CORRECTION
Bob Gailer
bgailer at alum.rpi.edu
Sun Jul 29 18:47:00 CEST 2007
tpc247 at gmail.com wrote:
>
>
> On 7/23/07, *Bob Gailer* <bgailer at alum.rpi.edu
> <mailto:bgailer at alum.rpi.edu>> wrote:
>
> A correction to the code at the end. The test of
> self.total_num_of_items
> should precede the pop(0)
>
>
>
> Bob, I spent today studying what you've been telling me and I put the
> finishing touches to make your code pass my battery of tests. It
> still is repetitive, i.e., table.append(tuple(row)), but I've found
> guidance in what Alan had to say about code readability and easy
> maintenance, and am no longer going to press the matter:
>
> class Table_Creator(object):
> def __init__(self, total_num_of_items, max_num_of_items_per_row):
> self.given_items = range(total_num_of_items)
> self.max_num_of_items_per_row = max_num_of_items_per_row
>
> def create_grid(self):
> table = []
> while True:
> row = []
> while len(row) < self.max_num_of_items_per_row:
> if not self.given_items:
> if row:
> table.append(tuple(row))
> return table
> row.append(self.given_items.pop(0))
> table.append(tuple(row))
A bit more juggling leads to more simplification:
def create_grid(self):
table = []
while self.given_items:
row = []
while len(row) < self.max_num_of_items_per_row and
self.given_items:
row.append(self.given_items.pop(0))
table.append(tuple(row))
return table
Testing self.given_items twice is unavoidable.
--
Bob Gailer
510-978-4454 Oakland, CA
919-636-4239 Chapel Hill, NC
More information about the Tutor
mailing list