Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have the following block of codes. it computes the 'Four color theorem'. I converted it from a java program. is there any way to write the name of the countries in map, instead of their id?

from collections import defaultdict
colors = ['Red', 'Yellow', 'Green', 'Blue']
mapColors = defaultdict(str)

def okToColor(Map ,country, color):
    for c in Map[country]:
        if mapColors[c] == color: return False
    return True

def explore(Map, country, color):
    if country >= len(Map): return True
    if okToColor(Map, country, color):
        mapColors[country] = color
        for color in colors:
            if explore(Map, country + 1, color): return True
            #explore(Map, country + 1, color)   
    return False

def printMap():
    for c in mapColors:
        print c, mapColors[c]
        #"map[" + str(i) + "] is " + mapColors[i]

Map = [[1, 4, 2, 5], [0, 4, 6, 5], [0, 4, 3, 6, 5], [2, 4, 6],
        [0, 1, 6, 3, 2], [2, 6, 1, 0], [2, 3, 4, 1, 5]]
result = explore(Map, 0, 'Red')
print result

I want't the Map to be a graph like this:

Map = { 'A':['B', 'C'], 'B':['A','D'], ...}

where A, B, C, D are the name of the countries.

share|improve this question

put on hold as off-topic by Jamal yesterday

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions containing broken code or asking for advice about code not yet written are off-topic, as the code is not ready for review. After the question has been edited to contain working code, we will consider reopening it." – Jamal
If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer 1

up vote 1 down vote accepted

while changing your Map to a dict like this is more readable

Map = { 'A': ['B', 'C', 'E', 'F'], 'B': ['A','E','G', 'F'],
         'C': ['A','E','D', 'G', 'F'], 'D': ['C','E','G'],
         'E': ['A','B', 'G', 'D', 'C'], 'F': ['C', 'G', 'B', 'A'],
         'G': ['C', 'D', 'E', 'B', 'F']}

it will make your algorithm a little bit less readable.
However, by adding an indexed container for the countries.

countries = Map.keys()

you can leave the other functions almost unchanged, besides explore where you will have to introduce a differentiation between indexes and names:

def explore(Map, country_idx, color):
    if country_idx >= len(Map): return True
    country = countries[country_idx]
    if okToColor(Map, country, color):
        mapColors[country] = color
        for color in colors:
            if explore(Map, country_idx + 1, color): return True
    return False
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.