def continued_fraction_reduce(cf):
 from sympy.core.symbol import Dummy
 from sympy.solvers import solve
 period = []
 x = Dummy('x')
 def untillist(cf):
  for nxt in cf:
   if isinstance(nxt, list):
    period.extend(nxt)
    (yield x)
    break
   (yield nxt)
 a = Integer(0)
 for a in continued_fraction_convergents(untillist(cf)):
  pass
 if period:
  y = Dummy('y')
  solns = solve((continued_fraction_reduce((period + [y])) - y), y)
  solns.sort()
  pure = solns[(-1)]
  return a.subs(x, pure).radsimp()
 else:
  return a

def continued_fraction_reduce ( cf ) : from sympy . core . symbol import Dummy from sympy . solvers import solve period = [ ] x = Dummy ( 'x' ) def untillist ( cf ) : for nxt in cf : if isinstance ( nxt , list ) : period . extend ( nxt ) ( yield x ) break ( yield nxt ) a = Integer ( 0 ) for a in continued_fraction_convergents ( untillist ( cf ) ) : pass if period : y = Dummy ( 'y' ) solns = solve ( ( continued_fraction_reduce ( ( period + [ y ] ) ) - y ) , y ) solns . sort ( ) pure = solns [ ( - 1 ) ] return a . subs ( x , pure ) . radsimp ( ) else : return a
reduce a continued fraction to a rational or quadratic irrational .