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

Bob Gailer bgailer at alum.rpi.edu
Mon Jul 23 18:15:01 CEST 2007


tpc247 at gmail.com wrote:
>
>
> On 7/20/07, *Bob Gailer* <bgailer at alum.rpi.edu 
> <mailto: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.
One of the many "shifts" one makes in adjusting to "new" language 
features. I made such a shift in 1974 when I switched from FORTRAN and 
PL/I to APL.
>
>     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
We gurus bask in attention.
> , but then the nitpick in me saw the two "while 
> self.total_num_of_item" statements, and I was less pleased.
Oh all right, that costs us one more statement. Independently we can get 
rid of count:

    def create_grid(self):
        table = []
        while True:
            row = []
            while len(row) < self.max_num_of_items_per_row:
                row.append(self.total_num_of_items.pop(0))
                if not self.total_num_of_items:
                    return table
            table.append(tuple(row))


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




More information about the Tutor mailing list