Read a conflicted file the way you have to before resolving it.
What to build
A program that counts the conflict blocks in a file and the lines on each side.
Requirements
- Markers are lines starting with
<<<<<<<,=======and>>>>>>>; there may be text after a marker, such as a branch name. - Print
conflicts: N, thenK: ours A, theirs Bfor each block K from 1.
Input
Line 1: n. Then the n lines of the file.
Output
One summary line, then one line per conflict.
Constraints
n ≤ 1,000; markers are properly nested and closed.
Example
Input:
6
title = Notes
<<<<<<< HEAD
color = green
=======
color = red
>>>>>>> feature
Output:
conflicts: 1
1: ours 1, theirs 1
Why it works
Every conflict is delimited by the same three markers, so scanning the lines and switching between ours and theirs at each marker measures every conflict.
Examples
Example 1 · Input
6 title = Notes <<<<<<< HEAD color = green ======= color = red >>>>>>> feature
Expected output
conflicts: 1 1: ours 1, theirs 1
Example 2 · Input
2 no conflicts here just text
Expected output
conflicts: 0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
A line starting with <<<<<<< opens a block, ======= switches from ours to theirs, and >>>>>>> closes it.
Hint 2
Count the lines on each side of every block.
Solution
Show one correct solution (try it yourself first)
lines = [input() for _ in range(int(input()))]
blocks, side = [], None
for line in lines:
if line.startswith("<<<<<<<"):
blocks.append([0, 0])
side = 0
elif line.startswith("=======") and side == 0:
side = 1
elif line.startswith(">>>>>>>"):
side = None
elif side is not None:
blocks[-1][side] += 1
print("conflicts:", len(blocks))
for k, (a, b) in enumerate(blocks, start=1):
print(f"{k}: ours {a}, theirs {b}")