Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

There are a few cases where the date is written as 'created ca. 1858-60', where a human reader would understand it as 'created ca 1858-1860.'

As such, imagine two integers representing years.

a = 1858
b = 60

I want to be able to get a+b == 1859.

I could parse them to strings, take the first two characters ('18'), concatinate the shorter string and parse them back to numbers, sure, but..that seems a bit round-a-bound.

What would be the Pythonic way to deal with this?

like image 339
Mitchell van Zuylen Avatar asked Nov 07 '17 21:11

Mitchell van Zuylen


1 Answers

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.

like image 157
Adam Smith Avatar answered Sep 19 '22 13:09

Adam Smith