Safe Box Management

Write a class SafeBox with private attributes for items and a combination code. Implement methods to add, remove, and list items only if the correct code is provided.

Example 1:

Input: Combination: 1234, Add: "Gold", Code: 1234 
Output: ["Gold"]
Example 2:
Input: Combination: 1234, Remove: "Gold", Code: 4321
Output: "Incorrect code"

Use a private attribute to maintain the combination code and check it in the methods that modify the safe box content.

class SafeBox:
    def __init__(self, combination):
        self._combination = combination
        self._items = []

    def add_item(self, item, code):
        if code == self._combination:
            self._items.append(item)
        else:
            return "Incorrect code"

    def remove_item(self, item, code):
        if code == self._combination:
            self._items.remove(item)
        else:
            return "Incorrect code"

    def list_items(self, code):
        if code == self._combination:
            return self._items
        else:
            return "Incorrect code"

# Test the class
safe_box = SafeBox(1234)
safe_box.add_item("Gold", 1234)
print(safe_box.list_items(1234))  # Output: ['Gold']
print(safe_box.remove_item("Gold", 4321))  # Output: Incorrect code

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!