Before you compare versions, you must read them. Parse semantic version numbers.
What to build
A program that reads version numbers and prints their parts, or says they are invalid.
Requirements
- A valid version has exactly three parts separated by dots. Each part is made only of digits, is not empty, and has no leading zero unless it is exactly
0. - For a valid version print
VERSION: major=A minor=B patch=C. - Otherwise print
VERSION: invalid.
Input
The first line has n (1 to 50). Each of the next n lines is a version (spaces at the ends are removed).
Output
n lines.
Constraints
1 ≤ n ≤ 50.
Example
Input:
3
1.4.2
2.0
1.10.0
Output:
1.4.2: major=1 minor=4 patch=2
2.0: invalid
1.10.0: major=1 minor=10 patch=0
Why it works
Splitting at the dots turns the text into its parts, and each part must pass the same small test, so a single helper function decides whether the whole version is valid.
Examples
3 1.4.2 2.0 1.10.0
1.4.2: major=1 minor=4 patch=2 2.0: invalid 1.10.0: major=1 minor=10 patch=0
2 0.0.1 1.2.3.4
0.0.1: major=0 minor=0 patch=1 1.2.3.4: invalid
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Split the text with version.split(".") and check that there are exactly 3 parts.
Hint 2
part.isdigit() checks that a part has only digits, and a part like "01" has a leading zero.
Hint 3
Print invalid if any check fails.
Solution
Show one correct solution (try it yourself first)
def valid_part(part):
return part.isdigit() and (part == "0" or not part.startswith("0"))
n = int(input())
for _ in range(n):
version = input().strip()
parts = version.split(".")
if len(parts) == 3 and all(valid_part(p) for p in parts):
print(f"{version}: major={parts[0]} minor={parts[1]} patch={parts[2]}")
else:
print(f"{version}: invalid")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step