Count what a diff adds and removes, like git diff --stat.
What to build
A program that reads a diff and summarizes the insertions and deletions per file and in total.
Requirements
- For each file, print
path +A -D. Then print a summary like Git's:N file(s) changed, followed by, A insertion(s)(+)if A > 0 and, D deletion(s)(-)if D > 0, using the singular for 1 (1 file changed,1 insertion(+),1 deletion(-)).
Input
Line 1: n. Then the n lines of the diff.
Output
One line per file, then the summary.
Constraints
n ≤ 1,000.
Example
Input:
8
diff --git a/app.py b/app.py
--- a/app.py
+++ b/app.py
@@ -1,2 +1,3 @@
import sys
-print("hi")
+print("hello")
+print("bye")
Output:
app.py +2 -1
1 file changed, 2 insertions(+), 1 deletion(-)
Why it works
Every added line starts with + and every removed line with −, so counting them per file gives the size of the change.
Examples
Example 1 · Input
8
diff --git a/app.py b/app.py
--- a/app.py
+++ b/app.py
@@ -1,2 +1,3 @@
import sys
-print("hi")
+print("hello")
+print("bye")
Expected output
app.py +2 -1 1 file changed, 2 insertions(+), 1 deletion(-)
Example 2 · Input
10 diff --git a/a.txt b/a.txt --- a/a.txt +++ b/a.txt @@ -1 +1 @@ +new line diff --git a/b.txt b/b.txt --- a/b.txt +++ b/b.txt @@ -1 +0,0 @@ -old line
Expected output
a.txt +1 -0 b.txt +0 -1 2 files changed, 1 insertion(+), 1 deletion(-)
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
A line starting with `diff --git a/` starts a new file; take the path after `a/`.
Hint 2
Lines starting with `+++` or `---` are file headers; other lines starting with `+` or `-` are insertions and deletions.
Solution
Show one correct solution (try it yourself first)
lines = [input() for _ in range(int(input()))]
files = []
for line in lines:
if line.startswith("diff --git a/"):
files.append([line.split()[2][2:], 0, 0])
elif line.startswith("+++") or line.startswith("---"):
continue
elif line.startswith("+") and files:
files[-1][1] += 1
elif line.startswith("-") and files:
files[-1][2] += 1
for path, a, d in files:
print(f"{path} +{a} -{d}")
total_a = sum(f[1] for f in files)
total_d = sum(f[2] for f in files)
summary = f"{len(files)} file{'s' if len(files) != 1 else ''} changed"
if total_a:
summary += f", {total_a} insertion{'s' if total_a != 1 else ''}(+)"
if total_d:
summary += f", {total_d} deletion{'s' if total_d != 1 else ''}(-)"
print(summary)