Many projects put one SPDX line at the top of every source file. Read it back.
What to build
A program that finds the license identifier in the header of a source file.
Requirements
- Look only at the first 5 lines of the file. Use the first line that contains
SPDX-License-Identifier:; the license is the text after the colon, without spaces at the ends. - If the license is
MIT,Apache-2.0,BSD-3-Clause,GPL-3.0,LGPL-3.0orAGPL-3.0, printlicense: ID. For any other text printlicense: ID (unknown). - If there is no such line in the first 5 lines, print
no license header.
Input
The first line has n (1 to 100). The next n lines are the file.
Output
One line.
Constraints
1 ≤ n ≤ 100.
Example
Input:
4
# SPDX-License-Identifier: MIT
import os
print(os.getcwd())
Output:
license: MIT
Why it works
Header checks only need the top of the file, so slicing the first 5 lines is enough; partition splits the line at the marker and the stripped remainder is the identifier.
Examples
4 # SPDX-License-Identifier: MIT import os print(os.getcwd())
license: MIT
3
import os
print(os.getcwd())
print("done")
no license header
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Only the first 5 lines count: lines[:5].
Hint 2
Use line.partition("SPDX-License-Identifier:") and strip the text after it.
Hint 3
Stop at the first header you find.
Solution
Show one correct solution (try it yourself first)
KNOWN = ["MIT", "Apache-2.0", "BSD-3-Clause", "GPL-3.0", "LGPL-3.0", "AGPL-3.0"]
n = int(input())
lines = [input() for _ in range(n)]
result = "no license header"
for line in lines[:5]:
before, marker, after = line.partition("SPDX-License-Identifier:")
if marker:
ident = after.strip()
result = f"license: {ident}" if ident in KNOWN else f"license: {ident} (unknown)"
break
print(result)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step