A stream arrives in chunks of any size. Messages end with a # mark (a stand-in for a newline). Cut the stream into whole messages.
What to build
A program that reads the chunks and prints each message as soon as its end mark has arrived.
Requirements
- Keep a buffer. After each chunk is added, print
message: TEXTfor every message that is now complete, in order. The#is not part of the message. - After the last chunk, if the buffer is not empty print
partial: TEXTwith the text left over.
Input
A line with n, then n lines, each one chunk (non-empty, with no # at the end of a message that is empty).
Output
message: lines and possibly one partial: line.
Constraints
1 ≤ n ≤ 30. No message is empty.
Example
Input:
3
hel
lo#wor
ld#
Output:
message: hello
message: world
Why it works
A chunk may hold part of a message, a whole one or several, so the program must keep what it has not finished. Cutting at the mark and keeping the rest in the buffer turns any chunking of the stream into the same list of messages.
Examples
3 hel lo#wor ld#
message: hello message: world
2 ping#pong# half
message: ping message: pong partial: half
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Add each chunk to a buffer string. While the buffer contains "#", cut at the first one.
Hint 2
buffer.partition("#") gives the message, the mark and the rest.
Hint 3
After the last chunk, whatever is left in the buffer is a partial message.
Solution
Show one correct solution (try it yourself first)
n = int(input())
buffer = ""
for _ in range(n):
buffer += input()
while "#" in buffer:
message, _, buffer = buffer.partition("#")
print("message: " + message)
if buffer:
print("partial: " + buffer)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step