> --- On Sun, 7/26/09, ammar azif <ceasar...@yahoo.com> wrote: > > From: ammar azif <ceasar...@yahoo.com> > Subject: [Tutor] Need help in making this code more pythonic > To: tutor@python.org > Date: Sunday, July 26, 2009, 6:23 AM > > Hello, > > I need some suggestions on how to make this code pythonic. The program > basically runs a simulation of an object that moves on a 2D plane. The > object keeps on moving from its current coordinate to randomly picked > adjacent coordinates with the object is not allowed to move move to a > previously covered coordinate point as the rule. If the object is unable to > move the program will terminate. Some of the concerns I have in mind is the > code in the move method in Person class. I am sure there are some built-in > methods or features in python that I could use to improve the implementation > of that method. Hope you guys can enlighten me. > > _______________________________________________ > Tutor maillist - tu...@python.org > http://mail.python.org/mailman/listinfo/tutor > >
A Couple of pointers: Rather than having a dict with all values == None, you can use a set (which is effectively the same thing, but looks cleaner and is easier to read). Us the "k in d" operator rather than d.has_key(k) x = position[0] y = position[1] is more pythonically written x,y = position using tuple unpacking. rather than using cannot_move = True and then if cannot_move: You'd be more pythonic to use if not potential_positions: An empty list is false in a boolean context, a list with one or more items is true. Rather than using random.rand_int(len(...)) to generate an index, you can go straight to the result by using random.choice(...) You might also want to add some docstrings to your class and its move method, so that you can tell at a glance what the class does. A docstring is simple a string on the first (non-blank) line after the definition: def move(self): "Moves person one space in a random direction. It is not permitted to move to a previous occupied position" Finally, you might want to put the code doing the actual work into a "if __name__ == "__main__": block, so that you can import the script as a module, and not get extra output. Take a look at some of the files in the standard library to see what I mean. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor