Taking the average of two years, written as [1858-60]

This version works entirely with integers and handles cross-century boundaries:

def year_range_average(a, b):
    return a + (b - (a % 100) + 100) % 100 // 2

>>> year_range_average(1858, 60)
1859
>>> year_range_average(1858, 61)
1859
>>> year_range_average(1858, 62)
1860
>>> year_range_average(1898, 2)
1900

I think you're going about this wrong. The easier approach is to add the century to b, then use them as normal numbers now that they're equatable.

def add_century(n: int, from_century=1900) -> int:
    """add_century turns a two-digit year into a four-digit year.

    takes a two-digit year `n` and a four-digit year `from_century` and
    adds the leading two digits from the latter to the former.
    """

    century = from_century // 100 * 100
    return century + n

Then you can do:

a, b = 1858, 60
b = add_century(b, from_century=a)
result = (a + b) / 2

Treating the numbers this way provides two benefits.

First of all, you clarify the edge case you might have. Explicitly adding the century from one onto the ending years from the other makes it very clear what's happened if the code should return the wrong result.

Secondly, transforming objects into equatable terms isn't just a good idea, it's required in languages that are, shall we say, less accepting than Python is. A quick transformation so two items are equatable is an easy way to make sure you're not confusing things down the road.

Tags:

Python