Skip to content

Instantly share code, notes, and snippets.

@WitherOrNot
Last active October 23, 2025 05:58
Show Gist options
  • Select an option

  • Save WitherOrNot/20870396fbb4289d957c8342703c7fd7 to your computer and use it in GitHub Desktop.

Select an option

Save WitherOrNot/20870396fbb4289d957c8342703c7fd7 to your computer and use it in GitHub Desktop.
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