assert round(area({'type': 'circle', 'r': 2}), 2) == 12.57
assert area({'type': 'square', 's': 4}) == 16
assert area({'type': 'rectangle', 'w': 3, 'h': 5}) == 15
languagePython
def area(shape):
if shape['type'] == 'circle':
return 3.14159 * shape['r'] ** 2
elif shape['type'] == 'square':
return shape['s'] ** 2
elif shape['type'] == 'rectangle':
return shape['w'] * shape['h']
SHAPE_AREA = {
'circle': lambda s: 3.14159 * s['r'] ** 2,
'square': lambda s: s['s'] ** 2,
'rectangle': lambda s: s['w'] * s['h'],
}
def area(shape):
return SHAPE_AREA[shape['type']](shape)
improvement_typeduplication removal via dispatch table