Commit 6565321
authored
Here is a **faster and more memory efficient version** of your code, re-written for optimal runtime and minimal temporary allocations.
The biggest optimizations are.
- **Avoid repeated f-string formatting per branch by leveraging intermediate integer math and tuple lookups.**
- **Minimize float conversion and string formatting: use integer division and only format floats where necessary.**
- Avoid unnecessary chained if/else expressions by using nested conditionals.
- Direct return, not temporary assignment, for common usage (early-out).
- Minimize creation of temporary float objects (division is only triggered at last possible moment, and only when needed).
The result string is exactly as before.
Input type and value checks are retained as in the original.
**Key speedups**.
- Uses integer division as long as possible (which is faster and avoids floats).
- Avoids repeated float formatting and f-string interpolation: Only floats and formatting are used when output would need decimals.
- No temporary assignments except where actually needed.
- No nested ternaries to reduce overhead and branch ambiguity.
**Result:**
This version produces exactly the same outputs as the original, but should be significantly faster and use less memory (notably in the most common branch calls).
You can further accelerate by removing or altering input type checks if running in a controlled environment.
1 parent 47fa9c4 commit 6565321
1 file changed
+31
-7
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
55 | 55 | | |
56 | 56 | | |
57 | 57 | | |
58 | | - | |
| 58 | + | |
59 | 59 | | |
60 | 60 | | |
61 | 61 | | |
62 | 62 | | |
63 | 63 | | |
| 64 | + | |
64 | 65 | | |
65 | 66 | | |
66 | 67 | | |
67 | | - | |
68 | | - | |
| 68 | + | |
| 69 | + | |
| 70 | + | |
| 71 | + | |
| 72 | + | |
| 73 | + | |
| 74 | + | |
| 75 | + | |
| 76 | + | |
| 77 | + | |
| 78 | + | |
| 79 | + | |
69 | 80 | | |
70 | | - | |
71 | | - | |
72 | | - | |
73 | | - | |
| 81 | + | |
| 82 | + | |
| 83 | + | |
| 84 | + | |
| 85 | + | |
| 86 | + | |
| 87 | + | |
| 88 | + | |
| 89 | + | |
| 90 | + | |
| 91 | + | |
| 92 | + | |
| 93 | + | |
| 94 | + | |
| 95 | + | |
| 96 | + | |
| 97 | + | |
74 | 98 | | |
75 | 99 | | |
76 | 100 | | |
| |||
0 commit comments