Created
July 21, 2025 20:47
-
-
Save kebman/2039dfb6e7972e9d70ea580c9ed175d8 to your computer and use it in GitHub Desktop.
Convert Seconds β‘ to Minutes and Seconds π In various ways....
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| test_value = 116 | |
| divisor = 60 | |
| # Pythonic (best) | |
| minutes, seconds = divmod(test_value, divisor) | |
| print(f"Pythonic: {minutes}:{seconds}") | |
| # C-Style (good) | |
| minutes = test_value // divisor | |
| seconds = test_value % divisor | |
| print(f"C-Style: {minutes}:{seconds}") | |
| # Floating Point Division (nah...) | |
| minutes = int(test_value / divisor) | |
| seconds = int((test_value / divisor - minutes) * divisor) | |
| print(f"Floating Point Division: {minutes}:{seconds}") | |
| # Bit Shifting (u crazy!!!) | |
| def fast_div60(x): | |
| return (x * 43691) >> 22 | |
| def fast_mod60(x): | |
| return x - fast_div60(x) * 60 | |
| minutes = fast_div60(test_value) | |
| seconds = fast_mod60(test_value) | |
| print(f"Bit Shifting: {minutes}:{seconds}") | |
| # Faster BS (re-inventing divmod :p) | |
| def fast_divmod60(x): | |
| q = (x * 43691) >> 22 | |
| r = x - q * 60 | |
| return q, r | |
| minutes, seconds = fast_divmod60(test_value) | |
| print(f"Faster BS: {minutes}:{seconds}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment