|
I come from a Python background so libraries were always just a pip install away. In the past year, however, I've been working on a large C++ codebase (couple million lines) and the result has been a considerably greater amount of "roll your own." This has filtered back into my Python. If it's not in the standard library, I don't install it unless I really need it. My boss always tells me that you can probably write it faster than a library, something I never used to believe. Until I tried it. I needed to check which of two version strings, of XX.XX.XX.XXXX format, were bigger. I tried the most recommended version number library, then I tried writing my own solution, the simplest solution I could think of: def version_compare(v1: str, v2: str) -> int:
"""
Compares two versions.
Parameters
----------
v1: str
v2: str
Returns
-------
int
1 if v1 is greater, -1 if v2 is greater, 0 if equal.
"""
for el1, el2 in zip(v1.split('.'), v2.split('.')):
if el1 != el2:
return 1 if int(el1) > int(el2) else -1
return 0
My code was faster by like 20x. Libraries are bloated and you probably only need a small subset of the functionality, so write your own code has become my mantra. |