# How to do “random” distribution of certain classes to certain amount of polygons with respect to spatial constraints

I have a polygon layer.

Now, I would like to assign/allocate/classify these Polygon into 13 different classes respecting spatial constraint, in my case: neighboring polygons (sharing line or nodes) are not allowed to have the some class.

How can I do this in ArcPy?

here is a bit of code based on my code for the four colour theorem. Instead of sorting the colours to use the minimum, I used here a random choice.

``````import random, arcpy
arcpy.MakeFeatureLayer_management(fc, fc[:-4]+ "_lyr" )
try:
except:
arcpy.CalculateField_management(fc[:-4] + "_lyr", "color",  "10" , "PYTHON")

arcpy.PolygonNeighbors_analysis(fc[:-4] + "_lyr", fc[:-4] + "_tb.dbf" )
graph = []
cursor=arcpy.da.SearchCursor( fc[:-4] + "_tb.dbf" , ("src_FID","nbr_FID") )
for row in cursor:
graph.append(row)

pols = arcpy.da.UpdateCursor(fc[:-4] + "_lyr", ("OID@","color"))
colored = []
random.seed()
for pol in pols:
nbrs = [ second for first, second in graph if first == pol[0]]
usedcolors = []
for nbr in nbrs:
usedcolors += [second for first, second in colored if first == nbr]
pol[1]=[color for color in random.shuffle(range(13)) if color not in usedcolors][0]
colored.append(pol)
pols.updateRow(pol)
``````