diff --git a/README.md b/README.md index 39bd2bc..8e0c4d6 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ working across different projects via [VisualMode](https://www.visualmode.dev/). For a steady stream of TILs, [sign up for my newsletter](https://visualmode.kit.com/newsletter). -_1788 TILs and counting..._ +_1789 TILs and counting..._ See some of the other learning resources I work on: @@ -1064,6 +1064,7 @@ If you've learned something here, support my efforts writing daily TILs by - [Dunder Methods](python/dunder-methods.md) - [Easy Key-Value Aggregates With defaultdict](python/easy-key-value-aggregates-with-defaultdict.md) - [Get Absolute Seconds From `timedelta` Object](python/get-absolute-seconds-from-timedelta-object.md) +- [Get Quotient And Remainder In One Operation](python/get-quotient-and-remainder-in-one-operation.md) - [Install With PIP For Specific Interpreter](python/install-with-pip-for-specific-interpreter.md) - [Iterate First N Items From Enumerable](python/iterate-first-n-items-from-enumerable.md) - [Iterate Over A Dictionary](python/iterate-over-a-dictionary.md) diff --git a/python/get-quotient-and-remainder-in-one-operation.md b/python/get-quotient-and-remainder-in-one-operation.md new file mode 100644 index 0000000..efa5c40 --- /dev/null +++ b/python/get-quotient-and-remainder-in-one-operation.md @@ -0,0 +1,42 @@ +# Get Quotient And Remainder In One Operation + +While writing some custom code to transform a number of seconds into the +constituent hours, minutes, and seconds, I found myself needing to get both the +quotient and remainder from a division between two numbers. + +```python +>>> import math +>>> math.floor(3666 / 3600) +1 +>>> 3666 % 3600 +66 +``` + +Instead, I can use Python's built-in +[`divmod`](https://docs.python.org/3/library/functions.html#divmod) function to +compute both values in one statement. + +```python +>>> divmod(3666, 3600) +(1, 66) +``` + +The result is a tuple with the first value being my quotient (in this case, the +number of hours) and the remainder (the remaining number of seconds). + +This kind of operation is known as [Euclidian +Division](https://en.wikipedia.org/wiki/Euclidean_division). + +Here is a snippet of some actual code where I use this in +[`py-vmt`](https://github.com/jbranchaud/py-vmt/blob/b9eae8b258e9fd720cfa3bb63b601225df352051/src/py_vmt/time_helpers.py#L14-L16): + +```python +def format_time_delta(diff: timedelta) -> str: + total_seconds = int(diff.total_seconds()) + + hours, remainder = divmod(total_seconds, 3600) + minutes, remainder = divmod(remainder, 60) + seconds = remainder + + # ... +```