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

ALAN GAULD alan.gauld at btinternet.com
Sun Jul 29 18:01:34 CEST 2007


> assert create_table(5, 3) == [(0, 1, 2), (3, 4)]
> AssertionError
>
> I know that my method of calculating the number of rows is faulty, 
> but I'm not sure how to correct it.




    num_rows = (num_items/row_size) + (num_items%row_size)


This uses integer division then adds the remainder, so for your 
example of 5,3 we get



5/3 = 1

5%3 = 2

So rows = 3 -  wrong!



All you want to do is add one if the modulus is not zero, so



    num_rows = (num_items/row_size) 

    if num_items % row_size > 0: 

        num_rows += 1



Should do what you want. 



HTH,



Alan G.














-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070729/f722cead/attachment.htm 


More information about the Tutor mailing list