From urnerk@qwest.net Sat Mar 1 19:39:26 2003 From: urnerk@qwest.net (Kirby Urner) Date: Sat, 01 Mar 2003 11:39:26 -0800 Subject: [Edu-sig] Introspection + sets In-Reply-To: <1046255362.3e5c9702cd786@mbox.slu.edu.ph> Message-ID: <5.2.0.9.0.20030301113515.02168fa8@pop.ptld.qwest.net> Here's a way to abet exploration of Python primitives using introspection with sets, new in 2.3: >>> import sets >>> j = sets.Set(dir([])) # j is set of list methods >>> k = sets.Set(dir({})) # k is set of dictionary methods >>> j.intersection(k) # what lists and dictionaries have in common Set(['__ne__', '__getitem__', '__getattribute__', '__str__', '__reduce__', 'pop', '__setitem__', '__gt__', '__lt__', '__eq__', '__init__', '__delitem__', '__setattr__', '__reduce_ex__', '__new__', '__contains__', '__iter__', '__class__', '__delattr__', '__le__', '__len__', '__hash__', '__doc__', '__ge__', '__repr__']) >>> j.difference(k) # what lists have that dictionaries do not Set(['sort', 'index', '__getslice__', '__delslice__', '__imul__', 'extend', 'insert', '__setslice__', 'count', 'remove', '__mul__', '__iadd__', '__add__', '__rmul__', 'append', 'reverse']) >>> k.difference(j) # what dictionaries have that lists do not Set(['fromkeys', 'setdefault', 'get', 'keys', 'items', 'clear', 'popitem', 'update', '__cmp__', 'has_key', 'values', 'itervalues', 'iteritems', 'copy', 'iterkeys']) Kinda fun. Suggestive. Kirby From urnerk@qwest.net Sat Mar 1 23:48:59 2003 From: urnerk@qwest.net (Kirby Urner) Date: Sat, 01 Mar 2003 15:48:59 -0800 Subject: [Edu-sig] Plain vanilla (Stirling numbers) In-Reply-To: <5.2.0.9.0.20030301113515.02168fa8@pop.ptld.qwest.net> References: <1046255362.3e5c9702cd786@mbox.slu.edu.ph> Message-ID: <5.2.0.9.0.20030301153727.01144da8@pop.ptld.qwest.net> Stirling numbers add row-wise sort of like Pascal's Triangle, except there's a multiplier at work on the first of each pair of terms to be added. Generators work well to give successive rows, while wrappers control iteration, such that row, column (n,k) value may be returned. Stirling numbers of the 2nd type give the number of ways you can divide n elements into k non-empty subsets, while those of the 1st type give the number of ways you can arrange n elements into k unique cycles or "necklaces" (order matters). Examples: >>> from concrete import * >>> subsets(4,2) # 4 things maybe be divided into 2 sets 7 ways 7 >>> cycles(4,2) # but more cycles, as subsets of 3 have 2 cycles 11 The implementation below also makes use of the enumerate() iterator, new in 2.3, list comprehensions, and the built-in zip function. ==================================== # Stirling Numbers # See: Graham, Knuth, Patashnik, Concrete Mathematics # (Addison-Wesley, 2nd Ed., 1994), pg.258-261 # Kirby Urner, Oregon Curriculum Network, March 1, 2003 def stirling2(): """ Generate next row of Stirling numbers of type 2 """ row = [1] yield row while True: mrow = [ i*j for (i,j) in enumerate(row) ] row = [ i+j for (i,j) in zip(mrow + [0], [0] + row) ] yield row def stirling1(): """ Generate next row of Stirling numbers of type 1 """ row = [1] yield row while True: n = len(row) mrow = [ i * (n-1) for i in row ] row = [ i+j for (i,j) in zip(mrow + [0], [0] + row) ] yield row def subsets(n,k): """ Number of ways to partition a set of n things into k nonempty subsets """ if n==0: return 1 if k==1: return 1 s = stirling2() for i in range(n+1): r = s.next() return r[k] def cycles(n,k): """ Number of ways to arrange n objects into k cycles """ if n==0: return 1 if k==1: return 1 s = stirling1() for i in range(n+1): r = s.next() return r[k] From wilson@visi.com Mon Mar 3 04:32:30 2003 From: wilson@visi.com (Tim Wilson) Date: Sun, 2 Mar 2003 22:32:30 -0600 Subject: [Edu-sig] Simple simulation exercises Message-ID: <200303022232.30080.wilson@visi.com> Hi everyone, My students have been working on OOP for a few weeks now, and I think many of them are ready to dig into a little meatier project. My first thought was some sort of a simulation problem. (I just read the article referenced in the Daily Python-URL. Good timing. [1]) I'm looking for ideas. What sort of simulation exercise is effective for beginning programmers. I seem to recall working on a traffic simulation years ago in college. But I don't remember the implementation details at all anymore. Thoughts? -Tim [1] Mueller, Klaus and Tony Vignaux, SimPy: Simulating Systems in Python, http://www.onlamp.com/pub/a/python/2003/02/27/simpy.html -- Tim Wilson Twin Cities, Minnesota, USA Science teacher, Linux fan, Zope developer, Grad. student, Daddy mailto:wilson@visi.com | http://qwerk.org/ | public key: 0x8C0F8813 From urnerk@qwest.net Mon Mar 3 05:26:23 2003 From: urnerk@qwest.net (Kirby Urner) Date: Sun, 02 Mar 2003 21:26:23 -0800 Subject: [Edu-sig] Simple simulation exercises In-Reply-To: <200303022232.30080.wilson@visi.com> Message-ID: <5.2.0.9.0.20030302211430.02132488@pop.ptld.qwest.net> At 10:32 PM 3/2/2003 -0600, you wrote: >Thoughts? > >-Tim Here's a weird little simulation I posted to this list three years ago: http://mail.python.org/pipermail/edu-sig/2000-April/000306.html -- not nearly so cool as simpy: http://simpy.sourceforge.net/ -- similar ideas though. Kirby >[1] Mueller, Klaus and Tony Vignaux, SimPy: Simulating Systems in Python, >http://www.onlamp.com/pub/a/python/2003/02/27/simpy.html > >-- >Tim Wilson >Twin Cities, Minnesota, USA >Science teacher, Linux fan, Zope developer, Grad. student, Daddy >mailto:wilson@visi.com | http://qwerk.org/ | public key: 0x8C0F8813 From urnerk@qwest.net Mon Mar 3 06:01:37 2003 From: urnerk@qwest.net (Kirby Urner) Date: Sun, 02 Mar 2003 22:01:37 -0800 Subject: [Edu-sig] Another fractal In-Reply-To: <5.2.0.9.0.20030301153727.01144da8@pop.ptld.qwest.net> References: <5.2.0.9.0.20030301113515.02168fa8@pop.ptld.qwest.net> <1046255362.3e5c9702cd786@mbox.slu.edu.ph> Message-ID: <5.2.0.9.0.20030302214513.011984f8@pop.ptld.qwest.net> The code below produces a decent graphic of the Mandelbrot Set, when run through Povray, the free ray tracer (Windows, Linux and more). It's not at all fast, but then the code is straightforward, meaning it's accessible to someone fairly new to Python. No modules are imported. It's all built-in stuff. Mixing Python and Povray is an old favorite around here. This is good for still pictures. For dynamic stuff, OpenGL is more the way to go (ala VPython), or perhaps PyGame. Faster fractal calcs would involve using the Numeric package, or at least a numeric array (from the array module) vs. a huge generic list as below. Or, better, since the results get saved in Povray, there's no need for a persistent complex plane of any kind -- just a loop in a loop would do the job (very standard procedural stuff). Kirby Here's the result: http://www.inetarena.com/~pdx4d/ocn/python/mandelbrot.png (cropped) See also: http://www.inetarena.com/~pdx4d/ocn/fractal.html (different code, requiring additional modules) ==================== def mandelbrot(): outfile = open("test2.pov",'w') header(outfile) # create complex plane cplane = [(x/200.0,y/200.0) for x in range(-400,401) for y in range(-400,401)] for x,y in cplane: c = complex(x,y) z = 0 i = 0 done = False while not done: i += 1 z = z*z + c if i > 999: # convergent -- color black done = True sphcolor = "rgb <%s, %s, %s>" % (0,0,0) elif abs(z)>1e6: # divergent, compute color from iterations so far done = True r,g,b = str(i).zfill(3) sphcolor = "rgb <0.%s, 0.%s, 0.%s>" % (r,g,b) if done: # write the colored sphere, move on to the next one povline = """sphere{<%s, %s, %s>, 0.01 texture{pigment {color %s} } no_shadow}\n""" \ % (x,y,0,sphcolor) outfile.write(povline) outfile.close() def header(wfile): """ Standard Povray file header with some custom settings """ wfile.write(""" //POV-Ray script //version 3.1 global_settings { assumed_gamma 2.2 } #include "colors.inc" #declare Cam_factor =8; #declare Camera_X = -1.0; #declare Camera_Y = 0; #declare Camera_Z = 1 * Cam_factor; camera { location up <0, 1.0, 0> right <-4/3, 0, 0> direction <-1, 0, 3> look_at <-1, 0, 0> rotate <0,0,0>} light_source { color White } light_source { color White } light_source { color White } """) From reavey@nep.net Wed Mar 5 00:40:38 2003 From: reavey@nep.net (reavey) Date: Tue, 04 Mar 2003 19:40:38 -0500 Subject: [Edu-sig] simula.run(40) error Message-ID: <3E654786.4040308@nep.net> errors running your simulation program. python 2.2 if I run 4 ticks no problem I tried 400 ticks went out around 11 and died. --- Tick 2 ------- Duck6 gets eaten by Wolf1 Duck6 dies Wolf2 gives birth Wolf3 is born Duck4 gives birth Duck7 is born Duck5 goes hungry Bug4 goes hungry Bug5 dies Bug2 dies Duck6 dies Traceback (most recent call last): File "", line 1, in ? File "simula.py", line 16, in run i.randevent() File "simula.py", line 76, in randevent else: self.dies() # ... or die File "simula.py", line 49, in dies del creatures[self.name] # Goodbye World! KeyError: Duck6 I like your program. beautiful idea. what is this error? thanks re-v From ajsiegel@optonline.net Tue Mar 4 03:32:23 2003 From: ajsiegel@optonline.net (Arthur) Date: Mon, 03 Mar 2003 22:32:23 -0500 Subject: [Edu-sig] Towers of Hanoi Message-ID: <000501c2e1fe$ac613630$2002a8c0@Arts> Proof of concept: Ruth Chabay's Tower of Hanoi VPython demo as a Windows executable. http://www.dstoys.org/Members/ajsiegel/TowerSetup/file_view The executable created using Python distutils together with py2exe. Uses Inno Setup to create an easy install, unistall of the executable and dependencies. (Wanted to get hands-on with it) Even used the VPython export to Povray facility to create a cute desktop icon for it. Button 1 pressed to pick and move the rings. Art From urnerk@qwest.net Tue Mar 4 03:36:30 2003 From: urnerk@qwest.net (Kirby Urner) Date: Mon, 03 Mar 2003 19:36:30 -0800 Subject: [Edu-sig] simula.run(40) error In-Reply-To: <3E654786.4040308@nep.net> Message-ID: <5.2.0.9.0.20030303174844.02289cc0@pop.ptld.qwest.net> At 07:40 PM 3/4/2003 -0500, reavey wrote: >errors running your simulation program. >python 2.2 <> >I like your program. >beautiful idea. what is this error? >thanks >re-v Yes, I see I made a very common mistake, in my run() loop: for i in creatures.values(): i.randevent() The problem here is creatures.values() gets run once, and then i iterates over this snapshot of what's in the creatures dictionary. However, in the meantime, randevent(i) may result in the death and removal of a given creature. So when i iterates over the snapshot to the next value, it may no longer exist. There are several ways to fix this. One is to do a confirmation check inside the loop, skipping i.randevent() if the creature is no longer present: for i in creatures.values(): if i in creatures.values(): i.randevent() Another approach is to simply catch the error and go on as if nothing had happened: for i in creatures.values(): try: i.randevent() except: pass I like this 2nd solution better because it doesn't keep trying to find i in what in principle could be a long list. This wasn't the only bug however. Inside the Creature class was the following: if self.stomach == 0: # 3 strikes and you're out print self.name + " starves" self.die() # <--- oops! But die() is not a method -- should have been self.dies() Lastly, what's true about this ecosystem is it's predisposed to kill everyone off. As written, I don't think you'll ever get anywhere close to 100 cycles. To get any new creatures you have to already have some -- they don't wander in from "off stage" as it were. So once everything is dead, there's not going to be further activity. Rather than show all the no-activity ticks, it makes more sense to just quit the simulation once all the creatures are gone: So my run() method now looks like this: def run(n): setstage() for j in range(n): # time spans print "--- Tick %s -------" % j for i in creatures.values(): try: i.randevent() # skip the dead except: pass if len(creatures.values())==0: # all dead break Thanks for pointing out the error of my ways. If you like this little simulation, you could have some fun tweaking it. Perhaps if death were not randomly invoked, such that only being eaten or starving caused it, maybe along with some dying of old age pegged to a life clock -- e.g. if self.lifespan>50: self.dies() -- then creatures would persist long enough to keep this ecosystem steady state or growing. Kirby From urnerk@qwest.net Tue Mar 4 03:46:20 2003 From: urnerk@qwest.net (Kirby Urner) Date: Mon, 03 Mar 2003 19:46:20 -0800 Subject: [Edu-sig] Towers of Hanoi In-Reply-To: <000501c2e1fe$ac613630$2002a8c0@Arts> Message-ID: <5.2.0.9.0.20030303194243.02345a78@pop.ptld.qwest.net> At 10:32 PM 3/3/2003 -0500, Arthur wrote: >Proof of concept: > >Ruth Chabay's Tower of Hanoi VPython demo as a Windows executable. > >http://www.dstoys.org/Members/ajsiegel/TowerSetup/file_view I'll give that a different URL: http://www.dstoys.com/content/education/index_html/Visual%20Arts/Interactive dstoys.org is a community portal requiring an account. However, once a community resource is published, it becomes world-accessible through dstoys.com When you submitted this resource for publication, it went into a workflow queue. An editor had to give final approval -- in this case me. So now people may check it out without needing to join dstoys.org (although that's certainly an option, for those with more than a casual interest in design science). Note that all this is handled through Plone, which sits atop the Content Management Framework (CMF) which sits atop Zope, the web application server -- which sits atop Python! (which sits atop C which...) Kirby From urnerk@qwest.net Tue Mar 4 03:54:34 2003 From: urnerk@qwest.net (Kirby Urner) Date: Mon, 03 Mar 2003 19:54:34 -0800 Subject: [Edu-sig] Speaking of errors... In-Reply-To: <3E654786.4040308@nep.net> Message-ID: <5.2.0.9.0.20030303194944.0112f128@pop.ptld.qwest.net> re-v -- I'm interested in the date stamp of your email, which reads: Date: Tue, 04 Mar 2003 19:40:38 -0500 From: "reavey" I don't see you can already be most of the way through tomorrow and yet be 5 hrs behind Greenwich mean time. I'm 8 hrs behind (Pacific Time, USA) and am still ploughing through Monday, 03 Mar. Kirby From ajsiegel@optonline.net Tue Mar 4 03:58:11 2003 From: ajsiegel@optonline.net (Arthur) Date: Mon, 03 Mar 2003 22:58:11 -0500 Subject: [Visualpython-users] Re: [Edu-sig] Towers of Hanoi References: <5.2.0.9.0.20030303194243.02345a78@pop.ptld.qwest.net> Message-ID: <002001c2e202$46d19ef0$2002a8c0@Arts> > I'll give that a different URL: > > http://www.dstoys.com/content/education/index_html/Visual%20Arts/Interactive > > dstoys.org is a community portal requiring an account. However, once a > community resource is published, it becomes world-accessible through > dstoys.com > > When you submitted this resource for publication, it went into a workflow > queue. An editor had to give final approval -- in this case me. Nice to have an in with the editor. I wondered about this, since this is the first time I tried to publish anything at dstoys. Tested it by signing out, and reentering the url, and it let me through. Cookie? > So now people may check it out without needing to join dstoys.org (although that's > certainly an option, for those with more than a casual interest in design > science). Thanks for making it available. > > Note that all this is handled through Plone, which sits atop the Content > Management Framework (CMF) which sits atop Zope, the web application > server -- which sits atop Python! (which sits atop C which...) I'm not generally a wiki type guy. but I'm finding this interface really, really nice. And have just begun to explore some of its possiblities. Art From ajsiegel@optonline.net Tue Mar 4 15:10:19 2003 From: ajsiegel@optonline.net (Arthur) Date: Tue, 04 Mar 2003 10:10:19 -0500 Subject: [Edu-sig] Fw: [Visualpython-users] Towers of Hanoi Message-ID: <000701c2e260$2bf6d650$2002a8c0@Arts> Forward of my post to the VPython list. As I get more familiar with the capabilities of distutils, supplemented as necessary by a full featured Installer like Inno Setup, the idea of a Python "runtime" - at least for a specific "app" like VPython scripts becomes, I think intriguing. The small size of the distribution is particularly impressive considering the fact of the dependencies on Numeric and VPython as well as on the standard Python files and moudles. A simple way to share one's Python based efforts with a very broad base of folks, is - potentially - a Very Good Thing. FWIW, the acutal VPython script that created what I think is a very impressive Tower of Hanoi implementation, is less than 75 lines of code. (Again, not my work) The script is included in the "executable" distribution. But of course it is built on top of VPython and Numeric and Python and C, etc - like Plone, but different. I have a small worry of running afoul of licensing issues by going down this road - only because I don't understand much about the subject, and it seems to be a quagmire even for people who do. I guess I will continue, and if anyone is offended by what I am trying to do, I will hear about it. Art > [Bruce] > > > Cool! And only a megabyte. > > Of the megabyte, probably about 80% is essentially a runtime environment - > which theoretically is a one time download. If one could educate a Setup > script sufficiently to look for the environment, the distribution of even > the most complex VPython constructions could be done as an executable of < > 250k. An eye blink at decent bandwidth. Setup could only go back for the > "runtime" if it doesn't find it on the machine. > > Not terribly different from what is normal for Flash or Java applets. > Probably the best available alternative to a Java based VPython - in some > ways better, I think. > > Of course, the Windows only aspect is a big downside. I won't even try to > approach what would be necessary to make this a true crossplatfrom > capability. > > Art > From webmaster@pferdemarkt.ws Thu Mar 6 14:01:28 2003 From: webmaster@pferdemarkt.ws (webmaster@pferdemarkt.ws) Date: Thu, 6 Mar 2003 06:01:28 -0800 Subject: [Edu-sig] Pferdemarkt.ws informiert! Newsletter 03/2003 http://www.pferdemarkt.ws Message-ID: <200303061401.GAA21380@eagle.he.net> http://www.pferdemarkt.ws Wir sind in 2003 erfolgreich in des neue \"Pferdejahr 2003 gestartet. Für den schnellen Erfolg unseres Marktes möchten wir uns bei Ihnen bedanken. Heute am 06.03.2003 sind wir gut 2 Monate Online! Täglich wächst unsere Datenbank um 30 Neue Angebote. Stellen auch Sie als Privatperson Ihre zu verkaufenden Pferde direkt und vollkommen Kostenlos ins Internet. Zur besseren Sichtbarmachung Ihrer Angebote können SIe bis zu ein Bild zu Ihrer Pferdeanzeige kostenlos einstellen! Wollen Sie direkt auf die erste Seite, dann können wir Ihnen unser Bonussystem empfehlen. klicken Sie hier: http://www.pferdemarkt.ws/bestellung.html Ihr http://Pferdemarkt.ws Team Klicken Sie hier um sich direkt einzuloggen http://www.Pferdemarkt.ws Kostenlos Anbieten, Kostenlos Suchen! Direkt von Privat zu Privat! Haben Sie noch Fragen mailto: webmaster@pferdemarkt.ws From arion@uselesspython.com Fri Mar 14 01:00:32 2003 From: arion@uselesspython.com (Rob Andrews) Date: Thu, 13 Mar 2003 19:00:32 -0600 Subject: [Edu-sig] constructive criticism sought Message-ID: Useless Python has been working on "getting its act together" to become a more beneficial resource for learning Python, and the team of volunteers is at a point in the process where I feel it would be good to solicit some constructive criticism. After it became obvious that the site had far outgrown the ability of one person to maintain the site more-or-less manually, a team of volunteers was recruited, and some development work has begun to bolster the integrity of the site. It's all underway currently, and is at a stage where there is still room to take suggestions to heart. A development version of the site is at http://uselesspython.com/newsite/ (much nicer navigation in store, and faster-loading) and the "old" version of the site is still carrying on at http://uselesspython.com (quite functional, but with plenty of room for improvement). In the new version of the site, it should be much easier to find source code by means of navigating through categories, and some reasonably advanced search capabilities are being developed. We have also noted a need to add some "quality control" and basic means for peer-review. So far, peer review has meant referring contributors to the Python Tutor email list, but we want to start making sure that each contribution is reviewed by a volunteer, and we may add a database-powered discussion board. The verdict is still out on which directions to take with this. So, aside from the fact that the development site has more dead links than actual pages (because it's a development site), how can we make the site a genuinely useful resource for novice/student programmers and educators? -Rob Andrews From ahimsa@onetel.net.uk Fri Mar 14 19:30:51 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Fri, 14 Mar 2003 19:30:51 +0000 Subject: [Edu-sig] constructive criticism sought (Rob Andrews) In-Reply-To: <20030314170005.14775.79280.Mailman@mail.python.org> References: <20030314170005.14775.79280.Mailman@mail.python.org> Message-ID: <200303141930.51941.ahimsa@onetel.net.uk> Hello Rob First, as an erstwhile 'consumer' of Useless Python, thanks for the work = you=20 and now your volunteer team have done on that site. It's good fun to surf= =2E Second, by way of offering (hopefully) constructive criticism, kindly acc= ept=20 the following points: 1. PLEASE remove it from yahoo! groups. I would be quite happy to volunte= er=20 but was unhappy with going via yahoo to do so. 2. Rather than toss truly useless code (I think my few contributions have= =20 probably landed in that bin!!), would it be possible to catalogue it and=20 remove duplicates. I suspect that many snippets of code are those done by= =20 newbies (such as myself) who are working through tuts or text books, etc,= so=20 is likely to be replicated. 3. With the foregoing in mind however, if it is to be "Useless" Python, t= hen=20 perhaps it could be graded because there is some pretty complex material = on=20 the site last time I looked and then there is some pretty basic stuff too= =2E It=20 would be a shame, I think, if the really basic stuff was elided by the=20 complex, not for any other reason than the sense of accomplishment a newb= ie=20 might get surfing through and reading code that s/he can actually underst= and=20 and even contribute to without feeling daunted/intimidated by really=20 elaborate/complex code. Let's face it, a certain % of that code is never=20 going to be worth anything, which surely is as good a definition of usele= ss=20 as anything I've ever come across. Third, look forward to seeing the new site once it is done and dusted. We= ll=20 done Rob - it was a good idea, and I for one am happy that you continued = with=20 it. Thanks. Andrew From reavey@nep.net Fri Mar 14 23:36:58 2003 From: reavey@nep.net (reavey) Date: Fri, 14 Mar 2003 18:36:58 -0500 Subject: [Edu-sig] constructive criticism Message-ID: <3E72679A.3020109@nep.net> Replt to Rob Andrews Perhaps an approach which provides commented code would help make this more usefull. There are many examples and I hate to finger point. However , helpdesk.py is pretty typical, it has virtually no comments. The last several weeks of mail on the tutor seem to have a lot of questions related to class and defining variables. Re-v From i.linkweiler@gmx.de Sat Mar 15 17:15:41 2003 From: i.linkweiler@gmx.de (Ingo Linkweiler) Date: Sat, 15 Mar 2003 18:15:41 +0100 Subject: [Edu-sig] ANN: Stifte und Maeuse f. Python! Message-ID: <3E735FBD.7050501@gmx.de> SuM - Von Stiften und M=E4usen DESCRIPTION: ------------ German only: About pens and mice, a conversion of the well-known didactical learning software to Python. BESCHREIBUNG: ------------- Eine Umsetzung der bekannten didaktischen Lernsoftware nach Python. Einf=FChrung in die Grundlagen der objektorientierten Programmierung. Anhand fertiger Klassen "Stift", "Maus", "Bildschirm" u.a. kann in dieser Lernumgebung der Einstieg in die objektorientierte=20 Softwareentwicklung mit einfacher Computergrafik vermittelt werden. VERSION: -------- 1.0 erste =F6ffentliche Version 1.1 zahlreiche Verbesserungen wurden vorgenommen. Es erfolgten Anpassungen an die aktuelle Klassenbibliothek. Zahlreiche Beispiele und eine komplett erneuerte Dokumentation=20 demonstrieren die Anwendung. URL: ---- http://www.ingo-linkweiler.de/diplom/ From urnerk@qwest.net Tue Mar 18 20:02:22 2003 From: urnerk@qwest.net (Kirby Urner) Date: Tue, 18 Mar 2003 12:02:22 -0800 Subject: [Edu-sig] An outline I'm using In-Reply-To: <3E735FBD.7050501@gmx.de> Message-ID: <5.2.0.9.0.20030318115244.0239eff0@pop.ptld.qwest.net> Here's an outline I'm using to help prepare for a talk I'm giving on Python in Education in July of this year at OSCON (Open Source Conference), which is here in Portland, Oregon this time. I'll be using PowerPoint of course, as well as Python in GUI shells (e.g. IDLE and PyCrust, maybe PythonCard if I can learn it in time). The outline below doesn't actually map out my talk -- it's more for background, to guide my information gathering. In the actual presentation, I'll have more focus on some specific uses of Python (e.g. Python + Povray). Of course I'll have some screen shots (e.g. from PyGeo) to show what kinds of stuff goes on out there. Kirby ========================================== Status Quo Graphing Calculators What languages now used? Java, C, Scheme...? Where is Python used? Current uses of Python Add-ons and Bindings (e.g. NumPy, Blender...) Currently available publications/resources (inventory) (especially those used/usable in school setting) History: CP4E initiative (DARPA etc.) Trends Laptops/PDAs Classroom configuration & technology Homeschooler demographics Teacher training (trends in) Projected uses of Python Curriculum Needs What's needed? More information about status quo + trends More lesson plans for hands-on Python K-12 (middle, high), homeschool College/Junior College/Adult Education Programming in different subject areas Computer science (college level) Programming as high school elective (AP comp sci) Science/Engineering and programming Math through Programming expanding "numeracy" to mean more familiarity with programming (promising door: cryptography) Art: programming and visual arts (e.g. povray, animation), music etc. Role of the web? (as source of curriculum) Problem of cheating (solutions?) Showcase Phase Web sites Applications/modules Public presentations / talks Published Articles Success Stories "Learn From" Stories CDs? DVDs? Books? From dblank@brynmawr.edu Tue Mar 18 20:30:58 2003 From: dblank@brynmawr.edu (Douglas S. Blank) Date: Tue, 18 Mar 2003 15:30:58 -0500 Subject: [Edu-sig] An outline I'm using References: <5.2.0.9.0.20030318115244.0239eff0@pop.ptld.qwest.net> Message-ID: <3E778202.4070009@brynmawr.edu> Here's another data point: robotics. We've just released our version 1.0=20 of Python Robotics (see http://emergent.brynmawr.edu/wiki/index.cgi/Pyro=20 ). I wasn't sure if Python would be fast enough to do "real" robotics,=20 but after building and testing, we found that we can get 10,000 updates=20 a second without OpenGL and 1,000 updates a second with it. Basically,=20 that's too fast as the hardware can't respond that quickly. Of course,=20 as we add more functionality (vision, neural networks, etc) it does slow=20 down a bit :) But Python isn't just another language to do robotics: it has serious=20 consequences for allowing us to teach upper level artificial=20 intelligence and cognitive science courses (for example) to non-computer=20 science (and cs) students. We're designing a new computer science=20 curriculum around these ideas. We also do all of our real research with=20 these Python tools as well. The flexibility that Python provides allows=20 us to try things we would have never dreamed using just C++. Here's a paper on the Python Robotics project: Blank, D., Meeden, L., and Kumar, D. (2003). Python robotics: An=20 Environment for Exploring Robotics Beyond LEGOs. ACM Special Interest=20 Group: Computer Science Education Conference, Reno, NV (SIGCSE 2003).=20 Preprint: http://dangermouse.brynmawr.edu/papers/sigcse-03.pdf and one of the curriculum design ideas: Blank, D. and Kumar, D. (2002). Patterns of Curriculum Design.=20 Proceedings of Informatics Curricula, Teaching Methods and best practice=20 (ICTEM), Florian=F3polis, SC Brazil.=20 http://dangermouse.brynmawr.edu/papers/BlankKumar.ps (it doesn't mention Python explicitly, but it is the facilitator=20 supporting these motivations). If you want to share your presentation when you get it finished, it=20 would be a nice resource to have available. -Doug Kirby Urner wrote: >=20 > Here's an outline I'm using to help prepare for a talk I'm giving on > Python in Education in July of this year at OSCON (Open Source Conferen= ce), > which is here in Portland, Oregon this time. >=20 > I'll be using PowerPoint of course, as well as Python in GUI shells > (e.g. IDLE and PyCrust, maybe PythonCard if I can learn it in time). >=20 > The outline below doesn't actually map out my talk -- it's more for > background, to guide my information gathering. >=20 > In the actual presentation, I'll have more focus on some specific uses = of > Python (e.g. Python + Povray). Of course I'll have some screen shots > (e.g. from PyGeo) to show what kinds of stuff goes on out there. >=20 > Kirby >=20 > =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D >=20 > Status Quo > Graphing Calculators > What languages now used? > Java, C, Scheme...? > Where is Python used? > Current uses of Python > Add-ons and Bindings (e.g. NumPy, Blender...) > Currently available publications/resources (inventory) > (especially those used/usable in school setting) > History: CP4E initiative (DARPA etc.) >=20 > Trends > Laptops/PDAs > Classroom configuration & technology > Homeschooler demographics > Teacher training (trends in) > Projected uses of Python >=20 > Curriculum Needs > What's needed? > More information about status quo + trends > More lesson plans for hands-on Python > K-12 (middle, high), homeschool > College/Junior College/Adult Education > Programming in different subject areas > Computer science (college level) > Programming as high school elective (AP comp sci) > Science/Engineering and programming > Math through Programming > expanding "numeracy" to mean more familiarity > with programming (promising door: cryptography) > Art: programming and visual arts > (e.g. povray, animation), music etc. >=20 > Role of the web? (as source of curriculum) > Problem of cheating (solutions?) >=20 > Showcase Phase > Web sites > Applications/modules > Public presentations / talks > Published Articles > Success Stories > "Learn From" Stories > CDs? DVDs? Books? >=20 >=20 > _______________________________________________ > Edu-sig mailing list > Edu-sig@python.org > http://mail.python.org/mailman/listinfo/edu-sig >=20 >=20 --=20 Douglas S. Blank, Assistant Professor dblank@brynmawr.edu, (610)526-6501 Bryn Mawr College, Computer Science Program 101 North Merion Ave, Park Science Bld. Bryn Mawr, PA 19010 dangermouse.brynmawr.edu From urnerk@qwest.net Tue Mar 18 20:39:48 2003 From: urnerk@qwest.net (Kirby Urner) Date: Tue, 18 Mar 2003 12:39:48 -0800 Subject: [Edu-sig] An outline I'm using In-Reply-To: <3E778202.4070009@brynmawr.edu> References: <5.2.0.9.0.20030318115244.0239eff0@pop.ptld.qwest.net> Message-ID: <5.2.0.9.0.20030318123753.0239b9f8@pop.ptld.qwest.net> At 03:30 PM 3/18/2003 -0500, you wrote: >Here's another data point: robotics. We've just released our version 1.0 >of Python Robotics (see http://emergent.brynmawr.edu/wiki/index.cgi/Pyro ). <> >If you want to share your presentation when you get it finished, it would >be a nice resource to have available. > >-Doug Thanks Doug! Excellent points! I've updated my outline to include Robotics and will be studying the resources you point to. I think my presentation slides will be made available through O'Reilly, along with all the others. Anyway, I'll let you know. Kirby From urnerk@qwest.net Wed Mar 19 05:58:22 2003 From: urnerk@qwest.net (Kirby Urner) Date: Tue, 18 Mar 2003 21:58:22 -0800 Subject: [Edu-sig] Intro to calculus through Python In-Reply-To: <5.2.0.9.0.20030318123753.0239b9f8@pop.ptld.qwest.net> References: <3E778202.4070009@brynmawr.edu> <5.2.0.9.0.20030318115244.0239eff0@pop.ptld.qwest.net> Message-ID: <5.2.0.9.0.20030318211312.023edde0@pop.ptld.qwest.net> We learn in intro the calculus that the derivative of a single-variable function at some point, is the ratio of change in f(x) to change in x, where this change approaches zero as its limiting value: D(f(x)) = lim (f(x+h)-f(x))/h h->0 What's maybe not so clear to some students, because the book isn't clear, is that D(f) -- derivative of f -- is itself a function, with a function as input. The variable x stands for "any x" in the domain, not a specific value. It's a parameter. Given Python's top-level functions, and the ability to take functions as arguments, and return them as results, we have the option to illustrate the above concept with some definite value of h. This is discrete mathematics, using floating point numbers, so not exactly formal calculus -- but such approximations serve a valid pedagogical purpose. def D(f,h=1e-3): """ Return derivative of function f (also a function) """ def df(x): deriv=(f(x+h)-f(x))/h return round(deriv,3) return df Let's pause to admire Python's flexibility here. D( ) is taking an arbitrary function f as its input (with a default value of h), and returning df. Python's scoping rules (as of 1.6) will build df using whatever function we pass in (f). For example, let's define f(x) = x**2 and pass that to D( ) above: >>> def g(x): return x*x >>> g # g is a function >>> dg = D(g) # we pass g, a function, to another function >>> dg # ... and we get back a function Now compare g(x), for x = 0,1,2,3...10 and dg(x) for the same values: >>> [g(x) for x in range(11)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100] >>> [dg(x) for x in range(11)] [0.001, 2.0009999999999999, 4.0010000000000003, 6.0010000000000003, 8.0009999999999994, 10.000999999999999, 12.000999999999999, 14.000999999999999, 16.001000000000001, 18.001000000000001, 20.001000000000001] Again, we're dealing in approximations here, but clearly dg(x) closely approximates 2*x, which is the actual derivative of x**2. We can highlight this in a couple of ways. By further rounding: >>> [round(dg(x)) for x in range(11)] [0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0] ...or by redefining dg using a smaller value for h (h yet closer to zero): >>> dg = D(g,h=1e-8) >>> [dg(x) for x in range(11)] [0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0] How about integration? The definite integral is the sum of the little rectangles fitted to the curve, as their widths become vanishingly small. The rectangles stand next to each other starting from a, running up to b. And because f(x+h) and f(x) will generally differ, because f(x) is a curve of some kind, it makes sense to compute the area of the rectangles using the *average* of these two values. Again, an approximation. And again, we use functions for inputs and outputs: def I(f,h=1e-3): """ Return definite integral function """ def intf(b,a=0): sum=0 x = a while x<=b: # keep accumulating sum += h*(f(x+h)+f(x))/2.0 # area of rectangle x += h return round(sum,3) return intf Our definite integral function is inherently less precise, and has to do more work, than our derivative function. Use of the average is precise only insofar as our straight line segments from (x,f(x)) to (x+h, f(x+h)) are good approximations of the curve. Clearly this gets better as h gets smaller, but since we have to sum a lot of these rectangles, we can't afford to make h too small -- we're depending on successive additions of h to get us all the way from a to b, after all. But let's admire Python some more. The fundamental theorem of the calculus states that the definite integral and derivative are inverse functions, i.e. if we take the derivative of the integral of f, or the integral of the derivative of f, over the interval [a,b], we should get back our original function: f. And Python allows us to show this rather directly (in an approximate form): >>> inv1 = I(D(g)) # a function of a function of a function! >>> [inv1(x) for x in range(11)] [0.0, 1.0009999999999999, 4.0060000000000002, 9.0090000000000003, 16.012, 25.004999999999999, 36.006, 49.006999999999998, 64.007999999999996, 81.009, 100.03] >>> inv2 = D(I(g)) # reversing I and D from the above case >>> [inv2(x) for x in range(11)] [0.0, 1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0, 64.0, 81.0, 100.0] In both of the above examples, we get back a function reasonably close to g(x) = x**2, as demonstrated by feeding it the values 0...10. inv1 was defined by applying the integral function to the function returned by the derivative function, which got function g as its argument. inv2 was defined by applying the derivative function to the definite integral of g. The interval [a,b] is arbitrary, with a=0 by default. Python's ability to support high level functional programming helps us appreciate that differentiation and integration apply to functions to create other functions, and that these resulting functions have an inverse relationship. Kirby From DaddyGravity@livingcode.ca Tue Mar 18 20:58:10 2003 From: DaddyGravity@livingcode.ca (Dethe Elza) Date: Tue, 18 Mar 2003 12:58:10 -0800 Subject: [Edu-sig] An outline I'm using In-Reply-To: <5.2.0.9.0.20030318115244.0239eff0@pop.ptld.qwest.net> Message-ID: <53F0CA42-5984-11D7-89E7-0003939B59E8@livingcode.ca> Kirby, > I'll be using PowerPoint of course, as well as Python in GUI shells > (e.g. IDLE and PyCrust, maybe PythonCard if I can learn it in time). Have you seen PythonPoint[1]? It's a pythonic alternative to PowerPoint, and there's a reStructuredText[2] project to create[3] PythonPoint slides from a (lightly marked-up) text document. [1] http://www.reportlab.com/demos/pythonpoint/pythonpoint.html [2] http://docutils.sourceforge.net/ [3] http://docutils.sourceforge.net/sandbox/richard/pythonpoint/ --Dethe From ajsiegel@optonline.net Wed Mar 19 13:17:31 2003 From: ajsiegel@optonline.net (Arthur) Date: Wed, 19 Mar 2003 08:17:31 -0500 Subject: [Edu-sig] re: An outline I'm using Message-ID: <000501c2ee19$e633c220$2102a8c0@Arts> Dethe writes - >Have you seen PythonPoint[1]? It's a pythonic alternative to >PowerPoint, and there's a reStructuredText[2] project to create[3] >PythonPoint slides from a (lightly marked-up) text document. Good suggestion. I'm finding reStructuredText a very practical tool for doing documentation. The light mark-up goes a long way, and the list of output possibilities continues to grow. Kirby might find that preparing his presentation in reStructuredText will allow him, for example, to use it in PythonPoint, and publish it on the web as html, or "do sutff" with it as xml output, all from the same marked up document. Art From ajsiegel@optonline.net Wed Mar 19 13:24:48 2003 From: ajsiegel@optonline.net (Arthur) Date: Wed, 19 Mar 2003 08:24:48 -0500 Subject: [Edu-sig] Re: An outline I'm using Message-ID: <000f01c2ee1a$ea601140$2102a8c0@Arts> Kirby writes - >In the actual presentation, I'll have more focus on some specific uses of >Python (e.g. Python + Povray). Of course I'll have some screen shots >(e.g. from PyGeo) to show what kinds of stuff goes on out there. I must have good political instincts. Hadn't known you were undertaking this project. But am adding a polyhedra exploration tool to PyGeo, mostly with you in mind. Essentially creating the 120 polyhedron vertexes and edge and face mapping based on: http://www.rwgrayprojects.com/Lynn/Coordinates/coord01.html as a PyGeo "library". Had to work on the lighting and the Povray output to make it fully functional. But seem to be mostly there. Having some fun with it. Art From rob@jam.rr.com Fri Mar 21 18:45:25 2003 From: rob@jam.rr.com (Rob Andrews) Date: Fri, 21 Mar 2003 12:45:25 -0600 Subject: [Edu-sig] constructive criticism sought (Rob Andrews) In-Reply-To: <200303141930.51941.ahimsa@onetel.net.uk> Message-ID: I thanked people privately for their responses to my question, but I = wanted to take a moment to say "thanks" to the list generally. "Thanks." -Rob Andrews > -----Original Message----- > Hello Rob >=20 > First, as an erstwhile 'consumer' of Useless Python, thanks for=20 > the work you=20 > and now your volunteer team have done on that site. It's good fun to = surf. >=20 > Second, by way of offering (hopefully) constructive criticism,=20 > kindly accept=20 > the following points: >=20 From urnerk@qwest.net Sun Mar 30 21:06:48 2003 From: urnerk@qwest.net (Kirby Urner) Date: Sun, 30 Mar 2003 13:06:48 -0800 Subject: [Edu-sig] Some design patterns with iterators In-Reply-To: References: <200303141930.51941.ahimsa@onetel.net.uk> Message-ID: <5.2.0.9.0.20030330113646.02442c28@pop.ptld.qwest.net> The construct: for i in collection: do something with i is extremely common. The collection is most simply a list or tuple, but may in fact be any iterable object. So the construct might be rewritten: for i in iterable: # construct (1) do something with i But how do we ensure that this is not an infinite loop? I.e. the collection returned by iterable may be inherently open-ended, e.g. the sequence of fibonacci numbers 1 1 2 3 5 8 13... A common modification to deal with such cases is: for i in iterable: # construct (2) if test(i): break do something with i An alternative to the above is to return to the original construct (1), but have the iterable become self-terminating. The syntax: iterable = iter(obj,sentinel) uses the builtin iter() to compare a callable to a sentinel, and stops iterating when they match. So lets define an object that returns the next fibonacci number whenever called, and which internalizes a test, which, if positive, will return the sentinel value: ---- # iters.py class Fib(object): def __init__(self,start=0,next=1,test=False,sentinel=-1): self.start = start self.next = next self.sentinel = sentinel self.test = test def __call__(self): self.start,self.next = self.next, self.start + self.next if self.test(self.start): return self.sentinel return self.start def t(x): """x > 1000""" return x > 1000 fibobj = Fib(test=t) iterable = iter(fibobj,-1) for i in iterable: print i, ---- If you run the above script you'll get a listing of Fibonacci numbers less than or equal to 1000: Sun 03/30/2003 11:57:21.79 D:\Program Files\Python22>python ./work/iters.py 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 Why go to all the trouble of passing in a test function, if we can simply set a sentinel value to abort iteration? The Fibonacci example suggests the answer: we don't know in advance exactly what the collection will be (or think of prime numbers), so we're not in a position to use a simple value to abort iteration -- we need something like a comparison, or a more complicated set of criteria, which is why we pass in a test. A callable object, turned into an iterator by way of iter(), behaves much the same as a generator object -- which objects may be functions. The Fib object might be rewritten as a generator, still accepting a test function as a parameter: >>> def fibfunc(test): data = [1,1] while not test(data[0]): yield data[0] data[0],data[1] = data[1],data[0]+data[1] return >>> iterable = fibfunc(t) # t is a test function >>> for i in iterable: print i, 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 In this case, fibfunc automatically returns an iterable. What is the advantage of passing a test into an iterable, versus simply going with construct (2)? From a readability point of view, this approach has the advantage of binding the test to the iterable at the time of definition. The same for-loop might handle lots of iterators, and needn't worry about which test to use. The test logically belongs with the iterator. For example, let's modify iters.py (keeping original Fib object intact): ---- def testfunc(max): """a factory for test functions""" def t(x): return x > max t.__doc__ = "stop when x > %s" % max return t t1 = testfunc(1000) t2 = testfunc(5000) def looper(iterable): # generic loop, doesn't worry about when to break for i in iterable: print i, print print t1.__doc__ looper(iter(Fib(test=t1),-1)) print t2.__doc__ looper(iter(Fib(test=t2),-1)) ---- >>> reload(iters) stop when x > 1000 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 stop when x > 5000 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 In this case, the same test functions will work with the generator version. Example: >>> iterable = fibfunc(t2) >>> for i in iterable: print i, 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 --- Kirby From urnerk@qwest.net Mon Mar 31 07:16:22 2003 From: urnerk@qwest.net (Kirby Urner) Date: Sun, 30 Mar 2003 23:16:22 -0800 Subject: [Edu-sig] Some design patterns with iterators In-Reply-To: <200303310044.h2V0i1D01899@pcp02138704pcs.reston01.va.comca st.net> References: <"Your message of Sun, 30 Mar 2003 13:06:48 PST." <5.2.0.9.0.20030330113646.02442c28@pop.ptld.qwest.net> <200303141930.51941.ahimsa@onetel.net.uk> <5.2.0.9.0.20030330113646.02442c28@pop.ptld.qwest.net> Message-ID: <5.2.0.9.0.20030330213831.0231c370@pop.ptld.qwest.net> At 07:44 PM 3/30/2003 -0500, Guido van Rossum wrote: .... Your comments highly welcomed and greatly appreciated! >-- > >That's a contorted example. Why not change this a bit so that instead >of __call__ it has a next method that raises StopIteration when >exhausted, and an __iter__ method returning self? Agreed. Students should realize that objects don't need to be wrapped by iter() in order to perform as iterators. It's sufficient to define a next() method internally, and then assign the object itself as the return of __iter__ -- as you point out. It's also possible to equate __call__ to next, so if the programmer *does* happen to wrap the object inside iter(), even with a sentinel, it won't break -- although the sentinel is irrelevant in this pattern, because now the test raises an exception instead. class Fib2(object): def __init__(self,start=0,next=1,test=lambda x: False): # note revised default for test -- previous default of # 'False' was not callable self.start = start self.next = next self.test = test def next(self): self.start,self.next = self.next, self.start + self.next if self.test(self.start): raise StopIteration return self.start __call__ = next # makes object callable def __iter__(self): return self def testfunc(max): """a factory for test functions""" def t(x): return x > max t.__doc__ = "stop when x > %s" % max return t t1 = testfunc(1000) t2 = testfunc(5000) def looper(iterable): for i in iterable: print i, print # newline when done def tests(): print t1.__doc__ looper(Fib2(test=t1)) # note: no iter() wrapper -- Fib2 is already iterable print t2.__doc__ looper(iter(Fib2(test=t2),-1)) # but we can wrap it without problems print t2.__doc__ looper(iter(Fib2(test=t2))) # with or without a sentinel Having a sentinel where it's not needed is of course a sign of programmer confusion. But one might argue the object itself is "more robust" this way. > > >>> def fibfunc(test): > > data = [1,1] > > while not test(data[0]): > > yield data[0] > > data[0],data[1] = data[1],data[0]+data[1] > > return > >Comment here: instead of using a two-element list (which could just as >well be a tuple!), use two variables. Faster and clearer IMO: > > def f(test): > last, next = 1, 1 > while not test(last): > yield last > last, next = next, last+next Yes, clearer. The list-based approach was left over from a version which makes the initial two-value seed a parameter as in: def iterseq(seed=[0,1],test=lambda x: False): # but even so, it's easier to read with two variables: last,next = seed while not test(last): yield last last, next = next, last+next With this new freedom we can generate the Lucas Numbers, with seed [2,1] instead of [1,1]: http://www.mcs.surrey.ac.uk/Personal/R.Knott/Fibonacci/lucasNbs.html def tests(): #... print "Lucas Numbers" looper(iterseq([2,1],t1)) >>> iters.tests() ... Lucas Numbers 2 1 3 4 7 11 18 29 47 76 123 199 322 521 843 A modification lets us iterate until a last/next ratio is reached through convergence -- need to be careful here, as infinite loops often result from equating floating point numbers. def iterseq2(seed=[1,1],test=lambda x,y: False): # variation, where test looks at both last and next last,next = seed while not test(last,next): yield "%s/%s" % (last,next) last, next = next, last+next # probaby overkill to wrap a function here, but I'm wanting to *not* rely on a # global value for phi, nor do I want to keep re-evaluating a square root with # every test -- so I pass it in explicitly and build a function around it. def testratio(terminus): def t(inta,intb): return (intb/inta) == terminus # uses new division # it'd be safer to test for abs(difference) < tolerance return t t3 = testratio(0.5*(1+pow(5,.5))) # phi = (1 + sqrt(5))/2 def tests(): # ... print "Converging..." looper(iterseq2([1,1],t3)) # Fibonacci seed, convergence test Converging... 1/1 1/2 2/3 3/5 5/8 8/13 13/21 21/34 34/55 55/89 89/144 144/233 233/377 377/610 610/987 987/1597 1597/2584 2584/4181 4181/6765 6765/10946 10946/17711 17711/28657 28657/46368 46368/75025 75025/121393 121393/196418 196418/317811 317811/514229 514229/832040 832040/1346269 1346269/2178309 2178309/3524578 3524578/5702887 5702887/9227465 9227465/14930352 14930352/24157817 24157817/39088169 39088169/63245986 63245986/102334155 The Lucas Number next/last ratios likewise converge to phi. >Are your students familiar with functions as first-order objects at >this point? It would be simpler if you could simply pass the limit as >the argument to Fib() rather than having to construct a test function >first. Sure, a test function allows more freedom, but the API design >here doesn't actually make it much easier to do something different in >the test function -- e.g. another useful termination test would be to >produce the first N numbers, but that would require the test function >to be stateful, and the API doesn't promise that test() is only called >once per iteration. Yes, I'm sort of demonstrating two concepts -- iterators, and the fact that functions may be passed as parameters. There's more convolution as a result. Plus the above example points up a weakness in this design: the passed-in function is relying on a hard-wired set of arguments, is in test(last), whereas we might want access to both last and next for our test. Our only access to the local scope, within the generator function, is based on the arguments to test() -- a limit on our freedom. I do find it interesting that objects don't suffer as much from this limitation, as one has access to all the object's instance variables through 'self' -- so it's possible to write a top-level test function knowing that 'self' is the only argument needed -- yet internal to the test function, you may access self's scope at will: class Fib3(object): def __init__(self,start=0,next=1,test=lambda x: False): self.start = start self.next = next self.test = test def next(self): self.start,self.next = self.next, self.start + self.next if self.test(self): # single parameter sufficient to access __dict__ raise StopIteration return self.start __call__ = next def __iter__(self): return self def testratio2(terminus): def t(obj): # obj will be the self of the enclosing object return obj.next/obj.start == terminus # uses new division return t But we're just getting more and more convoluted here (useful learning on my end though) ... Kirby From urnerk@qwest.net Mon Mar 31 07:35:03 2003 From: urnerk@qwest.net (Kirby Urner) Date: Sun, 30 Mar 2003 23:35:03 -0800 Subject: [Edu-sig] Some design patterns with iterators In-Reply-To: <5.2.0.9.0.20030330213831.0231c370@pop.ptld.qwest.net> References: <200303310044.h2V0i1D01899@pcp02138704pcs.reston01.va.comca st.net> <"Your message of Sun, 30 Mar 2003 13:06:48 PST." <5.2.0.9.0.20030330113646.02442c28@pop.ptld.qwest.net> <200303141930.51941.ahimsa@onetel.net.uk> <5.2.0.9.0.20030330113646.02442c28@pop.ptld.qwest.net> Message-ID: <5.2.0.9.0.20030330233404.02377268@pop.ptld.qwest.net> > >A modification lets us iterate until a last/next ratio is reached through Note: it's next/last (larger over smaller term) that approaches 1.618... Kirby