Skip to content

Instantly share code, notes, and snippets.

@vineyyadav
Created May 3, 2017 06:04
Show Gist options
  • Save vineyyadav/43eb862e7dcbbdec08374f3b6d1234e0 to your computer and use it in GitHub Desktop.
Save vineyyadav/43eb862e7dcbbdec08374f3b6d1234e0 to your computer and use it in GitHub Desktop.
# Solution for the SO question: http://stackoverflow.com/q/43702768/4045754
#
# The files e.g. coordinates.txt are mentioned in the SO question
# Read data from the file
with open("coordinates.txt") as f:
data = f.readlines()
data = [x.strip() for x in data]
# Final result
result = []
# Create a coordinate dictionary from the data
segDict = {}
for segment in data:
coordinates = segment.split('), (')
segDict[coordinates[0][2:]] = coordinates[1][:-2]
def getTupleFromStr(str):
coordinates = str.split(',')
return (int(coordinates[0]), int(coordinates[1]))
def getPolygon():
start_coordinate = None
poly = []
# Get any key
for key in segDict:
start_coordinate = key
poly.append('M')
poly.append(getTupleFromStr(start_coordinate))
poly.append('L')
break
while key in segDict:
newKey = segDict[key]
del(segDict[key])
poly.append(getTupleFromStr(newKey))
key = newKey
#Push to result if polygon complete
if key == start_coordinate:
result.extend(poly[:-1]) #exclude the last coordinate as it is same as first one
# Discover polygons from the segDict
while len(segDict) > 0:
getPolygon()
print result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment