4.2 Text history
A messaging service stores conversations in two parallel arrays:
- messages contains the text of each message
- timestamps contains the time each message was sent
The service requires a search function where the user enters a time (in hh:mm format).
The program must then:
- search through all the messages
- find every message sent at the given time
- display the message text together with the time
If no messages were sent at the chosen time, the program must display: “No messages at that time”.
messages = [
"Hey, you free after school?",
"Yeah, what's up?",
"Group project meeting at 3?",
"Works for me.",
"Cool, meet by the library doors.",
"Bring your notes please!",
"Same, see you soon.",
"On my way now."
]
timestamps = ["14:02", "14:02", "14:03", "14:03",
"14:04", "14:05", "14:28", "14:32"]
Enter a time (hh:mm): 14:03 Message at 14:03: "Group project meeting at 3?" Message at 14:03: "Works for me."
SET messages TO [...]
SET timestamps TO [...]
INPUT targetTime
SET found TO False
FOR i FROM 0 TO LENGTH(messages) - 1
IF timestamps[i] = targetTime THEN
OUTPUT "Message at " + targetTime + ": " + messages[i]
SET found TO True
END IF
END FOR
IF found = False THEN
OUTPUT "No messages at that time"
END IF
messages = [
"Hey, you free after school?",
"Yeah, what's up?",
"Group project meeting at 3?",
"Works for me.",
"Cool, meet by the library doors.",
"Bring your notes please!",
"Same, see you soon.",
"On my way now."
]
timestamps = ["14:02", "14:02", "14:03", "14:03",
"14:04", "14:05", "14:28", "14:32"]
target_time = input("Enter a time (hh:mm): ")
found = False
for i in range(len(messages)):
if timestamps[i] == target_time:
print("Message at", target_time + ":", '"' + messages[i] + '"')
found = True
if found == False:
print("No messages at that time")
# Parallel arrays: each message has a matching timestamp at the same index
messages = [
"Hey, you free after school?",
"Yeah, what's up?",
"Group project meeting at 3?",
"Works for me.",
"Cool, meet by the library doors.",
"Bring your notes please!",
"Same, see you soon.",
"On my way now."
]
timestamps = ["14:02", "14:02", "14:03", "14:03",
"14:04", "14:05", "14:28", "14:32"]
# Ask the user which time to search for
target_time = input("Enter a time (hh:mm): ")
# A flag to track if we found any messages at that time
found = False
# Search through the whole array
for i in range(len(messages)):
# If the timestamp matches the target time
if timestamps[i] == target_time:
# Print the message at that time
print("Message at", target_time + ":", '"' + messages[i] + '"')
# Set found to True because we got at least one match
found = True
# If no messages were found, show a message
if found == False:
print("No messages at that time")
Extension
Update the program to display a count of how many messages were at the entered time.
Enter a time (hh:mm): 14:03 Message at 14:03: "Group project meeting at 3?" Message at 14:03: "Works for me." 2 messages found.