Add algorithm to compute absolute age difference#13525
Add algorithm to compute absolute age difference#13525Ommodi07 wants to merge 3 commits intoTheAlgorithms:masterfrom
Conversation
|
#!/usr/bin/env python3 Calculate the absolute age difference between two people given their birthdates. Functions:
Run doctests: from datetime import date, datetime, timedelta DateLike = Union[str, date, datetime] def parse_date(value: DateLike) -> date: def _days_in_prev_month(ref: date) -> int: def absolute_age_difference(d1: DateLike, d2: DateLike) -> Tuple[int, int, int]: |
|
can you tell me in details what to do ?
…On Sun, 19 Oct 2025 at 08:29, ankit-nirala54 ***@***.***> wrote:
*ankit-nirala54* left a comment (TheAlgorithms/Python#13525)
<#13525 (comment)>
#!/usr/bin/env python3
"""
age_diff.py
Calculate the absolute age difference between two people given their
birthdates.
Functions:
- parse_date(value): parse and validate a date string (YYYY-MM-DD) or
accept datetime.date.
- absolute_age_difference(d1, d2): return (years, months, days)
difference, absolute value.
Run doctests:
python -m doctest age_diff.py -v
"""
from datetime import date, datetime, timedelta
from typing import Tuple, Union
DateLike = Union[str, date, datetime]
def parse_date(value: DateLike) -> date:
"""
Parse a date-like input into a datetime.date and validate it's not in the
future.
Accepts:
- 'YYYY-MM-DD' string
- datetime.date
- datetime.datetime
Raises:
ValueError on invalid format or if the date is in the future.
Examples
--------
>>> parse_date("2000-01-15")
datetime.date(2000, 1, 15)
>>> # invalid format
>>> try:
... parse_date("15-01-2000")
... except ValueError as e:
... print("err")
err
"""
if isinstance(value, date) and not isinstance(value, datetime):
d = value
elif isinstance(value, datetime):
d = value.date()
elif isinstance(value, str):
try:
d = datetime.strptime(value, "%Y-%m-%d").date()
except ValueError as exc:
raise ValueError(f"Date string must be YYYY-MM-DD, got: {value!r}") from exc
else:
raise ValueError(f"Unsupported date type: {type(value)}")
today = date.today()
if d > today:
raise ValueError(f"Date {d.isoformat()} is in the future (today is {today.isoformat()}).")
return d
def _days_in_prev_month(ref: date) -> int:
"""
Helper: number of days in the month preceding the month of ref.
For example, if ref is 2020-03-05 -> returns days in Feb 2020 (29).
"""
first_of_month = ref.replace(day=1)
prev_last_day = first_of_month - timedelta(days=1)
return prev_last_day.day
def absolute_age_difference(d1: DateLike, d2: DateLike) -> Tuple[int, int,
int]:
"""
Return the absolute difference between two dates as (years, months, days).
Rules:
- years is the number of full years between the two dates
- months is full months after removing years
- days is remaining days after removing years and months
Examples
--------
Same day -> zero difference:
>>> absolute_age_difference("2000-01-01", "2000-01-01")
(0, 0, 0)
Simple difference:
>>> absolute_age_difference("1990-05-10", "1995-07-15")
(5, 2, 5)
Order doesn't matter (it's absolute):
>>> absolute_age_difference("1995-07-15", "1990-05-10")
(5, 2, 5)
Leap day handling (Feb 29):
>>> absolute_age_difference("2000-02-29", "2001-02-28")
(0, 11, 30)
Another leap example across many years:
>>> absolute_age_difference("1988-02-29", "2012-02-29")
(24, 0, 0)
"""
a = parse_date(d1)
b = parse_date(d2)
# Ensure a <= b
if a > b:
a, b = b, a
# Start with year difference
years = b.year - a.year
# Adjust years if the last year is not yet a full year
if (b.month, b.day) < (a.month, a.day):
years -= 1
# For months and days, compute an "anniversary" date after removing full years
# anniversary = a advanced by `year
—
Reply to this email directly, view it on GitHub
<#13525 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/BCS6XV2CD7MJW5XPZJ6AEPT3YL5CFAVCNFSM6AAAAACJLB7WSGVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZTIMJZGE3DKNZRGA>
.
You are receiving this because you authored the thread.Message ID:
***@***.***>
|
Describe your change:
Added an algorithm to calculate absolute age difference between two people.
Includes input validation and doctests.
Fixes #13489
Checklist: