Last active
October 23, 2025 05:58
-
-
Save WitherOrNot/20870396fbb4289d957c8342703c7fd7 to your computer and use it in GitHub Desktop.
Resistor problem on twitter https://x.com/shapoco/status/1979897758506184989
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
| from fractions import Fraction | |
| def invert(n): | |
| if n == 0: | |
| return None | |
| return Fraction(1, n) | |
| def solve(r, x): | |
| if x == 0 or x is None: | |
| return [] | |
| if x < r: | |
| a = r // x | |
| x1 = invert(invert(x) - a * invert(r)) | |
| out = (a * [[r]]) | |
| if x1: | |
| out += [solve(r, x1)] | |
| return out | |
| else: | |
| a = x // r | |
| x1 = x % r | |
| return (a * [r]) + solve(r, x1) | |
| def check(soln): | |
| r = 0 | |
| s = 0 | |
| for x in soln: | |
| if type(x) == int: | |
| r += x | |
| elif type(x) == list: | |
| s += invert(check(x)) | |
| if s == 0: | |
| return r | |
| return r + invert(s) | |
| def count(soln): | |
| c = 0 | |
| for x in soln: | |
| if type(x) == int: | |
| c += 1 | |
| elif type(x) == list: | |
| c += count(x) | |
| return c | |
| soln = solve(int(input("Resistor value: ")), int(input("Circuit resistance: "))) | |
| print(soln) | |
| print("Checked resistance:", check(soln)) | |
| print("# resistors used:", count(soln)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment