HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Fundamental Polygon in Python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pythonpolygonfundamental

Problem

I am writing a python class to implement a object moving along a Fundamental Polygon. It takes in a size of the square and config option with three booleans enumerating the 8 possibilities, the first bit indicates whether connected sides are opposite or adjacent, the second indicates if the primary sides are parallel or antiparallel, and the third indicates if the secondary sides are parallel or antiparallel.

For example to denote a torus the config would be:

(False, False, False)


My implementation of the wraparound (when the pointer moves off the edge of the square), is quite messy. I'm not sure what I should do to make the code more readable and straight forward.

```
class Topology(object):
def __init__(self,dim,config):
self.dim = dim
self.direction = [0,1]
self.location = [0,0]
# (matching, primary twist, secondary twist)
self.config = config
def move(self):
self.location = [
self.location[0]+self.direction[0],
self.location[1]+self.direction[1]
]
#Important bit
if self.location[0] >= self.dim[0]:
if config[1]:
self.location[1] *= -1
if config[0]:
self.location = self.location[::-1]
self.direction = self.direction[::-1]
if self.location[1] >= self.dim[1]:
if config[2]:
self.location[0] *= -1
if config[0]:
self.location = self.location[::-1]
self.direction = self.direction[::-1]
if self.location[0] < 0:
if config[2]:
self.location[1] *= -1
if config[0]:
self.location = self.location[::-1]
self.direction = self.direction[::-1]
if self.location[1] < 0:
if config[1]:
self.location[0] *= -1
if config[0]:
self.location = self.location[::-1]

Solution

-
First thing first, make config a named tuple. This would seriously improve readability, and obviate the (really unclear) comment.

-
Factored out the repeated code into a function, e.g.:

def wraparound(coord, matching, twist):
    if 0 < self.location[coord] < self.dimension[coord]:
        return
    if twist:
        self.location[1 - coord] *= -1
    if matching:
        self.location = self.location[::-1]
        self.direction = self.direction[::-1]

Code Snippets

def wraparound(coord, matching, twist):
    if 0 < self.location[coord] < self.dimension[coord]:
        return
    if twist:
        self.location[1 - coord] *= -1
    if matching:
        self.location = self.location[::-1]
        self.direction = self.direction[::-1]

Context

StackExchange Code Review Q#163016, answer score: 2

Revisions (0)

No revisions yet.