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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With