Inefficient, but still kinda fun. I used it last night as an introduction to eval( ). First I take the eval away and show the expression (growing) being generated (it's a generator).
1 + 1/(1) 1 + 1/(1+ 1/(1)) 1 + 1/(1+ 1/(1+ 1/(1))) 1 + 1/(1+ 1/(1+ 1/(1+ 1/(1)))) 1 + 1/(1+ 1/(1+ 1/(1+ 1/(1+ 1/(1))))) 1 + 1/(1+ 1/(1+ 1/(1+ 1/(1+ 1/(1+ 1/(1)))))) 1 + 1/(1+ 1/(1+ 1/(1+ 1/(1+ 1/(1+ 1/(1+ 1/(1))))))) 1 + 1/(1+ 1/(1+ 1/(1+ 1/(1+ 1/(1+ 1/(1+ 1/(1+ 1/(1)))))))) and so on. Then I switch to eval-ing the expression and, lo and behold, we're approaching phi aren't we. 2.0 1.5 1.6666666666666665 1.6 1.625 1.6153846153846154 1.619047619047619 1.6176470588235294 1.6181818181818182 1.6179775280898876 1.6180555555555556 1.6180257510729614 1.6180371352785146 1.6180327868852458 1.618034447821682 1.618033813400125 1.6180340557275543 1.6180339631667064 1.6180339985218035 1.618033985017358 Way back in the annals of edu-sig, early years, we were digging into HOW-TO re continued fractions and exploring the more optimized algorithms. Sometimes though, it's just the concepts you need -- optimization in another sense. eval( ) and exhibiting a sequence of generators was the theme. I used the pi-digits generator we talked about this September (here on edu-sig), and that one of Ramanujan's, the latter posted here yesterday in Python 3.5 version. Kirby # -*- coding: utf-8 -*- """ Created on Thu Dec 3 16:08:49 2015 @author: kurner Another generator example: converging to Phi Shows eval( ) in action """ def continued(): patt = "+ 1/(1" the_expr = '' # empty n = 1 while True: the_expr = the_expr + patt the_frac = "1 " + the_expr + ")" * n yield eval(the_frac) # or show the_frac n += 1 the_gen = continued() for _ in range(20): print(next(the_gen))
_______________________________________________ Edu-sig mailing list Edu-sig@python.org https://mail.python.org/mailman/listinfo/edu-sig