← 返回 anthropic 的题目列表Implement a Function 'get_when' in an In-Memory Database
类型:online_judge
Implement a get_when feature in an in-memory database. Assume an in-memory database supports sequential insertion and querying. Implement a function get_when that returns the timestamp of the earliest record satisfying a condition.
Requirements:
You will receive an array of events in chronological order, each event includes a timestamp and several fields. Implement:
A method to insert events.
A method to query the earliest timestamp of an event satisfying a condition, i.e., get_when(predicate). The condition is defined by a passed function predicate(event) returning a boolean.
Input format:
event objects include fields: timestamp (an integer, representing the timestamp), data (any data type, representing other event information).
predicate is a function taking an event object as input and returning a boolean.
Output format:
The get_when method should return an integer representing the earliest timestamp of an event meeting the condition; return -1 if no such event exists.
Constraints:
Timestamps are unique and inserted in ascending order.
Up to 10^5 events.
Example:
# Suppose there is the following sequence of events
E = [
{'timestamp': 1, 'data': 'A'},
{'timestamp': 2, 'data': 'B'},
{'timestamp': 3, 'data': 'C'}
]
# Query condition
def is_event_B(event):
return event['data'] == 'B'
# get_when returns 2 because 'B' first appears at timestamp 2
Example
Input
{'timestamp': 1, 'data': 'A'} {'timestamp': 2, 'data': 'B'} {'timestamp': 3, 'data': 'C'} is_event_B B