XClose

An introduction to research programming with Python

Home
Menu

Solution: counting people in the maze

With this maze structure:

In [1]:
house = {
    'living' : {
        'exits': {
            'north' : 'kitchen',
            'outside' : 'garden',
            'upstairs' : 'bedroom'
        },
        'people' : ['James', 'Frank'],
        'capacity' : 2
    },
    'kitchen' : {
        'exits': {
            'south' : 'living'
        },
        'people' : [],
        'capacity' : 1
    },
    'garden' : {
        'exits': {
            'inside' : 'living'
        },
        'people' : ['Sue'],
        'capacity' : 3
    },
    'bedroom' : {
        'exits': {
            'downstairs' : 'living',
            'jump' : 'garden'
        },
        'people' : [],
        'capacity' : 1
    }
}

We can count the occupants and capacity like this:

In [2]:
for room_name in house:
    print(room_name)
living
kitchen
garden
bedroom
In [3]:
house
Out[3]:
{'living': {'exits': {'north': 'kitchen',
   'outside': 'garden',
   'upstairs': 'bedroom'},
  'people': ['James', 'Frank'],
  'capacity': 2},
 'kitchen': {'exits': {'south': 'living'}, 'people': [], 'capacity': 1},
 'garden': {'exits': {'inside': 'living'}, 'people': ['Sue'], 'capacity': 3},
 'bedroom': {'exits': {'downstairs': 'living', 'jump': 'garden'},
  'people': [],
  'capacity': 1}}
In [4]:
house.values()
Out[4]:
dict_values([{'exits': {'north': 'kitchen', 'outside': 'garden', 'upstairs': 'bedroom'}, 'people': ['James', 'Frank'], 'capacity': 2}, {'exits': {'south': 'living'}, 'people': [], 'capacity': 1}, {'exits': {'inside': 'living'}, 'people': ['Sue'], 'capacity': 3}, {'exits': {'downstairs': 'living', 'jump': 'garden'}, 'people': [], 'capacity': 1}])
In [5]:
running_total = 0

for room_data in house.values():
    running_total += len(room_data["people"])

print(running_total)
3