Git: What changed between two commits?

Compare two snapshots the way git diff --name-status does.

What to build

A program that lists the files added, deleted and modified between two snapshots of a project.

Requirements

  • Each snapshot is a list of files with their contents. Compare the old snapshot with the new one.
  • Print A path, D path or M path for each changed file, sorted by path; print no changes if there are none.

Input

Line 1: a. Then a lines path content for the old snapshot. Then b and b lines for the new snapshot.

Output

One line per changed file, or no changes.

Constraints

a, b ≤ 200; paths and contents have no spaces.

Example

Input:

2
README.md hello
tasks.txt milk
2
tasks.txt milk,report
notes.txt idea

Output:

D README.md
A notes.txt
M tasks.txt

Why it works

Since every commit is a full snapshot, the changes between two commits are found by comparing their file lists and contents.

Examples

Example 1 · Input
2
README.md hello
tasks.txt milk
2
tasks.txt milk,report
notes.txt idea
Expected output
D README.md
A notes.txt
M tasks.txt
Example 2 · Input
1
a.txt 1
1
a.txt 1
Expected output
no changes

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Put each snapshot in a dictionary from file name to content.

Hint 2

Added files are only in the new snapshot, deleted files only in the old one, and modified files are in both with different contents.

Solution

Show one correct solution (try it yourself first)
old = dict(input().split() for _ in range(int(input())))
new = dict(input().split() for _ in range(int(input())))
lines = []
for path in sorted(set(old) | set(new)):
    if path not in old:
        lines.append(f"A {path}")
    elif path not in new:
        lines.append(f"D {path}")
    elif old[path] != new[path]:
        lines.append(f"M {path}")
print("\n".join(lines) if lines else "no changes")

Lesson: Version control and your first repository →