Codepath

Counting Treasure

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q
    • What is the desired outcome?
    • To find the total number of treasures buried on the island.
    • What input is provided?
    • A dictionary where keys are location names and values are the number of treasures at those locations.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Iterate through each location in the dictionary, summing up the number of treasures at each location.

1) Initialize a variable `total` to store the sum of treasures.
2) Loop through each location in the `treasure_map`.
3) For each location, add the corresponding number of treasures to `total`.
4) After the loop, return the value of `total`.

⚠️ Common Mistakes

  • Forgetting to handle empty dictionaries, which should return a total of 0.
  • Incorrectly summing values, such as by using keys instead of values.

I-mplement

def total_treasures(treasure_map):
    total = 0
    for location in treasure_map:
        total += treasure_map[location]
    return total

# Example Usage:
treasure_map1 = {
    "Cove": 3,
    "Beach": 7,
    "Forest": 5
}

treasure_map2 = {
    "Shipwreck": 10,
    "Cave": 20,
    "Lagoon": 15,
    "Island Peak": 5
}
Fork me on GitHub