← 返回 anthropic 的题目列表Python Class and Data Structures
类型:online_judge
Create a Python class that uses lists, dictionaries, and sets to implement certain functionalities including sorting, hashing, and binary search. Implement the following methods:
add_item(item): Adds an item to the set.
remove_item(item): Removes an item from the set if it exists.
sort_items(): Returns a list of all items in sorted order.
hash_items(): Returns a dictionary with items as keys and their hash values as values.
binary_search(item): Returns the index of the item in the sorted list using binary search, or -1 if not found.
Test Cases:
# Example inputs/outputs:
Example 1:
add_item(2)
add_item(3)
add_item(1)
sort_items() -> [1, 2, 3]
hash_items() -> {1: hash(1), 2: hash(2), 3: hash(3)}
binary_search(2) -> 1
remove_item(3)
sort_items() -> [1, 2]
Example 2:
add_item(10)
add_item(5)
add_item(8)
sort_items() -> [5, 8, 10]
binary_search(10) -> 2
remove_item(5)
sort_items() -> [8, 10]
remove_item(7) # No change
Example 3:
add_item(5)
add_item(5)
sort_items() -> [5]
binary_search(1) -> -1
hash_items() -> {5: hash(5)}
Example
Input
add_item(2)
add_item(3)
add_item(1)
sort_items()
hash_items()
binary_search(2)
remove_item(3)
sort_items()
Output
[1, 2, 3]
{1: hash(1), 2: hash(2), 3: hash(3)}
1
[1, 2]