Before you send a change, read its diff. git diff --stat summarises it; write that summary.
What to build
A program that counts the added and removed lines in a unified diff.
Requirements
- A line starting with
diff --git a/NAME b/NAMEbegins the diff of file NAME. Lines starting with+++or---are file headers and are ignored. Any other line starting with+is an insertion and any other line starting with-is a deletion for the current file; all other lines are ignored. - Print
NAME | +I -Dfor each file in the order of appearance. - Finally print
F file(s) changed, I insertion(s), D deletion(s).
Input
The first line has n (1 to 200). The next n lines are the diff.
Output
One line per file, then the summary line.
Constraints
1 ≤ n ≤ 200. The diff has at least one file.
Example
Input:
10
diff --git a/average.py b/average.py
--- a/average.py
+++ b/average.py
@@ -1,3 +1,5 @@
def average(numbers):
+ if not numbers:
+ return 0
return sum(numbers) / len(numbers)
-
print(average([4, 8, 6]))
Output:
average.py | +2 -1
1 file(s) changed, 2 insertion(s), 1 deletion(s)
Why it works
Every line belongs to the file whose header came last, so a running current file and two counters per file are enough; skipping the three-character headers keeps them out of the counts.
Examples
10
diff --git a/average.py b/average.py
--- a/average.py
+++ b/average.py
@@ -1,3 +1,5 @@
def average(numbers):
+ if not numbers:
+ return 0
return sum(numbers) / len(numbers)
-
print(average([4, 8, 6]))
average.py | +2 -1 1 file(s) changed, 2 insertion(s), 1 deletion(s)
8 diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -1 +1 @@ -Wordfreq +# Wordfreq diff --git a/LICENSE b/LICENSE +MIT
README.md | +1 -1 LICENSE | +1 -0 2 file(s) changed, 2 insertion(s), 1 deletion(s)
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
A line "diff --git a/NAME b/NAME" starts a new file; NAME is line.split()[2][2:].
Hint 2
Skip lines that start with "+++" or "---" before testing for "+" and "-".
Hint 3
Keep the files in the order they appear and add up the totals.
Solution
Show one correct solution (try it yourself first)
n = int(input())
files = []
stats = {}
current = None
for _ in range(n):
line = input()
if line.startswith("diff --git "):
current = line.split()[2][2:]
files.append(current)
stats[current] = [0, 0]
elif line.startswith("+++") or line.startswith("---"):
continue
elif line.startswith("+") and current:
stats[current][0] += 1
elif line.startswith("-") and current:
stats[current][1] += 1
total_add = total_del = 0
for name in files:
added, removed = stats[name]
total_add += added
total_del += removed
print(f"{name} | +{added} -{removed}")
print(f"{len(files)} file(s) changed, {total_add} insertion(s), {total_del} deletion(s)")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step