Use a Dictionary with dict.get

Darts
Darts in Python
def score(x_coord, y_coord):
    point = (x_coord**2 + y_coord**2)
    scores = {
        point <= 100: 1,
        point <= 25: 5,
        point <= 1: 10
    }
    
    return scores.get(True, 0)

At first glance, this approach looks similar to the Booleans as Integers approach, due to the Boolean evaluation used in the dictionary keys. However, this approach is not interpreting Booleans as integers and is instead exploiting three key properties of dictionaries:

  1. Keys must be hashable — in other words, keys have to be unique.
  2. Insertion order is preserved (as of Python 3.7), and evaluation/iteration happens in insertion order.
  3. Duplicate keys overwrite existing keys. If the first key is True and the third key is True, the value from the third key will overwrite the value from the first key.

Finally, the return line uses dict.get() to return a default value of 0 when a throw is outside the existing circle radii. To see this in action, you can view this code on Python Tutor.

Because of the listed dictionary qualities, order matters. This approach depends on the outermost scoring circle containing all smaller circles and that checks proceed from largest --> smallest circle. Iterating in the opposite direction will not resolve to the correct score. The following code variations do not pass the exercise tests:


def score(x_coord, y_coord):
    point = (x_coord**2 + y_coord**2)
    scores = {
        point <= 1: 10,
        point <= 25: 5,
        point <= 100: 1,
    }
    
    return scores.get(True, 0)
    
    #OR#

def score(x_coord, y_coord):
    point = (x_coord**2 + y_coord**2)
    scores = {
        point <= 25: 5,
        point <= 1: 10,
        point <= 100: 1,
    }
    
    return scores.get(True, 0)
    

While this approach is a very clever use of dictionary properties, it is likely to be very hard to reason about for those who are not deeply knowledgeable. Even those experienced in Python might take longer than usual to figure out what is happening in the code. Extensibility could also be error-prone due to needing a strict order for the dict keys.

This approach offers no space or speed advantages over using if-statements or other strategies, so is not recommended for use beyond a learning context.

9th Apr 2025 · Found it useful?