[Tutor] Making Doubly Linked List with Less Lines of Code.

WolfRage wolfrage8765 at gmail.com
Thu Dec 25 18:09:19 CET 2014

Thanks, definitely adding this concept into my code. And re-writing. I 
originally hard coded everything just to get it working... but 
obviously, it would have been more time efficient to have thought in 
these terms from the beginning. Hopefully I can learn to write code more 
like this to begin with, even when I just want to get something working.
Reading the rest of your recommendations now.

On 12/25/2014 12:15 AM, Danny Yoo wrote:
> Quick comment: the structure of the code here catches my eye:
>>          # Each variable below is a link to the head Node in the respective
>>          # row or column.
>>          self.row0 = None
>>          self.row1 = None
>>          self.row2 = None
>>          self.row3 = None
>>          self.row4 = None
>>          self.row5 = None
>>          self.row6 = None
>>          self.row7 = None
>>          self.row8 = None
>>          self.row9 = None
> It seems highly regular; the code here is maintaining a collection of
> row variables.  Because it's so regular, you might consider using a
> list to represent this collection.  Concretely:
>      self.rows = [None, None, None, None, None, None, None, None, None, None]
> We can express this more concisely in Python as:
>      self.row = [None] * 10
> Once we have this, then we can get at any particular row through its
> offset.  So instead of:
>      self.row0
> we say:
>      self.row[0]
> The big win with a list representation is that the offset can be
> computed.  So if we need to do an operation on each row, we might say:
>      for i in range(10):
>          ## ... Do something with self.row[i]
> And if you see the full power of this, you'll realize that this allows
> us to express loops to do something to _all_ the rows, expressing that
> action just once.  Or if we need to do something for every other row,
> that too is not too difficult to express:
>      for i in range(0, 10, 2):
>          ## ... Do something with self.row[i]
> In contrast, doing the same thing without using an explicit container
> representation means that doing container-wide actions is harder to
> do.  This is the code smell that we saw at the beginning of this post,
> where we see repetitive code.

More information about the Tutor mailing list