|
| 1 | +""" |
| 2 | +Algorithm to calculate the absolute age difference between two people. |
| 3 | +
|
| 4 | +Wikipedia: https://en.wikipedia.org/wiki/Chronological_age |
| 5 | +""" |
| 6 | + |
| 7 | + |
| 8 | +def age_difference(boy_age: int, girl_age: int) -> int: |
| 9 | + """ |
| 10 | + Return the absolute age difference between two people. |
| 11 | +
|
| 12 | + The function raises a ValueError if any of the ages is negative. |
| 13 | +
|
| 14 | + >>> age_difference(22, 20) |
| 15 | + 2 |
| 16 | + >>> age_difference(20, 22) |
| 17 | + 2 |
| 18 | + >>> age_difference(30, 30) |
| 19 | + 0 |
| 20 | + >>> age_difference(-1, 5) |
| 21 | + Traceback (most recent call last): |
| 22 | + ... |
| 23 | + ValueError: Age cannot be negative. |
| 24 | + >>> age_difference(18, -2) |
| 25 | + Traceback (most recent call last): |
| 26 | + ... |
| 27 | + ValueError: Age cannot be negative. |
| 28 | + """ |
| 29 | + if boy_age < 0 or girl_age < 0: |
| 30 | + raise ValueError("Age cannot be negative.") |
| 31 | + return abs(boy_age - girl_age) |
| 32 | + |
| 33 | + |
| 34 | +if __name__ == "__main__": |
| 35 | + # Example usage (not required by TheAlgorithms, but for local testing) |
| 36 | + print(age_difference(22, 20)) # 2 |
| 37 | + print(age_difference(20, 22)) # 2 |
| 38 | + print(age_difference(30, 30)) # 0 |
0 commit comments