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

tpc247 at gmail.com tpc247 at gmail.com
Mon Jul 23 08:24:53 CEST 2007


On 7/20/07, Bob Gailer <bgailer at alum.rpi.edu> wrote:
>
> 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
>

simply amazing.  Thank you.

OK - to address your original question:
>
>     def create_grid(self):
>         table = []
>         while self.total_num_of_items:
>             row = []
>             count = 0
>             while count < self.max_num_of_items_per_row and
> self.total_num_of_items:
>                 row.append(self.total_num_of_items.pop(0))
>                 count += 1
>             table.append(tuple(row))
>         return table


At first I  regarded you with quiet awe, but then the nitpick in me saw the
two "while self.total_num_of_item" statements, and I was less pleased.
However, I see this as a doable challenge you have given me, and I will
attempt to optimize your revisions.  Thanks again.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070722/faf0bd99/attachment.html 


More information about the Tutor mailing list