From urnerk@qwest.net Mon Oct 1 09:25:46 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Mon, 01 Oct 2001 01:25:46 -0700
Subject: [Edu-sig] more math with Python
In-Reply-To:
References: <4.2.0.58.20010930092216.00c31450@pop3.norton.antivirus>
Message-ID: <4.2.0.58.20011001005940.019b3570@pop3.norton.antivirus>
>In fact, it's such a good approximation that
>
> drs(n) == round(n!/e)
>
>where round(x) rounds x to the nearest integer, for all n >= 1.
A very excellent point.
>If the students are advanced enough, it's an interesting exercise
>to find the smallest n for which the limitations of floating-point
>arithmetic cause round(n!/e) to return a different result than
>your exact computation using rationals.
Not following this.
>>> def altdrs(n):
return round(fact(n)/e)
returns the same answer as drs(n) right down to n=1.
A related question (that I understand) would be how far
do we need to push the series in brackets to get 1/e
within the limitations of floating point arithmetic:
>>> from math import e
>>> def e_neg1():
f = 0
sign = 1
t = 0
while float(f)<>(1/e):
f += sign * F(1, fact(t))
sign = -sign
t += 1
return (t-1,f)
>>> e_neg1()
(18, (138547156531409/376610217984000))
I get 18 terms, with the accompanying fraction.
>>> 138547156531409/376610217984000 # (import future division)
0.36787944117144233
>>> 1/e
0.36787944117144233
This is related to the thread wherein we get phi to the limits
of floating point, using the continued fraction:
phi= 1 + 1
--------------
1 + 1
--------
1 + 1
----
1 + ...
It's related because evaluating a continued fraction involves
recursive use of the Fraction object F:
>>> def evalcf(qs):
"""
Evaluate continued fraction with partial quotients qs
"""
if len(qs)==1:
return F(qs[0],1)
return F(qs[0],1) + F(1,evalcf(qs[1:]))
>>> evalcf([1,1,1,1,1])
(8/5)
>>> evalcf([1,1,1,1,1,1,1,1,1])
(55/34)
>>> float(evalcf([1,1,1,1,1,1,1,1,1]))
1.6176470588235294
>>> from math import sqrt
>>> phi = (1 + sqrt(5))/2
>>> def getphi():
qs = []
v = 0
while float(v) <> phi:
qs.append(1)
v = evalcf(qs)
return (len(qs),v)
>>> getphi()
(40, (165580141/102334155))
>And later you flipped in a different way, by testing the
>parity of t. A common idiom in numeric programs is to
>multiply by 1 or -1 instead, like so:
Slaps forehead. Yes, of course! This is what you see most
often.
> f = 0
> sign = 1
> for t in range(n+1):
> f += sign * F(1, fact(t))
> sign = -sign
> return fact(n) * f
>
>As a *programming* issue, it's thus interesting to consider whether
>F.__mul__ should or shouldn't try to recognize the special cases of
>multiplication by 1 and -1. There's isn't a "one size fits all"
>answer, so it's not for students with low tolerance for uncertainty
>.
Not following again. Like, of course it should, right?
>>> f = F(1,2)
>>> f
(1/2)
>>> f*1
(1/2)
>>> f*-1
(-1/2)
What other behavior would I want?
Kirby
From feiguin@magnet.fsu.edu Mon Oct 1 18:58:14 2001
From: feiguin@magnet.fsu.edu (Adrian Feiguin)
Date: Mon, 1 Oct 2001 13:58:14 -0400 (EDT)
Subject: [Edu-sig] GracePlot
In-Reply-To: <08ae01c149b2$0e344f00$cc090740@megapathdsl.net>
Message-ID:
You might find interesting SciGraphica
(http://scigraphica.sourceforge.net). The Python interface is still under
development, but eventually will allow to create interactive 2D/3D/Polar
plots.
In any case, nice job ;-)
Saludos,
On Sun, 30 Sep 2001, Jason Cunliffe wrote:
>
> http://www.idyll.org/~n8gray/code/index.html
>
>
> Announcement
> This module provides interactive 2-D plotting capabilities via the Grace
> package. Why do we need yet another plotting package for Python? Simple.
> None of the packages out there (that I've tried) currently offer all of the
> following desirable properties:
> Designed for use at the interactive prompt
> Provide UI access to plot properties and allow changes on-the-fly
> Tight integration with Numeric Python
> A typical gracePlot session goes something like this:
>
> >>> from gracePlot import gracePlot
> >>> p = gracePlot() # A grace session opens
> >>> p.plot( [1,2,3,4,5], [10, 4, 2, 4, 10], [1, 0.7, 0.5, 1, 2],
> ... symbols=1 ) # A plot with errorbars & symbols
> >>> p.title('Funding: Ministry of Silly Walks')
> >>> p.ylabel('Funding (Pounds\S10\N)')
> >>> p.multi(2,1) # Multiple plots: 2 rows, 1 column
> >>> p.xlimit(0, 6) # Set limits of x-axis
> >>> p.focus(1,0) # Set current graph to row 1, column 0
> >>> p.histoPlot( [7, 15, 18, 20, 21], x_min=1,
> ... dy=[2, 3.5, 4.6, 7.2, 8.8]) # A histogram w/errorbars
> >>> p.xlabel('Silliness Index')
> >>> p.ylabel('Applications/yr')
> >>> p.xlimit(0, 6) # Set limits of x-axis
>
>
>
>
> _______________________________________________
> Edu-sig mailing list
> Edu-sig@python.org
> http://mail.python.org/mailman/listinfo/edu-sig
>
From kimtitu@yahoo.com Mon Oct 1 19:16:21 2001
From: kimtitu@yahoo.com (Titu Kim)
Date: Mon, 1 Oct 2001 11:16:21 -0700 (PDT)
Subject: [Edu-sig] Double inclusion
Message-ID: <20011001181621.71071.qmail@web14708.mail.yahoo.com>
Hi there,
I face a tricky question(at least for me it is) in
regular string assignment. Let say i want to create a
string representation of a floating number according
to the decimal specification by user. For instance:
a = 0.05
format ="9.8f"
b=?
If i want to assign b with a string representation of
variable a with the decimal format specified by
'format'. How can i do this? Thanks a lot.
Kim Titu
__________________________________________________
Do You Yahoo!?
Listen to your Yahoo! Mail messages from any phone.
http://phone.yahoo.com
From dyoo@hkn.eecs.berkeley.edu Mon Oct 1 21:38:28 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 1 Oct 2001 13:38:28 -0700 (PDT)
Subject: [Edu-sig] Double inclusion
In-Reply-To: <20011001181621.71071.qmail@web14708.mail.yahoo.com>
Message-ID:
On Mon, 1 Oct 2001, Titu Kim wrote:
> I face a tricky question(at least for me it is) in
> regular string assignment. Let say i want to create a
> string representation of a floating number according
> to the decimal specification by user. For instance:
> a = 0.05
> format ="9.8f"
> b=?
> If i want to assign b with a string representation of
> variable a with the decimal format specified by
> 'format'. How can i do this? Thanks a lot.
Sounds like a job for Python's string formatting --- it should works very
well for this:
###
>>> a = 0.05
>>> format = "9.8f"
>>> b = ("%" + format) % a
>>> a
0.050000000000000003
###
You can find out more about string formatting here, in the "Fancier Output
Formatting" section of the Python tutorial:
http://www.python.org/doc/current/tut/node9.html#SECTION009100000000000000000
and String Formatting is explained in more detail in the library reference
here:
http://www.python.org/doc/current/lib/typesseq-strings.html
Good luck to you!
From tim.one@home.com Tue Oct 2 00:14:05 2001
From: tim.one@home.com (Tim Peters)
Date: Mon, 1 Oct 2001 19:14:05 -0400
Subject: [Edu-sig] more math with Python
In-Reply-To: <4.2.0.58.20011001005940.019b3570@pop3.norton.antivirus>
Message-ID:
[Tim]
>> If the students are advanced enough, it's an interesting exercise
>> to find the smallest n for which the limitations of floating-point
>> arithmetic cause round(n!/e) to return a different result than
>> your exact computation using rationals.
[Kirby Urner]
> Not following this.
>
> >>> def altdrs(n):
> return round(fact(n)/e)
>
> returns the same answer as drs(n) right down to n=1.
Then 1 certainly isn't the smallest n for which equality fails .
Think about larger n, not smaller. After all, "e" there has at best 53 bits
of precision, and for large enough n "fact(n)" can't even be represented
approximately as a float (in 2.2a4 you'll get an OverflowError then; in
earlier Pythons *probably* a platform floating Infinity).
> A related question (that I understand) would be how far
> do we need to push the series in brackets to get 1/e
> within the limitations of floating point arithmetic:
Yes, that is related.
> ...
> while float(v) <> phi:
Note that loops like this may never terminate: there's really no a priori
guarantee that any approximation will *exactly* equal the value computed by
some other approximation (and math.sqrt() and math.e are approximations
too).
>> f = 0
>> sign = 1
>> for t in range(n+1):
>> f += sign * F(1, fact(t))
>> sign = -sign
>> return fact(n) * f
>>
>> As a *programming* issue, it's thus interesting to consider whether
>> F.__mul__ should or shouldn't try to recognize the special cases of
>> multiplication by 1 and -1. There's isn't a "one size fits all"
>> answer, so it's not for students with low tolerance for uncertainty
>> .
> Not following again. Like, of course it should, right?
>
> >>> f = F(1,2)
> >>> f
> (1/2)
> >>> f*1
> (1/2)
> >>> f*-1
> (-1/2)
>
> What other behavior would I want?
It's a pragmatic ("programming") issue, not a semantic issue: the purpose
of special-casing 1 and -1 within F.__mul__ would not be to deliver a
different answer, but to return the correct answer *faster*. Even just
making a copy of an unbounded rational number can take an unbounded amount
of time (depending on how long it takes to copy over all the data), so
special-casing multiplication by 1 to simply return "self" can save an
unbounded amount of runtime.
On the other hand, testing for 1 also takes time, and that time is wasted
whenver the outcome is "nope -- it's not 1". So deciding whether it's a
good idea *overall* is a balancing act.
For most programs using floats or (machine) ints, it turns out it's usually
an overall speed loss to special-case potentially special values. The
tradeoffs are much muddier for unbounded numeric types, while the existence
of idioms like "multiply by 1 or -1 on alternate iterations" make it an
important pragmatic issue ("who in their right mind would bother multiplying
by one?" turns out to be a poor argument ).
From urnerk@qwest.net Tue Oct 2 04:26:36 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Mon, 01 Oct 2001 20:26:36 -0700
Subject: [Edu-sig] more math with Python
In-Reply-To:
References: <4.2.0.58.20011001005940.019b3570@pop3.norton.antivirus>
Message-ID: <4.2.0.58.20011001201404.019b7e50@pop3.norton.antivirus>
At 07:14 PM 10/1/2001 -0400, Tim Peters wrote:
>[Tim]
> >> If the students are advanced enough, it's an interesting exercise
> >> to find the smallest n for which the limitations of floating-point
> >> arithmetic cause round(n!/e) to return a different result than
> >> your exact computation using rationals.
>
>[Kirby Urner]
> > Not following this.
> >
> > >>> def altdrs(n):
> > return round(fact(n)/e)
> >
> > returns the same answer as drs(n) right down to n=1.
>
>Then 1 certainly isn't the smallest n for which equality fails .
OK, I get it now:
>>> def notsame():
n = 1
while altdrs(n)==drs(n):
n = n+1
return n
>>> notsame()
19
>>> drs(19)
44750731559645106
>>> altdrs(19)
44750731559645112.0
I.e. at n=18, we're still in the money:
>>> drs(18)
2355301661033953
>>> altdrs(18)
2355301661033953.0
> > ...
> > while float(v) <> phi:
>
>Note that loops like this may never terminate:
Very true. Would be better to have some loop that detects
when there's no difference between successive iterations
and cuts it off there -- assumes the series is convergent
in a nice way.
Or you could do some abs(target-current)It's a pragmatic ("programming") issue, not a semantic issue: the purpose
>of special-casing 1 and -1 within F.__mul__ would not be to deliver a
>different answer, but to return the correct answer *faster*.
OK, I understand.
My code doesn't do any case checking for 1, -1, but does a lot
of instance checking, as my fraction objects may have matrices
or polynomials to deal with (which doesn't mean I've implemented
rational expressions -- just means you can multiply a polynomial
by (1/2) and have the coefficients be fractions:
>>> p
x**6 + 2*x**5 + 3*x**4 + 4*x**3 + 4*x**2 + 2
>>> p*F(1,2)
(1/2)*x**6 + x**5 + (3/2)*x**4 + 2*x**3 + 2*x**2 - 0*x + 1
^^^
Oops, I see a bug I need to deal with).
Kirby
From matthias@ccs.neu.edu Tue Oct 2 17:19:35 2001
From: matthias@ccs.neu.edu (Matthias Felleisen)
Date: Tue, 2 Oct 2001 12:19:35 -0400 (EDT)
Subject: [Edu-sig] Re: measuring python
In-Reply-To: (edu-sig-request@python.org)
References:
Message-ID: <200110021619.f92GJZF09561@sualocin.ccs.neu.edu>
For a follow-up on the Karlsruhe studies at NASA, see
http://www-aig.jpl.nasa.gov/public/home/gat/lisp-study.html
Since people are slowly figuring out FP in Python, this may
just give you an edge on C++ and Java and others.
-- Matthias
Matthias Felleisen
Professor of Computer Science
Northeastern University, Boston
Rice University, Houston
See http://www.teach-scheme.org/ for a new look at high school computing.
From WHITSTON@ltu.edu Tue Oct 2 17:31:36 2001
From: WHITSTON@ltu.edu (WHITSTON@ltu.edu)
Date: Tue, 02 Oct 2001 12:31:36 -0400 (EDT)
Subject: [Edu-sig] [OT] Question
Message-ID: <01K90XINKAOO94DNS4@LTU.EDU>
To all:
I have an "OT" type question and please respond to me privately.
Are any of you members of SIGCSE of ACM (special interest group - computer
science education of The Association of Computing Machinery)?
If so, are you attending SIG-CSE 2002? (I know it is two questions...)
Thanks
Howard Whitston
Instructional Technology Specialist/Adjunct Professor
Lawrence Technological University
whitston@ltu.edu
From urnerk@qwest.net Tue Oct 2 18:05:13 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Tue, 02 Oct 2001 10:05:13 -0700
Subject: [Edu-sig] Re: measuring python
In-Reply-To: <200110021619.f92GJZF09561@sualocin.ccs.neu.edu>
References:
Message-ID: <4.2.0.58.20011002095058.019a8220@pop3.norton.antivirus>
At 12:19 PM 10/2/2001 -0400, Matthias Felleisen wrote:
>For a follow-up on the Karlsruhe studies at NASA, see
>
> http://www-aig.jpl.nasa.gov/public/home/gat/lisp-study.html
>
>Since people are slowly figuring out FP in Python, this may
>just give you an edge on C++ and Java and others.
>
>-- Matthias
Interesting to me that Lisp and Scheme would be lumped as
a single unit, that the authors saw no reason to differentiate
between them.
Were any statistical differences between the Lisp and
Scheme groups, either in terms of development, runtime or
memory size. Seems the samples were kinda small (2 and
3 entries respectively).
Question: are the "fast, mature" compilers and IDEs used
in this study as freely available as javac and gcc. I.e.
the trial version of Allegro CL can't be used freely except
for homework and learning purposes. Could it be that the
"mystery" of LISP's not being widespread has something
to do with its affordability?
Kirby
From urnerk@qwest.net Wed Oct 3 07:17:16 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Tue, 02 Oct 2001 23:17:16 -0700
Subject: [Edu-sig] Python Tutorial for Math Teachers
In-Reply-To: <20011003001946.C10273@harmony.cs.rit.edu>
References: <004d01c14ba1$4a19b0a0$45814cd8@joeltklrijxxms>
<001901c14b98$49be3940$45814cd8@joeltklrijxxms>
<20011002194751.E6956@harmony.cs.rit.edu>
<004d01c14ba1$4a19b0a0$45814cd8@joeltklrijxxms>
Message-ID: <4.2.0.58.20011002231249.00a6b220@pop3.norton.antivirus>
Here's a little tutorial I posted for math teachers,
using the challenge of programming a Fraction class
-- something to use as an on-ramp, in the context of
the Python-endowed math classroom (something we'll be
seeing more of, I expect):
http://www.mathforum.com/epigone/math-learn/starcrumderm
Kirby
From rkr_ii@yahoo.com Wed Oct 3 17:03:17 2001
From: rkr_ii@yahoo.com (Robert Rickenbrode II)
Date: Wed, 03 Oct 2001 12:03:17 -0400
Subject: [Edu-sig] Math weirdness?
Message-ID: <5.0.2.1.0.20011003115848.00a79bd0@pop.mail.yahoo.com>
Hey folks, can someone explain these to me:
>>> import math
>>> math.pi
3.1415926535897931
>>> round (math.pi, 3)
3.1419999999999999
>>>
and this:
>>> 10./3
3.3333333333333335
These are taken from IDLE on a Win98 machine running Python 2.1.1:
>>> import sys
>>> print sys.version
2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)]
Thanks, Rob
Robert K. Rickenbrode II
rkr_ii@yahoo.com
From com-nospam@ccraig.org Wed Oct 3 19:58:51 2001
From: com-nospam@ccraig.org (Christopher A. Craig)
Date: 03 Oct 2001 14:58:51 -0400
Subject: [Edu-sig] Math weirdness?
In-Reply-To: <5.0.2.1.0.20011003115848.00a79bd0@pop.mail.yahoo.com>
References: <5.0.2.1.0.20011003115848.00a79bd0@pop.mail.yahoo.com>
Message-ID: <87snd0wnx0.fsf@elbereth.ccraig.org>
Robert Rickenbrode II writes:
> Hey folks, can someone explain these to me:
>
> >>> import math
> >>> math.pi
> 3.1415926535897931
> >>> round (math.pi, 3)
> 3.1419999999999999
> >>>
>
>
> and this:
>
> >>> 10./3
> 3.3333333333333335
These are floating point numbers. They do not (and cannot) map to
decimal numbers with 100% precision. Please see the FAQ at
http://www.python.org/doc/FAQ.html#4.98
There are BCD modules available if you really need your numbers to be
decimal, but you pay a price in performance. I haven't ever needed
this, so I can't point you to one.
If you really need rationals you can use a rational number module of
which there are several good ones available. I wrote a module which
is currently in testing called crat
(http://prdownloads.sourceforge.net/pythonic/crat-0.4.tar.gz). The
mxNumber (http://www.lemburg.com/files/python/mxNumber.html) module
contains a rational type based on the GNU Multiprecision Library
(gmp). There are also modules available called surd and yarn, but I
haven't seen them since the ftp.python.org re-org. For these you will
pay an even bigger performance price.
I can't help you with irrational numbers like pi. They by definition
can't be represented with 100% precision. (Except, of course, by
saying "pi")
--
Christopher A. Craig
"The shortest distance between two points is usually torn up." Frank Walsh
From urnerk@qwest.net Wed Oct 3 20:15:15 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Wed, 03 Oct 2001 12:15:15 -0700
Subject: [Edu-sig] Math weirdness?
In-Reply-To: <5.0.2.1.0.20011003115848.00a79bd0@pop.mail.yahoo.com>
Message-ID: <4.2.0.58.20011003120651.00d10e80@pop3.norton.antivirus>
At 12:03 PM 10/3/2001 -0400, Robert Rickenbrode II wrote:
>Hey folks, can someone explain these to me:
>
> >>> import math
> >>> math.pi
>3.1415926535897931
> >>> round (math.pi, 3)
>3.1419999999999999
> >>>
>
>
>and this:
>
> >>> 10./3
>3.3333333333333335
It's the usual floating point thing. Internally, 10./3 is
stored in base 2, and it doesn't have the same repeating
pattern as in decimal. When it chops at the end (it's gotta
chop somewhere), it loses the significant bits that'd enable
it to translate back to a decimal ending in 3, as we would
get in base 10.
Some similar explanation relates to the PI examples.
You'll find floating points have a lot of weird properties.
They don't behave "just like good little decimals". But
this behavior isn't unique to Python. Floating point
specs are spelled out independently of the language,
with a focus on word length and stuff.
Kirby
From cmeyers@guardnet.com Wed Oct 3 20:44:41 2001
From: cmeyers@guardnet.com (Chris Meyers)
Date: Wed, 03 Oct 2001 12:44:41 -0700
Subject: [Edu-sig] Math weirdness?
Message-ID:
10/03/2001 9:03:17 AM, Robert Rickenbrode II wrote:
Interestingly, I get different results on Python 1.5.2 running on a Sparc. For one thing the precision is lower. math.pi is
3.14159265359, and rounding it correctly gives 3.142. 10.0/3 gives 3.33333333333 again 12 digit accuracy. So I think there
is a question whether later versions of Python have broken something in floating point calcuations.
Chris
>Hey folks, can someone explain these to me:
>
> >>> import math
> >>> math.pi
>3.1415926535897931
> >>> round (math.pi, 3)
>3.1419999999999999
> >>>
>
>
>and this:
>
> >>> 10./3
>3.3333333333333335
>
>These are taken from IDLE on a Win98 machine running Python 2.1.1:
> >>> import sys
> >>> print sys.version
>2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)]
>
>Thanks, Rob
>
>Robert K. Rickenbrode II
>rkr_ii@yahoo.com
>
>
>_______________________________________________
>Edu-sig mailing list
>Edu-sig@python.org
>http://mail.python.org/mailman/listinfo/edu-sig
>
From com-nospam@ccraig.org Wed Oct 3 21:02:11 2001
From: com-nospam@ccraig.org (Christopher A. Craig)
Date: 03 Oct 2001 16:02:11 -0400
Subject: [Edu-sig] Math weirdness?
In-Reply-To:
References:
Message-ID: <87r8skh4qk.fsf@elbereth.ccraig.org>
"Chris Meyers" writes:
> 10/03/2001 9:03:17 AM, Robert Rickenbrode II wrote:
>
> Interestingly, I get different results on Python 1.5.2 running on a
> Sparc. For one thing the precision is lower. math.pi is
> 3.14159265359, and rounding it correctly gives 3.142. 10.0/3 gives
> 3.33333333333 again 12 digit accuracy. So I think there is a
> question whether later versions of Python have broken something in
> floating point calcuations.
Nope, the earlier ones had something broken in their floating point
representation. 1.6 and later return the full precision of the number
in repr(), older than that Python rounded to 12 decimal digits.
Your Python (1.5.2) still thinks 10./3 is 3.3333333333333335, it just
tells you it's 3.33333333333 because it thinks that will make you feel
better. This scheme presented the interesting problem that
assert(float(repr(f))==f) would fail for some values of 'f' (for
example try 3.3333333333333339).
When 1.6 came out this problem was addressed. You can still get the
old behavior by using str() instead of repr() though.
--
Christopher A. Craig
"Unix-to-Unix Copy Program," said PDP-1. "You will never find a more
wretched hive of bugs and flamers. We must be cautious." - DEC Wars
From tim@zope.com Wed Oct 3 22:41:15 2001
From: tim@zope.com (Tim Peters)
Date: Wed, 3 Oct 2001 17:41:15 -0400
Subject: [Edu-sig] Math weirdness?
In-Reply-To: <5.0.2.1.0.20011003115848.00a79bd0@pop.mail.yahoo.com>
Message-ID:
Please read
http://python.sourceforge.net/devel-docs/tut/node14.html
before panic .
From dinu@reportlab.com Thu Oct 4 09:36:21 2001
From: dinu@reportlab.com (Dinu Gherman)
Date: Thu, 04 Oct 2001 10:36:21 +0200 (CEST)
Subject: [Edu-sig] MD5 in pure Python
Message-ID: <1002184580.3bbc1f8502190@webmail.in-berlin.de>
Hi,
a long while ago there was a crypto thread here. I remember
having posted something about a pure Python MD5 implementa-
tion. As at that time it was a bit buggy I've not released
it, then, but now I've put it into my Starship cabin:
http://starship.python.net/crew/gherman/#md5py
This is reasonably tested against the built-in MD5 module,
but, of course, you should not use it for any serious pur-
pose!
Perhaps, this will help retrigger some crypto-activities?
(I've seen fancy proposals for Python Crypto-APIs, but not
much more.)
Regards,
Dinu
--
Dinu C. Gherman
................................................................
UN Resolution 42/159 on fighting international terrorism (1987),
adopted by 153-2 votes (US and Israel against):
http://www.un.org/documents/ga/res/42/a42r159.htm
From kimtitu@yahoo.com Thu Oct 4 19:02:29 2001
From: kimtitu@yahoo.com (Titu Kim)
Date: Thu, 4 Oct 2001 11:02:29 -0700 (PDT)
Subject: [Edu-sig] How to verify an integer or float string
Message-ID: <20011004180229.19533.qmail@web14704.mail.yahoo.com>
Hi,
I am trying to verify a string is a legal integer
or float. Which method help me to do the job? Thanks a
lot
Kim Titu
__________________________________________________
Do You Yahoo!?
NEW from Yahoo! GeoCities - quick and easy web site hosting, just $8.95/month.
http://geocities.yahoo.com/ps/info1
From schoen@loyalty.org Thu Oct 4 19:26:01 2001
From: schoen@loyalty.org (Seth David Schoen)
Date: Thu, 4 Oct 2001 11:26:01 -0700
Subject: [Edu-sig] How to verify an integer or float string
In-Reply-To: <20011004180229.19533.qmail@web14704.mail.yahoo.com>
References: <20011004180229.19533.qmail@web14704.mail.yahoo.com>
Message-ID: <20011004112601.W1050@zork.net>
Titu Kim writes:
> Hi,
> I am trying to verify a string is a legal integer
> or float. Which method help me to do the job? Thanks a
> lot
Perhaps checking for exceptions in the conversion process:
def can_be_float(s):
try:
float(s)
except ValueError:
return 0
return 1
The float function might raise other exceptions, too; those are the
ones which came to mind quickly. (It doesn't appear to raise an
OverflowError, though.)
It seems to me that, if a string can be a legal integer, it can also
be a legal float.
--
Seth David Schoen | Its really terrible when FBI arrested
Temp. http://www.loyalty.org/~schoen/ | hacker, who visited USA with peacefull
down: http://www.loyalty.org/ (CAF) | mission -- to share his knowledge with
http://www.freesklyarov.org/ | american nation. (Ilya V. Vasilyev)
From urnerk@qwest.net Thu Oct 4 19:40:36 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Thu, 04 Oct 2001 11:40:36 -0700
Subject: [Edu-sig] How to verify an integer or float string
In-Reply-To: <20011004180229.19533.qmail@web14704.mail.yahoo.com>
Message-ID: <4.2.0.58.20011004111525.00c4ea60@pop3.norton.antivirus>
At 11:02 AM 10/4/2001 -0700, Titu Kim wrote:
>Hi,
> I am trying to verify a string is a legal integer
>or float. Which method help me to do the job? Thanks a
>lot
>
>Kim Titu
If you just want a true/false answer as to whether
a string is a float or int, the code below will work.
It only tries to convert to float, because all legal
int strings, including longs, will also convert to
floats.
>>> def isintorfloat(thestring):
try:
thevalue = float(thestring)
return 1
except:
return 0
If you want to screen out long integers, then you need
a slightly more complicated method, employing similar
ideas.
Another approach, if you're not exposing your code to
potentially malicious users over the web, is to use
eval():
>>> type(eval('12'))
>>> type(eval('12909023423423'))
>>> type(eval('1.0'))
So a function might be:
>>> def isintorfloat(thestring):
try:
thevalue = eval(thestring)
if type(thevalue) == type(1):
return (1,int(thestring))
elif type(thevalue) == type(1L):
return (1,long(thestring))
elif type(thevalue) == type(1.0):
return (1,float(thestring))
else:
return (0,0)
except:
return (0,0)
This version not only catches the strings that aren't legal,
it converts them, returning a tuple with 1 or 0 as a first
element (true or false) and the converted string as the 2nd
(but if the first is 0, then the 2nd defaults to 0 and may
be ignored).
>>> isintorfloat('898989289823')
(1, 898989289823L)
>>> isintorfloat('8989892')
(1, 8989892)
>>> isintorfloat('8989892.0')
(1, 8989892.0)
>>> isintorfloat('8989892AAA')
(0, 0)
>>> isintorfloat('[1,2,3]')
(0, 0)
There are ways to make eval safer than shown.
Kirby
From kimtitu@yahoo.com Fri Oct 5 05:27:33 2001
From: kimtitu@yahoo.com (Titu Kim)
Date: Thu, 4 Oct 2001 21:27:33 -0700 (PDT)
Subject: [Edu-sig] How to verify an integer or float string
In-Reply-To: <4.2.0.58.20011004111525.00c4ea60@pop3.norton.antivirus>
Message-ID: <20011005042733.42076.qmail@web14706.mail.yahoo.com>
Thanks Kirby and Seth. I get more details than i
expect. Your replies are very helpful, especially for
the beginner like me.
Kim Titu
--- Kirby Urner wrote:
> At 11:02 AM 10/4/2001 -0700, Titu Kim wrote:
> >Hi,
> > I am trying to verify a string is a legal
> integer
> >or float. Which method help me to do the job?
> Thanks a
> >lot
> >
> >Kim Titu
>
> If you just want a true/false answer as to whether
> a string is a float or int, the code below will
> work.
> It only tries to convert to float, because all legal
> int strings, including longs, will also convert to
> floats.
>
> >>> def isintorfloat(thestring):
> try:
> thevalue = float(thestring)
> return 1
> except:
> return 0
>
> If you want to screen out long integers, then you
> need
> a slightly more complicated method, employing
> similar
> ideas.
>
> Another approach, if you're not exposing your code
> to
> potentially malicious users over the web, is to use
> eval():
>
> >>> type(eval('12'))
>
> >>> type(eval('12909023423423'))
>
> >>> type(eval('1.0'))
>
>
> So a function might be:
>
> >>> def isintorfloat(thestring):
> try:
> thevalue = eval(thestring)
> if type(thevalue) == type(1):
> return (1,int(thestring))
> elif type(thevalue) == type(1L):
> return (1,long(thestring))
> elif type(thevalue) == type(1.0):
> return (1,float(thestring))
> else:
> return (0,0)
> except:
> return (0,0)
>
> This version not only catches the strings that
> aren't legal,
> it converts them, returning a tuple with 1 or 0 as a
> first
> element (true or false) and the converted string as
> the 2nd
> (but if the first is 0, then the 2nd defaults to 0
> and may
> be ignored).
>
> >>> isintorfloat('898989289823')
> (1, 898989289823L)
> >>> isintorfloat('8989892')
> (1, 8989892)
> >>> isintorfloat('8989892.0')
> (1, 8989892.0)
> >>> isintorfloat('8989892AAA')
> (0, 0)
> >>> isintorfloat('[1,2,3]')
> (0, 0)
>
> There are ways to make eval safer than shown.
>
> Kirby
>
>
> _______________________________________________
> Edu-sig mailing list
> Edu-sig@python.org
> http://mail.python.org/mailman/listinfo/edu-sig
__________________________________________________
Do You Yahoo!?
NEW from Yahoo! GeoCities - quick and easy web site hosting, just $8.95/month.
http://geocities.yahoo.com/ps/info1
From kimtitu@yahoo.com Tue Oct 9 02:12:46 2001
From: kimtitu@yahoo.com (Titu Kim)
Date: Mon, 8 Oct 2001 18:12:46 -0700 (PDT)
Subject: [Edu-sig] Disable Cookie when user close browser
Message-ID: <20011009011246.5656.qmail@web14701.mail.yahoo.com>
Hi,
How can i disable the cookie after user closes the
browser? I can disable user by setting the expire time
to certain value. But i wish i could disable cookie
when users close their browsers. Any suggestion is
very appreciated.
Kim titu
__________________________________________________
Do You Yahoo!?
NEW from Yahoo! GeoCities - quick and easy web site hosting, just $8.95/month.
http://geocities.yahoo.com/ps/info1
From dustin@cs.uchicago.edu Tue Oct 9 02:37:31 2001
From: dustin@cs.uchicago.edu (Dustin Mitchell)
Date: Mon, 8 Oct 2001 20:37:31 -0500 (CDT)
Subject: [Edu-sig] Disable Cookie when user close browser
In-Reply-To: <20011009011246.5656.qmail@web14701.mail.yahoo.com>
Message-ID:
On Mon, 8 Oct 2001, Titu Kim wrote:
> How can i disable the cookie after user closes the
> browser? I can disable user by setting the expire time
> to certain value. But i wish i could disable cookie
> when users close their browsers. Any suggestion is
> very appreciated.
IIRC, the cookie RFC (RFC2109, http://www.rfc-editor.org/rfc/rfc2109.txt)
states that a cookie without an expiration will be discarded when the user
closes the browser. At a cursory look, I can't find the chapter and
verse, but I'm pretty sure it's in there. Netscape's cookie page
(http://home.netscape.com/newsref/std/cookie_spec.html) *does* spell this
out explicitly.
Enjoy.
Dustin
--
Dustin Mitchell
dustin@cs.uchicago.edu
dustin@ywlcs.org
From cmeyers@guardnet.com Thu Oct 11 16:36:54 2001
From: cmeyers@guardnet.com (Chris Meyers)
Date: Thu, 11 Oct 2001 08:36:54 -0700
Subject: [Edu-sig] Thanks for the tip
Message-ID:
I would like to thank Jason for his recent recommedation of "Who is Fourier? A Mathematical Adventure" translated from
Japanese by Alan Gleason. I bought a copy last week. The book is an absolute delight and should be read by both students
interested in math/science and anyone *teaching* math or math-like subjects. For details read the reader reviews on
amazon.com (it gets almost unanimous 5 star ratings). A friend has also ordered "What is Quantum Mechanics? A Physics
Adventure" by the same folks. Looking forward to it.
Thanks
Chris
From Jason Cunliffe"
Message-ID: <00ec01c1529e$cb5f10c0$c3090740@megapathdsl.net>
Chris
Yes Delighted you picked up on the book :-)
I believe a remarkable model of how a new kind of teaching can be done.. I
wish this were available in every Public and School library.
I would love to see it Python-ized. In other words publish a new edition:
Who is Fourier? A mathematical Adventure with Python
This should not be too hard to do, since the book is so well structured. It
could be another valuable curriculum tool to add those already being
developed by Edu-sig members.
Inspired by the book and curious about its origins, I did attend a 'Hippo
Family Club' meeting in Manhattan some months ago and mentioned I was
interested in extending the book... 'Hippo' is the multi-lingual
pan-cultural organization, some of whose members wrote "Who is Fourier?" and
the Quantum Mechanics follow-up. My interest in extensions would be:
1. Web-ify the text and add interactive Flash illustrations
2. CDROM edition
3. Pythonize it as new edition book
4. Pythonize it as new edition book with CD-ROM and some appropriate
focused shell/IDE [wxPython/PythonCard/??]
5. Go further with new work in the spirit of Who is Fourier
The immediate problem is perhaps you don;t know what I am talking about:
that most people on this list may not be familiar with the book.. I wish I
could send you all a copy for Xmas.. or perhaps buy an extra copy and mail
out along with mine so we circulate it..? [Edu-Sig nomadics library]
Open to your good suggestions as always, and curious to get feedback on The
Quantum Mechanics [I still don't have a copy myself]
regards
- Jason
Who Is Fourier? : A Mathematical Adventure
by Alan Gleason (Translator), Yo Sakakibara (Introduction),
Transnational College of LEX
Price: $24.95
Paperback (May 1995)
http://www.amazon.com/exec/obidos/ASIN/0964350408/qid%3D1002836293/ref%3Dsr%
5F11%5F0%5F1/103-0619731-5648610
----- Original Message -----
From: "Chris Meyers"
To:
Sent: Thursday, October 11, 2001 11:36 AM
Subject: Re: [Edu-sig] Thanks for the tip
> I would like to thank Jason for his recent recommedation of "Who is
Fourier? A Mathematical Adventure" translated from
> Japanese by Alan Gleason. I bought a copy last week. The book is an
absolute delight and should be read by both students
> interested in math/science and anyone *teaching* math or math-like
subjects. For details read the reader reviews on
> amazon.com (it gets almost unanimous 5 star ratings). A friend has also
ordered "What is Quantum Mechanics? A Physics
> Adventure" by the same folks. Looking forward to it.
>
> Thanks
> Chris
From urnerk@qwest.net Fri Oct 12 00:31:26 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Thu, 11 Oct 2001 16:31:26 -0700
Subject: [Edu-sig] Thanks for the tip
In-Reply-To: <00ec01c1529e$cb5f10c0$c3090740@megapathdsl.net>
References:
Message-ID: <4.2.0.58.20011011163104.00c57df0@pop3.norton.antivirus>
I'm looking forward to reading this too.
Kirby
From cmeyers@guardnet.com Fri Oct 12 19:09:14 2001
From: cmeyers@guardnet.com (Chris Meyers)
Date: Fri, 12 Oct 2001 11:09:14 -0700
Subject: [Edu-sig] Thanks for the tip
Message-ID:
Hi Jason
I agree it would be great if the book "Who was Fourier.." was available on the web and extended with Python as you
suggest. I wonder if the contents could be used in the open source arena. Of course extending the book like this would be a
*large* undertaking.
The HIPPO club also is intriguing. Too bad there are only two in the U.S. and both out your way. Oregon is a long way from
New York.
One question that I have. Do students take to this book as enthusiastically as teachers and professionals? Students aren't
likely to have had as much exposure previous exposure to the underlying ideas. For many of us, much of the book can be
kind of a "cute" review that then leads to some surprising insights.
The book has students doing a fair amount of calculation by hand and that's probably a very good way to hammer home the
ideas. Those might also be places where students could develope small Python programs to do the calculations as well,
getting double mileage from the exercise.
I'm thinking of a small project to develope an object class of "wave". A simple wave can be generated from a formula.
Operations like addition and multiplication of waves create new and more complex waves. You can play with them at the
python interactive prompt. And of course plot them. With a method to integrate a wave it would be straightforward to
rediscover the Fourier coefficients using the technique in the book interactively. Then further automation. Maybe a "Python
for Fun" project.
I've been playing with David Petterssons little frame buffer module that lays on top of SDL. It would be fine for plotting
the waves. Right now it's busy hosting turtles in random motion while I'm trying to figure out if StarLogo-like programs can be
done effectively in Python.
Chris
From delza@landry.alliances.org Fri Oct 12 18:45:42 2001
From: delza@landry.alliances.org (delza@landry.alliances.org)
Date: Fri, 12 Oct 2001 17:45:42 +0000 (Local time zone must be set--see zic manual page)
Subject: [Edu-sig] Logo in Python
Message-ID: <20011012174542.79B834E98D@landry.alliances.org>
There seems to be a lot of interest in recreating a Logo-like environment
in Python. I keep seeing people re-doing this (I've re-done it myself).
Is there any interest in joining forces to build something or at least bounce
ideas around?
--Dethe
==========================================================================
| dethe@burningtiger.com | http://livingcode.manilasites.com |
==========================================================================
"Well I've wrestled with reality for thirty-five years now, doctor, and I'm
happy to state I've finally won out over it." -- Elwood P. Dowd, Harvey
From cmeyers@guardnet.com Fri Oct 12 20:07:45 2001
From: cmeyers@guardnet.com (Chris Meyers)
Date: Fri, 12 Oct 2001 12:07:45 -0700
Subject: [Edu-sig] Logo in Python
Message-ID:
>There seems to be a lot of interest in recreating a Logo-like environment
>in Python. I keep seeing people re-doing this (I've re-done it myself).
>
>Is there any interest in joining forces to build something or at least bounce
>ideas around?
>
Sure. Although we probably want to make sure we're talking about the same thing. Starlogo, a spinoff of Logo, is a language
described in the book Turtles, Termites and Traffic Jams (Resnick, MIT) for writing massively parrallel programs. A good example
is the program where ants find food and bring it back to the nest. I'm not trying to recreate the language, just make a set of base
classes that provide all of the common functionality for turtles, patches and an observer. You would subclass these for your
particular program. This is only my first idea and I've got just a couple of days work into it. I'm happy to pass the code around (let
me make it work first!) and would enjoy hearing other ideas too.
Thanks, Chris
From urner@alumni.princeton.edu Fri Oct 12 22:10:27 2001
From: urner@alumni.princeton.edu (Kirby Urner)
Date: Fri, 12 Oct 2001 14:10:27 -0700
Subject: [Edu-sig] Review of Some Math-Through-Programming Themes
Message-ID:
Review of Some Math-Through-Programming Themes
by K. Urner, Oct 12, 2001
My suggestion to curriculum writers has been to return
to the front pioneered using BASIC and Logo: integrate
the teaching of paper and pencil algorithms with the=20
coding of same in some computer language, so that=20
students reap the benefits of contemporary engineering.
Once programming enters the picture, I prefer a general
purpose computer language to a calculator language, as
these latter don't supply as broad a foundation in=20
programming, plus the development environment is cramped.
I've advocated using this approach starting around 8th=20
grade to learn math concepts by building math objects.
This is a sort of hands-on approach, suggestive of shop
class or labs, wherein we actually construct gizmos=20
which embody our understanding of the relevant ideas.
A first object we might construct is the Fraction object.
I emphasize "object" because, unlike with the Logo or BASIC=20
languages of the 1980s, we're now in a position to introduce
students to a later programming paradigm, that of objects.
This doesn't have to be considered "advanced" -- it's just
a paradigm. Newcomers to programming might start with=20
classes and objects just as new users of telephones might=20
start with a wireless unit.
The object-oriented approach turns out to be especially handy=20
in mathematics learning, as it often allows us to keep our=20
syntax relatively close to that of the traditional text book=20
notations. For example, with Fraction objects, symbolized by=20
=46, we can add, subtract, multiply, divide, and raise them to=20
powers just as we would integers, i.e. with the direct application=20
of the relevant operators:
>>> from mathobjects import Fraction as F
>>> F(1,2)
(1/2)
>>> F(1,2) + F(1,3) + F(3,7)
(53/42)
>>> F(2,3) * F(1,2)
(1/3)
>>> F(3,5)**2
(9/25)
So what? Don't calculators also allow such expressions using=20
numerators and denominators? Sure, many do. The fun and instructive
part is that we coded the Fraction object ourselves, and therefore=20
had to develop our understanding of the role of GCD and LCD in these=20
various operations. We actually "built" the object we're now using
in the above, simple, expressions.[1] (Note that we'll use the
Euclidean Algorithm (EA) to implement GCD -- we really need to=20
bring this ancient method back into pre-algebra, (later we'll=20
introduce and use the extended version or EEA, which plays a=20
critical role in RSA cryptography)).[2]
So now that we have a Fraction object, we'd like to explore
other algorithms in which Fractions occur, and which would=20
be tedious and error-prone if figured on pencil and paper.
In other words, we want to understand the paper and pencil=20
way of doing things, but then code them so we can do the=20
calculations quickly and reliably.
Note that I'm not talking about approximating precise answers
with floating point operations in this context. On the=20
contrary, now that we have fraction objects, we're in a=20
position to push beyond what floating point numbers are able
to tell us. We'll stay in the realm of purely rational=20
numbers p/q, where p and q are both whole (q nonzero).
So far, I've explored and written up three useful topics to=20
which our newly developed fraction object might apply:
(1) Continued Fractions (recursion, phi)
http://www.mathforum.com/epigone/math-teach/smersmarzand
(2) Derangements (more links to combinatorics)
http://aspn.activestate.com/ASPN/Mail/Message/edu-sig/788963
(3) Bernoulli numbers (links to Pascal's Triangle)
http://www.mathforum.com/epigone/nctm.l/flanghoupah
All of the above make use of the Fraction object in ways=20
that would be relatively difficult and tedious with paper=20
and pencil. However, by tackling the algorithms and concepts
behind the scenes, we nevertheless gain exposure to important
techniques and generalizations, as well as history.
The Bernoulli numbers thread provides a segue to another=20
math object, the polynomial. They also make an appearance=20
in the context I recently posted about: figurate numbers, as=20
per the approach taken in 'The Book of Numbers' in Conway and=20
Guy, and posted about by myself under the heading of 'Pool
Hall Math' (because we're stacking/packing pool balls).[3]
After we build the Fraction and Polynomial objects, and use
these to anchor a lot of relevant mathematics, we'll move=20
on the the Vector and Matrix objects (which synergize with
the previous objects, e.g. the characteristic polynomial
of a square matrix -- which might have fractional coefficients).[4]
=46inally, we might also develop Polyhedron objects, using=20
the matrix and vector objects as a part of their definition.
The generic methods for rotating, translating, scaling a poly
go in the superclass definition, while the individual polyhedra
are defined as subclasses (this follows a classic OO text book=20
model, except usually the text books stick with planar shapes,
which are less beautiful and interesting -- why not use the
technology to its fuller potential?).
Note: rotation of polyhedra provides a segue to quaternion=20
objects if we like -- another way of implementing rotation.[5]
All of this connects back to my 'Trends in Early Mathematics Learning'
essay, wherein I envision a greater integration of math education
and computer science under the more generic umbrella of "numeracy".[6]
Kirby
[1] Tutorial on developing a Fraction object using the=20
Python language, posted to math-learn:
http://www.mathforum.com/epigone/math-learn/starcrumderm
[2] Euclidean Algorithm
http://www.mathforum.com/epigone/math-learn/vultingsheld =20
http://www.mathforum.com/epigone/nctm.l/sangjalskeld
[3] Pool Hall Math
http://www.mathforum.com/epigone/nctm.l/ningdimfrimp =20
[4] Characteristic polynomials using mathobjects
http://aspn.activestate.com/ASPN/Mail/Message/580745
[5] 'Getting Inventive with Vectors' (CP4E 4-part essay)
http://www.inetarena.com/~pdx4d/ocn/numeracy1.html
[6] 'Trends in Early Mathematics Learning: Beyond Y2K'
http://www.inetarena.com/~pdx4d/ocn/trends2000.html
From bic@cgl.ucsf.edu Fri Oct 12 22:44:35 2001
From: bic@cgl.ucsf.edu (Bruce Cohen)
Date: Fri, 12 Oct 2001 14:44:35 -0700
Subject: [Edu-sig] Review of Some Math-Through-Programming Themes
In-Reply-To:
Message-ID: <542BF95A-BF5A-11D5-B231-003065CAF786@cgl.ucsf.edu>
--Apple-Mail-1-993555626
Content-Transfer-Encoding: 7bit
Content-Type: text/plain;
charset=US-ASCII;
format=flowed
Kirby-
Thanks for the posting. I particularly like this paragraph:
> A first object we might construct is the Fraction object.
> I emphasize "object" because, unlike with the Logo or BASIC
> languages of the 1980s, we're now in a position to introduce
> students to a later programming paradigm, that of objects.
> This doesn't have to be considered "advanced" -- it's just
> a paradigm. Newcomers to programming might start with
> classes and objects just as new users of telephones might
> start with a wireless unit.
All too often, we (in the math education world) hear people say students
must master paper and pencil skills before they may be allowed to touch
calculators and computers. We don't need to have kids replicate the
experience of their grandparents. On the other hand, maybe we should
have 6 year olds learn to use a dial phone before we let them use a
touchtone phone ... :-)
-Bruce
Bruce Cohen | e-mail: bic@cgl.ucsf.edu
Lowell High School | http://www.cgl.ucsf.edu/home/bic
--Apple-Mail-1-993555626
Content-Transfer-Encoding: 7bit
Content-Type: text/enriched;
charset=US-ASCII
Kirby-
Thanks for the posting. I particularly like this paragraph:
A first object we might construct is the Fraction object.
I emphasize "object" because, unlike with the Logo or BASIC
languages of the 1980s, we're now in a position to introduce
students to a later programming paradigm, that of objects.
This doesn't have to be considered "advanced" -- it's just
a paradigm. Newcomers to programming might start with
classes and objects just as new users of telephones might
start with a wireless unit.
All too often, we (in the math education world) hear people say
students must master paper and pencil skills before they may be
allowed to touch calculators and computers. We don't need to have
kids replicate the experience of their grandparents. On the other
hand, maybe we should have 6 year olds learn to use a dial phone
before we let them use a touchtone phone ... :-)
-Bruce
Bruce Cohen | e-mail: bic@cgl.ucsf.edu
Lowell High School |
http://www.cgl.ucsf.edu/home/bic
--Apple-Mail-1-993555626--
From pobrien@orbtech.com Fri Oct 12 22:53:14 2001
From: pobrien@orbtech.com (Patrick K. O'Brien)
Date: Fri, 12 Oct 2001 16:53:14 -0500
Subject: [Edu-sig] Review of Some Math-Through-Programming Themes
In-Reply-To:
Message-ID:
Kirby,
As much as you like coding directly in the Python shell, I was wondering if
you had tried the PyCrust shell (http://sourceforge.net/projects/pycrust/).
It has a couple of features that I think are particularly well suited to
students:
1. Call tips for functions and methods that display the parameters required
and the documentation string. This information pops up in a balloon-style
box underneath the current line of code when you type in a function followed
by a left parenthesis.
2. Command auto-completion that pops up a list of valid attributes
(properties and methods) for the current object whenever you type an object
name followed by a dot.
3. Colorized code, and basic syntax checking.
4. Namespace inspection through a tree control that allows you to drill down
through all objects in the current local namespace. Objects selected in the
tree control display information about themselves, including the source code
upon which they are based.
5. You can create applications in wxPython or Tkinter or scipy or PythonCard
directly in the shell and control them interactively without the lockups or
conflicts that you have in other shells. It even works with Zope and ZODB.
I use PyCrust every day and rely on these features to help me understand
what is really happening in the Python environment, and to reduce keying
errors. Of course, I wrote PyCrust, so I'm biased. Which is why I'd love to
hear from the education community. If you are using PyCrust, or having
suggestions for improvement, please send them my way. Thanks.
---
Patrick K. O'Brien
Orbtech (http://www.orbtech.com)
"I am, therefore I think."
-----Original Message-----
From: edu-sig-admin@python.org [mailto:edu-sig-admin@python.org]On Behalf Of
Kirby Urner
Sent: Friday, October 12, 2001 4:10 PM
To: mathedcc@mathforum.com
Cc: edu-sig@python.org
Subject: [Edu-sig] Review of Some Math-Through-Programming Themes
Review of Some Math-Through-Programming Themes
by K. Urner, Oct 12, 2001
My suggestion to curriculum writers has been to return
to the front pioneered using BASIC and Logo: integrate
the teaching of paper and pencil algorithms with the
coding of same in some computer language, so that
students reap the benefits of contemporary engineering.
Once programming enters the picture, I prefer a general
purpose computer language to a calculator language, as
these latter don't supply as broad a foundation in
programming, plus the development environment is cramped.
I've advocated using this approach starting around 8th
grade to learn math concepts by building math objects.
This is a sort of hands-on approach, suggestive of shop
class or labs, wherein we actually construct gizmos
which embody our understanding of the relevant ideas.
A first object we might construct is the Fraction object.
I emphasize "object" because, unlike with the Logo or BASIC
languages of the 1980s, we're now in a position to introduce
students to a later programming paradigm, that of objects.
This doesn't have to be considered "advanced" -- it's just
a paradigm. Newcomers to programming might start with
classes and objects just as new users of telephones might
start with a wireless unit.
The object-oriented approach turns out to be especially handy
in mathematics learning, as it often allows us to keep our
syntax relatively close to that of the traditional text book
notations. For example, with Fraction objects, symbolized by
F, we can add, subtract, multiply, divide, and raise them to
powers just as we would integers, i.e. with the direct application
of the relevant operators:
>>> from mathobjects import Fraction as F
>>> F(1,2)
(1/2)
>>> F(1,2) + F(1,3) + F(3,7)
(53/42)
>>> F(2,3) * F(1,2)
(1/3)
>>> F(3,5)**2
(9/25)
So what? Don't calculators also allow such expressions using
numerators and denominators? Sure, many do. The fun and instructive
part is that we coded the Fraction object ourselves, and therefore
had to develop our understanding of the role of GCD and LCD in these
various operations. We actually "built" the object we're now using
in the above, simple, expressions.[1] (Note that we'll use the
Euclidean Algorithm (EA) to implement GCD -- we really need to
bring this ancient method back into pre-algebra, (later we'll
introduce and use the extended version or EEA, which plays a
critical role in RSA cryptography)).[2]
So now that we have a Fraction object, we'd like to explore
other algorithms in which Fractions occur, and which would
be tedious and error-prone if figured on pencil and paper.
In other words, we want to understand the paper and pencil
way of doing things, but then code them so we can do the
calculations quickly and reliably.
Note that I'm not talking about approximating precise answers
with floating point operations in this context. On the
contrary, now that we have fraction objects, we're in a
position to push beyond what floating point numbers are able
to tell us. We'll stay in the realm of purely rational
numbers p/q, where p and q are both whole (q nonzero).
So far, I've explored and written up three useful topics to
which our newly developed fraction object might apply:
(1) Continued Fractions (recursion, phi)
http://www.mathforum.com/epigone/math-teach/smersmarzand
(2) Derangements (more links to combinatorics)
http://aspn.activestate.com/ASPN/Mail/Message/edu-sig/788963
(3) Bernoulli numbers (links to Pascal's Triangle)
http://www.mathforum.com/epigone/nctm.l/flanghoupah
All of the above make use of the Fraction object in ways
that would be relatively difficult and tedious with paper
and pencil. However, by tackling the algorithms and concepts
behind the scenes, we nevertheless gain exposure to important
techniques and generalizations, as well as history.
The Bernoulli numbers thread provides a segue to another
math object, the polynomial. They also make an appearance
in the context I recently posted about: figurate numbers, as
per the approach taken in 'The Book of Numbers' in Conway and
Guy, and posted about by myself under the heading of 'Pool
Hall Math' (because we're stacking/packing pool balls).[3]
After we build the Fraction and Polynomial objects, and use
these to anchor a lot of relevant mathematics, we'll move
on the the Vector and Matrix objects (which synergize with
the previous objects, e.g. the characteristic polynomial
of a square matrix -- which might have fractional coefficients).[4]
Finally, we might also develop Polyhedron objects, using
the matrix and vector objects as a part of their definition.
The generic methods for rotating, translating, scaling a poly
go in the superclass definition, while the individual polyhedra
are defined as subclasses (this follows a classic OO text book
model, except usually the text books stick with planar shapes,
which are less beautiful and interesting -- why not use the
technology to its fuller potential?).
Note: rotation of polyhedra provides a segue to quaternion
objects if we like -- another way of implementing rotation.[5]
All of this connects back to my 'Trends in Early Mathematics Learning'
essay, wherein I envision a greater integration of math education
and computer science under the more generic umbrella of "numeracy".[6]
Kirby
[1] Tutorial on developing a Fraction object using the
Python language, posted to math-learn:
http://www.mathforum.com/epigone/math-learn/starcrumderm
[2] Euclidean Algorithm
http://www.mathforum.com/epigone/math-learn/vultingsheld
http://www.mathforum.com/epigone/nctm.l/sangjalskeld
[3] Pool Hall Math
http://www.mathforum.com/epigone/nctm.l/ningdimfrimp
[4] Characteristic polynomials using mathobjects
http://aspn.activestate.com/ASPN/Mail/Message/580745
[5] 'Getting Inventive with Vectors' (CP4E 4-part essay)
http://www.inetarena.com/~pdx4d/ocn/numeracy1.html
[6] 'Trends in Early Mathematics Learning: Beyond Y2K'
http://www.inetarena.com/~pdx4d/ocn/trends2000.html
_______________________________________________
Edu-sig mailing list
Edu-sig@python.org
http://mail.python.org/mailman/listinfo/edu-sig
From urnerk@qwest.net Fri Oct 12 22:59:35 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Fri, 12 Oct 2001 14:59:35 -0700
Subject: [Edu-sig] Review of Some Math-Through-Programming Themes
In-Reply-To:
References:
Message-ID: <4.2.0.58.20011012145811.00a7cf00@pop3.norton.antivirus>
At 04:53 PM 10/12/2001 -0500, Patrick K. O'Brien wrote:
>Kirby,
>
>As much as you like coding directly in the Python shell,
>I was wondering if you had tried the PyCrust shell
>(http://sourceforge.net/projects/pycrust/).
I've been putting this off, only because I find IDLE fairly
satisfying. However, you've persuaded me I take your pycrust
for a test drive. I plan to do so ASAP (like now).
Kirby
From urnerk@qwest.net Fri Oct 12 23:33:17 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Fri, 12 Oct 2001 15:33:17 -0700
Subject: [Edu-sig] PyCrust
In-Reply-To:
References:
Message-ID: <4.2.0.58.20011012151700.00bf49e0@pop3.norton.antivirus>
OK, didn't take long to install. Had to get
wxPython, for which I didn't find an installer
for 2.2. Probably easy enough to do that, but
I'm with 2.1 now. Your PyCrust installer
helpfully found both installations -- I picked
2.1 (BTW, does wxPython work on Mac? -- seems
PyCrust blurb say yours does, yet wxPython page
mentions only Windows, POSIX -- which I guess
includes OSX).
So I have PyCrust open, and it does the shell
mode fine. I like the tips.
I gather there's no builtin program editor ala
IDLE. I should use Scintilla or something like
that?
Any way to change default colors? I'm used to
the IDLE color scheme and/or would like the
returned values ("computer types...") to be a
different color (like blue).
The response seems pretty snappy on the whole.
One thing that's cool about IDLE is if I have
a multi-line function or class defined at the shell
prompt, I can scroll back and click on any of these
lines to get a full copy of the whole function or
class -- which I may now edit/revise. Having only
a single line copy down doesn't allow easy re-editing.
If I use copy/paste, I can get multiple lines, but
the interpreter seems to only recogize the last
one.
Maybe there's something planned around line numbers
(on the left) that'd let me do this. If there's
a way to turn the line numbers off, that'd be cool
too, as they haven't a lot of meaning to me in shell
mode, the way I think about it today anyway.
Not finding a lot of docs (or any, yet), so maybe
I'm not booting pyCrust the best way. I open DOS
box and go ..\python pycrust.py
I could convert that into a PIF, or else there's
the option to use the .pyw extension. Lemme try
renaming pycrust.py to pycrust.pyw and booting it
by clicking in the file manager...
Yeah, that works (had to change the file association
from python22\python to python21\python -- not a
problem). Note: the blinking cursor after the
prompt doesn't appear on its own when booting.
I have to click in that window, then it shows after
a second or two.
Kirby
From kevino@tulane.edu Fri Oct 12 23:58:20 2001
From: kevino@tulane.edu (Kevin Ollivier)
Date: Fri, 12 Oct 2001 18:58:20 -0400
Subject: [Edu-sig] PyCrust
References: <4.2.0.58.20011012151700.00bf49e0@pop3.norton.antivirus>
Message-ID: <00e201c15371$64309580$2101a8c0@kevinnew>
Hi Kirby,
Thought I would chirp in here and let you know wxPython does not work on Mac
OS X -- yet. It's a work in progress. I do know it's being worked on though,
and I'm pretty sure wxPython for Mac will sport it's Aqua interface when its
all done. =)
Kevin
----- Original Message -----
From: "Kirby Urner"
To:
Cc:
Sent: Friday, October 12, 2001 6:33 PM
Subject: [Edu-sig] PyCrust
>
> OK, didn't take long to install. Had to get
> wxPython, for which I didn't find an installer
> for 2.2. Probably easy enough to do that, but
> I'm with 2.1 now. Your PyCrust installer
> helpfully found both installations -- I picked
> 2.1 (BTW, does wxPython work on Mac? -- seems
> PyCrust blurb say yours does, yet wxPython page
> mentions only Windows, POSIX -- which I guess
> includes OSX).
>
> So I have PyCrust open, and it does the shell
> mode fine. I like the tips.
>
> I gather there's no builtin program editor ala
> IDLE. I should use Scintilla or something like
> that?
>
> Any way to change default colors? I'm used to
> the IDLE color scheme and/or would like the
> returned values ("computer types...") to be a
> different color (like blue).
>
> The response seems pretty snappy on the whole.
>
> One thing that's cool about IDLE is if I have
> a multi-line function or class defined at the shell
> prompt, I can scroll back and click on any of these
> lines to get a full copy of the whole function or
> class -- which I may now edit/revise. Having only
> a single line copy down doesn't allow easy re-editing.
> If I use copy/paste, I can get multiple lines, but
> the interpreter seems to only recogize the last
> one.
>
> Maybe there's something planned around line numbers
> (on the left) that'd let me do this. If there's
> a way to turn the line numbers off, that'd be cool
> too, as they haven't a lot of meaning to me in shell
> mode, the way I think about it today anyway.
>
> Not finding a lot of docs (or any, yet), so maybe
> I'm not booting pyCrust the best way. I open DOS
> box and go ..\python pycrust.py
>
> I could convert that into a PIF, or else there's
> the option to use the .pyw extension. Lemme try
> renaming pycrust.py to pycrust.pyw and booting it
> by clicking in the file manager...
>
> Yeah, that works (had to change the file association
> from python22\python to python21\python -- not a
> problem). Note: the blinking cursor after the
> prompt doesn't appear on its own when booting.
> I have to click in that window, then it shows after
> a second or two.
>
> Kirby
>
>
> _______________________________________________
> Edu-sig mailing list
> Edu-sig@python.org
> http://mail.python.org/mailman/listinfo/edu-sig
>
From pobrien@orbtech.com Sat Oct 13 00:33:15 2001
From: pobrien@orbtech.com (Patrick K. O'Brien)
Date: Fri, 12 Oct 2001 18:33:15 -0500
Subject: [Edu-sig] PyCrust
In-Reply-To: <4.2.0.58.20011012151700.00bf49e0@pop3.norton.antivirus>
Message-ID:
I'll do my best to answer your questions inline below. (You seem to have
uncovered every existing weakness of PyCrust, btw. )
---
Patrick K. O'Brien
Orbtech
"I am, therefore I think."
> -----Original Message-----
> From: edu-sig-admin@python.org [mailto:edu-sig-admin@python.org]On
> Behalf Of Kirby Urner
> Sent: Friday, October 12, 2001 5:33 PM
> To: pobrien@orbtech.com
> Cc: edu-sig@python.org
> Subject: [Edu-sig] PyCrust
>
> OK, didn't take long to install. Had to get
> wxPython, for which I didn't find an installer
> for 2.2. Probably easy enough to do that, but
> I'm with 2.1 now. Your PyCrust installer
> helpfully found both installations -- I picked
> 2.1 (BTW, does wxPython work on Mac? -- seems
> PyCrust blurb say yours does, yet wxPython page
> mentions only Windows, POSIX -- which I guess
> includes OSX).
PyCrust should work on the Mac as soon as wxPython does, which is supposedly
imminent. But I am not involved in that effort so I can't say for sure. My
goal is to support the same platforms as wxPython.
> So I have PyCrust open, and it does the shell
> mode fine. I like the tips.
>
> I gather there's no builtin program editor ala
> IDLE. I should use Scintilla or something like
> that?
That's right. PyCrust doesn't edit files, and I'm not in any hurry to add
that feature. I tend to use Boa Constructor as my IDE, with occasional use
of IDLE and PythonWin.
> Any way to change default colors? I'm used to
> the IDLE color scheme and/or would like the
> returned values ("computer types...") to be a
> different color (like blue).
User configuration of colors and fonts and such is still on the todo list.
> The response seems pretty snappy on the whole.
>
> One thing that's cool about IDLE is if I have
> a multi-line function or class defined at the shell
> prompt, I can scroll back and click on any of these
> lines to get a full copy of the whole function or
> class -- which I may now edit/revise. Having only
> a single line copy down doesn't allow easy re-editing.
> If I use copy/paste, I can get multiple lines, but
> the interpreter seems to only recogize the last
> one.
IDLE is definitely more flexible in this area than PyCrust, and I'm at a bit
of a loss to duplicate IDLE's functionality in this regard. It would take
quite an effort to mimic. The best way to deal with multi-line functions is
to use the command history retrieve-previous key (Ctrl-Up) to retrieve the
first command in the series. This positions you in the command history
buffer. Now subsequent uses of command history retrieve-next (Ctrl-Down)
will get you each subsequent line. Not as good as IDLE, but better than
nothing. Hopefully we can make it better in the future.
PyCrust is also pretty weak at autoindenting. Improving that is also on the
todo list.
> Maybe there's something planned around line numbers
> (on the left) that'd let me do this. If there's
> a way to turn the line numbers off, that'd be cool
> too, as they haven't a lot of meaning to me in shell
> mode, the way I think about it today anyway.
You can easily turn off line numbers by hacking the code, and this will be a
user configuration option down the road. They show up now because I like
them.
> Not finding a lot of docs (or any, yet), so maybe
> I'm not booting pyCrust the best way. I open DOS
> box and go ..\python pycrust.py
Documentation? Its on my todo list. Way down towards the bottom,
unfortunately.
> I could convert that into a PIF, or else there's
> the option to use the .pyw extension. Lemme try
> renaming pycrust.py to pycrust.pyw and booting it
> by clicking in the file manager...
>
> Yeah, that works (had to change the file association
> from python22\python to python21\python -- not a
> problem). Note: the blinking cursor after the
> prompt doesn't appear on its own when booting.
> I have to click in that window, then it shows after
> a second or two.
I haven't seen that behavior. What plaform are you on and what version of
wxPython? You can go to Help | About in PyCrust to see this version
information.
I know PyCrust has its shortcomings, but hopefully with more feedback and
assistance I can correct those. In the mean time, I hope it has enough
advantages to earn a place on your desktop.
> Kirby
>
>
> _______________________________________________
> Edu-sig mailing list
> Edu-sig@python.org
> http://mail.python.org/mailman/listinfo/edu-sig
From urnerk@qwest.net Sat Oct 13 01:26:18 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Fri, 12 Oct 2001 17:26:18 -0700
Subject: [Edu-sig] PyCrust
In-Reply-To:
References: <4.2.0.58.20011012151700.00bf49e0@pop3.norton.antivirus>
Message-ID: <4.2.0.58.20011012172057.00c53920@pop3.norton.antivirus>
>
>I haven't seen that behavior. What plaform are you on and what version of
>wxPython? You can go to Help | About in PyCrust to see this version
>information.
Shell: 1.19
Interp: 1.8
Python 2.1.1
wxPython 2.3.1
Plat win32
>I know PyCrust has its shortcomings, but hopefully with more feedback and
>assistance I can correct those. In the mean time, I hope it has enough
>advantages to earn a place on your desktop.
Definitely -- I should study the code, too. What you've
done is far beyond my capabilities as a GUI-programmer
using Python. One reason I like using the shell so much
is I like GUIs, but don't as yet have the time/patience
to program them in Python.
Kirby
From urner@alumni.princeton.edu Sat Oct 13 06:12:20 2001
From: urner@alumni.princeton.edu (Kirby Urner)
Date: Fri, 12 Oct 2001 22:12:20 -0700
Subject: [Edu-sig] Re: quadratic functions
In-Reply-To:
References: <6b.1bdef0e1.28f60691@aol.com> <3BC4EBF9.C9972169@voyager.net> <3BC5FF96.15308208@email.unc.edu>
Message-ID: <18dfsto103oo1ghq01mcre325fk4me65r2@4ax.com>
On Fri, 12 Oct 2001 12:08:13 -0700, I wrote:
>And is there a more general expression for
>
> n
> f(n,c) =3D SIGMA k^c =3D some polynomial of degree c+1 ?
> k =3D 1
>
>
>The answer to the 2nd question is yes, and the Bernoulli numbers
>give us the coefficients of such a c+1 degree polynomial. =20
Just to spell that out at the command line, what we're=20
looking for is a closed form expression for the sum of
consecutive integers all to the cth power. What we=20
expect is some polynomial of degree (c+1) with rational
coefficients in which the Bernoulli numbers figure (as
fractions).
So, for example, what is 1^4 + 2^4 + 3^4 + 4^4... n^4?
An easy function just does the arithmetic in a loop:
>>> from operator import add
>>> def sum(n,c):
return reduce(add,[i**c for i in range(1,n+1)])
Note that range(1,n) generates the list [1,2...n-1], hence
the parameter n+1. [i**c for i in range(1,n+1)] is the=20
sequence of terms in list form, and reduce(add, list)=20
simply sums them up.
>>> sum(10,4)
25333
That's the sum of the first 10 natural numbers to the 4th power.
Bernoulli got his numbers from Johann Faulhaber, who wrote=20
about this series in 1631.[1] With this series, Bernoulli=20
could brag about how quickly he could get the sum of the 10th
powers of the first 1000 natural numbers. =20
Using our sum function:
>>> sum(1000,10)
91409924241424243424241924242500L
(the L means 'long integer' -- it'll be dropped in later=20
versions of Python, as the integer types become more seamless).
But Bernoulli was using a polynomial:
>>> summa(10)
(1/11)*x**11 + (1/2)*x**10 + (5/6)*x**9 - x**7 + x**5 - (1/2)*x**3 + =
(5/66)*x
The coefficients above aren't naked Bernoulli numbers; they're=20
folded into products which also involve choice(n+1,k), where
k is the kth term. =20
kth coefficient =3D b[k]*choice(n+1,k) (b[k] =3D kth bernoulli)
------------------
n+1
Given x=3D1000, the powers are easy to compute. summa(10)=20
returns a polynomial object into which we can substitute a=20
value using p() syntax i.e.:
>>> p =3D summa(10)
>>> p(1000)
91409924241424243424241924242500
Let's look at the first 10 bernoullis:
>>> bernseries(10)
[1, (1/2), (1/6), 0, (-1/30), 0, (1/42), 0, (-1/30), 0, (5/66)]
Not so bad. The odd ones become 0 after the 0th, 1st, 2nd.
The Bernoulli numbers get pretty crazy (see below) and difficult
to compute by hand after the first few. But our computer=20
algorithm, using the Fraction object, is up to the task.=20
Let's ask for the 100th Bernoulli number:
>>> bern(100)
(-94598037819122125295227433069493721872702841533066936
133385696204311395415197247711/33330)
Wow, that took almost 10 seconds. And it agrees with the result=20
posted here (yay):
ftp://ftp.cdrom.com/pub/gutenberg/etext01/brnll10.txt
We calculate successive bernoullis using Pascal's Triangle.
The bernseries algorithm will show how this works if passed=20
a non-zero "show" parameter (2nd argument):
>>> bernseries(4,1)
b[1] =3D (1/2) * (1)
b[2] =3D (1/3) * (3*b[1]- 1)
b[3] =3D (1/4) * (6*b[2] - 4*b[1]+ 1)
b[4] =3D (1/5) * (10*b[3] - 10*b[2] + 5*b[1]- 1)
[1, (1/2), (1/6), 0, (-1/30)]
Those'd be the bernoullis used to compute the sum of=20
consecutive integers to the 4th power. The corresponding
5th degree polynomial:
>>> summa(4)
(1/5)*x**5 + (1/2)*x**4 + (1/3)*x**3 - (1/30)*x
And the result for x =3D 10?
>>> p =3D summa(4)
>>> p(10)
25333
That agrees with our earlier answer.
n
And note we get the earlier formula for SIGMA k^2
k =3D 1
>Well, you have metal cluster experiments, written up in=20
>Scientific American (Dec 1998), about agglomerations of atoms
^^^^
1997
>in icosahedral form transforming into cuboctahedra.[1] How many
>atoms in all? These formula will tell you.
So how do we do the total number of spheres in a cuboctahedron
again? I posted quite a bit about this over on math-teach=20
awhile ago.
=46or each layer, you've got the six squares and 8 triangles,=20
but then you have shared edges and vertices, so adding all=20
the squares and triangles involves double-counting edge=20
spheres and quadruple counting the vertices. The number of
edge spheres is 24 * (n-2) and the number of vertices is 12
(see http://www.inetarena.com/~pdx4d/ocn/urner.html for a
graphic). So 8*n(n+1)/2 + 4*n^2 - 24*(n-2) - 3*12 should
be it. That simplifies to: 10*n^2 - 20*n + 12. This=20
works for n>=3D2, i.e. a cuboctahedron with 2 spheres along
an edge has 12 spheres in that layer, with 3 spheres along
an edge has 42, then 92, then 162 and so on (icosahedral
shells the same, as per the jitterbug transformation:
http://www.inetarena.com/~pdx4d/ocn/numeracy0.html ).
What we want is a cumulative number of spheres in all=20
layers. In other words:
n
1 + SIGMA (10k^2 - 20k + 12)
k=3D2
the 1 being the nuclear sphere.
n
10 SIGMA k^2 =3D 10 [(1/3)*n^3 + (1/2)*n^2 + (1/6)*n) - 1]
k=3D2
n
20 SIGMA k =3D 20 [n(n+1)/2 - 1]
k=3D2
n
12 SIGMA 1 =3D 12[n - 1]
k=3D2
Combining and simplifying gives:
Cubocta(n) =3D (10/3)*n^3 - 5*n^2 + (11/3)*n - 1
(remember to add 1 in front of all the SIGMA terms).
Making this a function:
>>> def cubocta(n):
return int((10/3)*n**3 - 5*n**2 + (11/3)*n - 1)
>>> map(cubocta,range(1,11))
[1, 13, 55, 147, 309, 561, 923, 1415, 2057, 2869]
That's the first 10 cuboctahedral numbers.
Citation:
http://www.research.att.com/cgi-bin/access.cgi/as/njas/sequences/eisA.cgi=
?Anum=3DA005902
=3D=3D=3D=3D=3D=3D=3D=3D=3D
ID Number: A005902 (Formerly M4898)
Sequence: 1,13,55,147,309,561,923,1415,2057,2869,3871,5083,6525,8217,
10179,12431,14993,17885,21127,24739,28741,33153,37995,43287,
49049,55301,62063,69355,77197,85609,94611,104223,114465,
125357,136919,149171
Name: Centered icosahedral (or cuboctahedral) numbers, also crystal =
ball
sequence for f.c.c. lattice.
Comments: Called "magic numbers" in some chemical contexts.
References S. Bjornholm, Clusters..., Contemp. Phys. 31 1990 pp. 309-324.
T. P. Martin, Shells of atoms, Phys. Reports, 273 (1996), =
199-241,
eq.
(2).
B. K. Teo and N. J. A. Sloane, Magic numbers in polygonal and
polyhedral
clusters, Inorgan. Chem. 24 (1985), 4545-4558.
Links: J. H. Conway and N. J. A. Sloane, Low-Dimensional Lattices =
VII:
Coordination Sequences, Proc. Royal Soc. London, A453 (1997), 2369-2389 =
(pdf,
ps).
=46ormula: (2*n+1)*(5*n^2+5*n+3)/3.
Maple: A005902:=3D n -> (2*n+1)*(5*n^2+5*n+3)/3;
=3D=3D=3D=3D=3D=3D=3D=3D=3D
Kirby
PS: Source code for bernoulli.py is at the Oregon Tips website,
along with the mathobjects package upon which it depends:
http://www.oregon-tips.org/
[1] See John H. Conway, Richard K. Guy, 'The Book of Numbers'=20
(Springer-Verlag, 1996) p. 106-109 re Faulhaber and Bernoulli=20
numbers.
From altis@semi-retired.com Sat Oct 13 16:59:40 2001
From: altis@semi-retired.com (Kevin Altis)
Date: Sat, 13 Oct 2001 08:59:40 -0700
Subject: [Edu-sig] PythonCard and turtle geometry
Message-ID:
PythonCard http://pythoncard.sourceforge.net/ AFAIK still has the most
complete turtle geometry routines for Python, though Guido's turtle.py
included with Python is fine if you're using tkinter. I think Guido
experimented with the PythonCard turtle, so maybe he can chime in on what he
liked and disliked and what improvements he would like to see.
There are over twenty scripts included with the turtle sample, the docs
directory even includes documentation on Logo commands and the most
important issues to be aware of while converting old Logo programs to
Python. You can have as many turtles as you want, each is independent, so
you should be able to do artificial life experiments similar to what is
possible with Starlogo. You can drive the turtle from the shell which has
command-completion as well as toolTips for all of the turtle commands. There
are screen shots at:
http://pythoncard.sourceforge.net/samples2.html
I've brought up the the turtle library before on this list, but didn't get
much feedback, so I assumed there wasn't any interest. Turtles are fun, so
I'm happy to work on this part of PythonCard.
I would love to get feedback from people interested in using the turtle
library with PythonCard. Note that there is an abstract turtle class, which
is suitable for making a tkinter, wxPython, PostScript or serial-port based
turtle, say for driving a Legos robot. The abstract turtle api will be
improved along with the PythonCard turtle api depending on user demand. In
fact, on a related note, in preparation for making SciPy and PythonCard more
integrated (SciPy already works with PythonCard and the PyCrust shell) I'm
integrating the turtle directly into the PythonCard framework. I posted a
message to the list about this last night:
http://aspn.activestate.com/ASPN/Mail/Message/PythonCard/802606
The latest release version of PythonCard is always at:
http://sourceforge.net/project/showfiles.php?group_id=19015
PythonCard requires Python 2.1 or higher and wxPython 2.3.x, and yes I bug
Robin regularly about the Mac port.
ka
---
Kevin Altis
altis@semi-retired.com
From urnerk@qwest.net Sat Oct 13 17:05:13 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sat, 13 Oct 2001 09:05:13 -0700
Subject: [Edu-sig] PythonCard and turtle geometry
In-Reply-To:
Message-ID: <4.2.0.58.20011013090449.00c02990@pop3.norton.antivirus>
At 08:59 AM 10/13/2001 -0700, Kevin Altis wrote:
>There
>are screen shots at:
>http://pythoncard.sourceforge.net/samples2.html
Impressive.
Kirby
From urnerk@qwest.net Sun Oct 14 05:56:01 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sat, 13 Oct 2001 21:56:01 -0700
Subject: [Edu-sig] Intro to CS (boolean.py)
In-Reply-To: <4.2.0.58.20011013090449.00c02990@pop3.norton.antivirus>
References:
Message-ID: <4.2.0.58.20011013213544.00c4f5d0@pop3.norton.antivirus>
Here's a simple boolean algebra module, for which
"useless Python" I'll no doubt find many more capable
versions (haven't checked yet).
Still, I like this one because it includes a broad
range of Python concepts in not-too-difficult form,
namely:
* a simple class: the Bool class does little more than
override the behavior of __invert__ for integers, so
instead of getting two's complement, I get the logical
negation, i.e. I say '~a' instead of 'not a'.
* a regular expression: really basic, but used to find
all occurances of a single letter variable, and replace
it with ~variable. This version only allows up to four
variables a-d.
* plenty of string manipulation, which is the nuts and
bolts of a lot of programming
* an example of eval() with a local namespace
Here's how it looks, used in shell mode:
>>> reload(boolean)
>>> boolean.truth(1,'~a')
a | ~a
==|===
0 | 1
1 | 0
>>> expr = "(a & ~b) | c"
>>> boolean.truth(3,expr)
a b c | (a & ~b) | c
======|=============
0 0 0 | 0
0 0 1 | 1
0 1 0 | 0
0 1 1 | 1
1 0 0 | 1
1 0 1 | 1
1 1 0 | 0
1 1 1 | 1
>>> newexpr = boolean.demorgan(expr)
>>> newexpr
'~(((~a) | ~(~b)) & (~c))'
>>> boolean.truth(3,newexpr)
a b c | ~(((~a) | ~(~b)) & (~c))
======|=========================
0 0 0 | 0
0 0 1 | 1
0 1 0 | 0
0 1 1 | 1
1 0 0 | 1
1 0 1 | 1
1 1 0 | 0
1 1 1 | 1
As an intro to computer science module, it's got some
other key stuff too, in addition to exercising the above
features of Python (which features are characteristic
of many other languages).
It's got decimal to binary conversion...
>>> from boolean import bin
>>> bin(10)
'1010'
>>> bin(100)
'1100100'
>>> bin(3242034)
'1100010111100000110010'
And it's got this DeMorgan's equivalence relation, whereby
you can express the same logical expression in two different
ways. CS students know what I'm talking about.
That being said, I'm sure the code could be enchanced/improved,
features added and so on (I'm working on an improvement or
two right now).
So, have at it...
Kirby
=====
"""
Simple boolean algebra module by
Kirby Urner, Oct 13, 2001
"""
from string import replace, center
from re import sub
class Bool:
"""
Intialize w/ 1 or 0: a,b = Bool(1), Bool(0)
Example expressions: a&b, a|b, ~a (note: ~ for negation)
returns a Bool
"""
def __init__(self,val):
if not (val==0 or val==1):
raise ValueError,"Must be 1 or 0"
self.value = val
def __invert__(self):
return Bool(not self.value)
def __and__(self,other):
return Bool(self.value & other.value)
def __or__(self,other):
return Bool(self.value | other.value)
def __repr__(self):
return repr(self.value)
def demorgan(expr):
"""
Swap & with |, negate args, negate expression
-- should have same truth table as original
"""
def negate(matchobj):
t = matchobj.group(0)
return '(~%s)' % t
expr = replace(expr,'&','@')
expr = replace(expr,'|','&')
expr = replace(expr,'@','|')
expr = sub('[a-d]',negate,expr)
return "~("+expr+")"
def bin(n):
result = ''
while 1:
result = str(n%2)+result
n = n//2
if not n: break
return result
def truth(n,expr):
"""
Generates truth table for n=1-4 variables a-d,
for the passed boolean expression expr
"""
truth_table = []
locals = {}
padding = n*'0'
for i in range(2**n):
digits = (padding + bin(i))[-n:]
truth_table.append(tuple(digits))
print
print " "+("%s "*n) % tuple('abcd')[:n] + "| " + expr
print " "+"=="*n + "|=" + "="*len(expr)
for row in truth_table:
for i in range(n):
locals['abcd'[i]]=Bool(int(row[i]))
print " "+("%s "*n) % row + "| " + \
center(str(eval(expr,locals)),len(expr))
print
=====
From mkeller@noos.fr Sun Oct 14 14:31:24 2001
From: mkeller@noos.fr (Marc Keller)
Date: Sun, 14 Oct 2001 15:31:24 +0200
Subject: [Edu-sig] boolean expression
Message-ID: <3BC993AC.5038F2A3@noos.fr>
A variation on your Boolean module, leaving Python evaluates boolean
expressions, with local names as arguments:
def bin(num,nbits=0):
b, q = '', num
while q !=0 or nbits > len(b):
b, q = `q&1 > 0` + b, q>>1
return b
def domainBool(n):
return [tuple(map(int,tuple(bin(x,n)))) for x in range(2**n)]
def truth(expr,*args):
n = len(args)
print n*'%s '%args+'|',expr
print n*'=='+'|='+len(expr)*'='
locals = {}
for v in domainBool(n):
for i in range(n):
locals[args[i]] = v[i]
print n*'%d '%v+'|',center(str(eval(expr,locals)),len(expr))
Examples
>>> truth('not a','a')
a | not a
==|======
0 | 1
1 | 0
>>> expr = "(a and not b) or c"
>>> truth(expr,'a', 'b', 'c')
a b c | (a and not b) or c
======|===================
0 0 0 | 0
0 0 1 | 1
0 1 0 | 0
0 1 1 | 1
1 0 0 | 1
1 0 1 | 1
1 1 0 | 0
1 1 1 | 1
From urnerk@qwest.net Sun Oct 14 20:55:33 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sun, 14 Oct 2001 12:55:33 -0700
Subject: [Edu-sig] boolean expression
In-Reply-To: <3BC993AC.5038F2A3@noos.fr>
Message-ID: <4.2.0.58.20011014125411.00a70ee0@pop3.norton.antivirus>
At 03:31 PM 10/14/2001 +0200, Marc Keller wrote:
>A variation on your Boolean module, leaving Python evaluates boolean
>expressions, with local names as arguments:
Yes, this was instructive. Good demo of alternative
strategies -- I especially like the bit-shifting
version of bin().
Kirby
From mascher@crg.ha.nw.schule.de Sun Oct 14 21:26:41 2001
From: mascher@crg.ha.nw.schule.de (Christian Mascher)
Date: Sun, 14 Oct 2001 22:26:41 +0200
Subject: [Edu-sig] Re: PyCrust, IDLE
References:
Message-ID: <3BC9F501.2F744121@gmx.de>
> From: Kirby Urner
> Subject: [Edu-sig] PyCrust
>
> One thing that's cool about IDLE is if I have
> a multi-line function or class defined at the shell
> prompt, I can scroll back and click on any of these
> lines to get a full copy of the whole function or
> class -- which I may now edit/revise. Having only
> a single line copy down doesn't allow easy re-editing.
> If I use copy/paste, I can get multiple lines, but
> the interpreter seems to only recogize the last
> one.
I want to second this. When using python in the classroom, I've always
used IDLE
mostly because of this feature. I realized the importance of the
"multi-line recall by cursor movement" when I installed a Python-shell
on an old win3.1-laptop lately (no TK, no IDLE): editing is really no
fun in shell mode, so I couldn't work with it as before which is about
like this:
Together with a beamer, we often start by using one IDLE-shell as an
experimental interface, where one pupil can code an algorithm and test
it directly, while the class can follow the interaction on the projected
screen. Any occuring errors can be corrected by others, functions can be
modified step by step in hardly any time. This is a very efficient way
in working with a whole class. We seldom edit a file. In the case that
we do, the process is slowed down by the distraction of having to save
the file etc. In IDLE we stay focussed on building the
function-algorithm. And we can play around a lot even in a classroom
situation, because we don't have to type that much when we do a change.
Afterwards pupils had little difficulty in using idle when doing
problems on their own with a partner.
I must confess I haven't tried out pycrust yet though it sounds
promising.
Christian
From urnerk@qwest.net Sun Oct 14 23:52:23 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sun, 14 Oct 2001 15:52:23 -0700
Subject: [Edu-sig] Re: PyCrust, IDLE
In-Reply-To: <3BC9F501.2F744121@gmx.de>
References:
Message-ID: <4.2.0.58.20011014154707.00a705c0@pop3.norton.antivirus>
At 10:26 PM 10/14/2001 +0200, Christian Mascher wrote:
>Together with a beamer, we often start by using one IDLE-shell as an
>experimental interface, where one pupil can code an algorithm and test
>it directly, while the class can follow the interaction on the projected
>screen. Any occuring errors can be corrected by others, functions can be
>modified step by step in hardly any time. This is a very efficient way
>in working with a whole class. We seldom edit a file. In the case that
>we do, the process is slowed down by the distraction of having to save
>the file etc. In IDLE we stay focussed on building the
>function-algorithm. And we can play around a lot even in a classroom
>situation, because we don't have to type that much when we do a change.
This is all music to my ears. Very cool that you're teaching
in this way, with a beamer and everything. Sounds like 7th
heaven to me.
For more complicated functions and/or objects, I imagine saving
the work by cutting/pasting the working/debugged code to an open
window, saving as a module. That does take time, as indentation
can be an issue (but there's block dedent/indent). Then, next
day, or a week later, you can pull up the saved code and further
enchance, modify etc.
This is how I'd gradually evolve a Fraction or Matrix object
say. One day, we'd work on Fraction * Fraction, by overriding
__mul__. On another day, we'd implement addition. And so on.
Also, once a module is saved, if students work on their own
computers, they can pull it off the server and start from where
the projected demo left off.
Kirby
From dyoo@hkn.eecs.berkeley.edu Mon Oct 15 01:39:30 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 14 Oct 2001 17:39:30 -0700 (PDT)
Subject: [Edu-sig] Re: [Tutor] Intro to CS (boolean.py)
In-Reply-To: <4.2.0.58.20011013213544.00c4f5d0@pop3.norton.antivirus>
Message-ID:
Hi Kirby,
I've written a small "propositional logic" parser class that you might
find useful:
http://hkn.eecs.berkeley.edu/~dyoo/python/propositions/
I wrote it as an experiment with the Spark parser-generator a month ago. I
haven't been working on it for a while now, and you're welcome to use the
parser if it's useful for you.
Here's a small sample of what it does:
###
[dyoo@tesuque propositions-0.2]$ python parser.py
This is a small test of the propositional parser.
Enter propositional phrases at the prompt. To quit, type "quit" at
the prompt.
Examples of some phrases:
jack and jill
rock and rolling implies not moss
[ParserTest] >>> a and not b or c
or[and[a, not[b]], c]
###
The parser tries to be nice by allowing both English and "C"-ish syntax,
and sticks with precedence rules to reduce the number of parentheses
needed to disambiguate the expressions.
I actually have an updated version 0.3 on my laptop that should work
better than what's on the web site, and I'll put it up tonight when I get
the chance. (Version 0.2 is actually a little broken: it has a logic bug
that I should investigate.)
Hope this helps!
From urnerk@qwest.net Mon Oct 15 05:16:50 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sun, 14 Oct 2001 21:16:50 -0700
Subject: [Edu-sig] Re: [Tutor] Intro to CS (boolean.py)
In-Reply-To:
References: <4.2.0.58.20011013213544.00c4f5d0@pop3.norton.antivirus>
Message-ID: <4.2.0.58.20011014211527.00c59570@pop3.norton.antivirus>
At 05:39 PM 10/14/2001 -0700, Danny Yoo wrote:
>Hi Kirby,
>
>I've written a small "propositional logic" parser class that you might
>find useful:
>
> http://hkn.eecs.berkeley.edu/~dyoo/python/propositions/
>
>I wrote it as an experiment with the Spark parser-generator a month ago. I
>haven't been working on it for a while now, and you're welcome to use the
>parser if it's useful for you.
Impressive stuff Danny, as well as your plans for future
features :-D.
I don't see 0.3 up yet, but this is a thread I'd like to
track. There could be some fun curriculum written around
here.
Kirby
From dyoo@hkn.eecs.berkeley.edu Tue Oct 16 03:51:09 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 15 Oct 2001 19:51:09 -0700 (PDT)
Subject: [Edu-sig] Re: [Tutor] Intro to CS (boolean.py)
In-Reply-To: <4.2.0.58.20011014211527.00c59570@pop3.norton.antivirus>
Message-ID:
On Sun, 14 Oct 2001, Kirby Urner wrote:
> At 05:39 PM 10/14/2001 -0700, Danny Yoo wrote:
> >Hi Kirby,
> >
> >I've written a small "propositional logic" parser class that you might
> >find useful:
> >
> > http://hkn.eecs.berkeley.edu/~dyoo/python/propositions/
> >
> >I wrote it as an experiment with the Spark parser-generator a month ago. I
> >haven't been working on it for a while now, and you're welcome to use the
> >parser if it's useful for you.
>
>
> Impressive stuff Danny, as well as your plans for future
> features :-D.
>
> I don't see 0.3 up yet, but this is a thread I'd like to
> track. There could be some fun curriculum written around
> here.
Ok, I put the newest version on my site. The code is still a little
messy; I think I need a day to clean things up and add test cases and
documentation. If only I could clone() myself. *grin*
Hope this helps!
From wilson@visi.com Tue Oct 16 13:08:22 2001
From: wilson@visi.com (Timothy Wilson)
Date: Tue, 16 Oct 2001 07:08:22 -0500 (CDT)
Subject: [Edu-sig] Real world simulations
Message-ID:
Hi everyone,
Has anyone used simulation-type problems in an introductory programming
class? I'm trying to avoid overly contrived, typical CS class projects in my
course. Since I'm a science teacher too I think it would be great to sneak a
little science past them while they learn programming. Any ideas?
-Tim
--
Tim Wilson | Visit Sibley online: | Check out:
Henry Sibley HS | http://www.isd197.org | http://www.zope.com
W. St. Paul, MN | | http://slashdot.org
wilson@visi.com | | http://linux.com
From ajs@ix.netcom.com Tue Oct 16 13:30:05 2001
From: ajs@ix.netcom.com (Arthur Siegel)
Date: Tue, 16 Oct 2001 08:30:05 -0400
Subject: [Edu-sig] re: Real world simulations
Message-ID: <000001c15641$e250e5a0$a9e1fea9@carol>
Tim,
Have you checked out the VPython demos.
http://virtualphoton.pc.cc.cmu.edu/projects/visual/
The visual element is a wonderful motivator, IMO.
Art
>everyone,
>Has anyone used simulation-type problems in an introductory programming
>class? I'm trying to avoid overly contrived, typical CS class projects in
my
>course. Since I'm a science teacher too I think it would be great to sneak
a
>little science past them while they learn programming. Any ideas?
>-Tim
From arthur.siegel@rsmi.com Tue Oct 16 17:54:25 2001
From: arthur.siegel@rsmi.com (arthur.siegel@rsmi.com)
Date: Tue, 16 Oct 2001 12:54:25 -0400
Subject: [Edu-sig] PyGeo prensentation
Message-ID:
Proud to note that I will be giving a presentation
of PyGeo to a portion of the math faculty/students
at PolyTechnic University in NY tomorrow evening.
Their interest is in assessing its usefulness for
the dynamic illustration of curriculum material.
The professor who arranged the "event" shares
my geometric interests, and I think correctly
assesses that PyGeo has features relevant to
geometric teaching not otherwise available.
Hopefully another small step toward Python
in the classroom.
Art
From dyoo@hkn.eecs.berkeley.edu Wed Oct 17 04:27:13 2001
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue, 16 Oct 2001 20:27:13 -0700 (PDT)
Subject: [Edu-sig] Re: [Tutor] help ;-)
In-Reply-To: <20011016160147.A28016@harmony.cs.rit.edu>
Message-ID:
On Tue, 16 Oct 2001, dman wrote:
> On Tue, Oct 16, 2001 at 09:56:10AM -0700, Sean 'Shaleh' Perry wrote:
> | if this list would block any mail whose subject matched r'^\s*help\s*$'?
> |
> | Please boys and girls tells us what you need. 'I dont understand
> | classes', 'why is python dying', 'help me with my homework because I
> | am lazy and just go to school to get a degree to go out and make
> | money'. Whatever, just give us something to go on.
>
> Yeah, I usually ignore messages that just say "help" because I don't
> have time to read everything. It the subject doesn't appear
> interesting and/or something I know about, I tend to ignore it.
[Warning: My post is a personal rant, and has little to do with
programming in Python.]
Yikes. This is starting to sound like something out of ESR's "How to ask
Questions the Smart Way" FAQ:
http://www.tuxedo.org/~esr/faqs/smart-questions.html
It is sometimes a little demoralizing if we get questions that seem to beg
for an answer without showing any effort at trying things out.
But it is not unexpected: In the culture of education and knowledge, I
feel there's an unhealthy tendency to emphasize "The Answer" at the
expense of ignoring what motions or Process that people make toward a
goal. Math drills do this. Multiple choice questions do this. The SAT
does this.
And game shows do this all the time. People in Jeopardy are considered
geniuses if they can spit out "questions" at the chime of a buzzer, but
that's still, in essence, just another Answer that's disconnected from any
real understanding. Perhaps those contestants really do know the ideas
behind the facts, or perhaps they're just parroting what they remembered
from flash cards. How can one tell? Given a large enough database of
facts, perhaps a Python dictionary could outperform Alex Trebek.
It's my opinion that the educational culture in the United States does
real damage to people by not encouraging people encogh to practicing the
Process of discovering things. I feel that, instead, schools encourage
the impulse to depend on others for an answer, without asking how or why
that answer makes sense with what we already know. It's the path of least
friction: it's just easier to lure the "teacher" to give an answer, rather
than to discover it for oneself. This feeling seems echoed by John Holt's
book, "How Children Fail", but perhaps I'm misinterpreting his words.
How does this relate back to programming? I believe computer programming
can help make Process important again. What makes programming so much
different from other "intellectual" things that people can try out is that
Process really does matter. One can't get good at programming without
building models of what's going on, or without knowing how to ask good
questions.
When I learned programming, few teachers really knew how to program --- I
couldn't depend on my teachers for an Answer, although I could ask them
for suggestions on resources that could help me. Nor could I depend
solely on reading books, because it was unlikely I could copy an exact
answer in the back.
But I could combine what I read about books, try interactive experiments
with the computer, and try to build some sort of model that would solve
what I was looking for. Programming made creativity and invention
important again. And even if I couldn't figure out how exactly to solve a
problem, I learned how to make things less confusing for myself.
I have to admit, though, that I was a little lonely, not to be able to
talk to other people about this crazy stuff about circular linked lists or
binary arithmetic.
I'd better tie this rant somehow with what was discussed earlier...
> | Please boys and girls tells us what you need. 'I dont understand
> | classes', 'why is python dying', 'help me with my homework because I
> | am lazy and just go to school to get a degree to go out and make
> | money'. Whatever, just give us something to go on.
I agree that it would be nice if people put more effort in, but I think
that this was a little rough. Quite a few people who are on Tutor are new
at this "programming" sort of thing. Programming is different, alien, and
unfamiliar enough that I think some liberties should be given to people
who have just started something new. It takes time to break out bad
habits, but the fact that people are actually talking to us, complete
strangers, about things that aren't part of a standard school curriculum
(yet), is a step in the right direction.
Let's try to make sure people know that they are welcome here, and that we
will do what we can to make it less intimidating.
From shalehperry@home.com Wed Oct 17 06:24:01 2001
From: shalehperry@home.com (Sean 'Shaleh' Perry)
Date: Tue, 16 Oct 2001 22:24:01 -0700 (PDT)
Subject: [Edu-sig] Re: [Tutor] help ;-)
In-Reply-To:
Message-ID:
>
> Let's try to make sure people know that they are welcome here, and that we
> will do what we can to make it less intimidating.
>
My apology if anyone saw this as intimidating. I really was aiming this at the
people who answer questions on this list, hopefully one of them has control
over the actual list. Several of my emails have been held beause the length
was not sufficient or for other reasons. Some magic person has ok'ed them.
Would it be that much harder to deny messages with a subject of only 'help'?
The mail from the bot could tell them to please add a better subject and
resend. Even point them to ESR's great essay.
-----
We have buried the putrid corpse of Liberty. -- Benito Mussolini
From pobrien@orbtech.com Wed Oct 17 21:09:49 2001
From: pobrien@orbtech.com (Patrick K. O'Brien)
Date: Wed, 17 Oct 2001 15:09:49 -0500
Subject: [Edu-sig] Re: PyCrust, IDLE
In-Reply-To: <3BC9F501.2F744121@gmx.de>
Message-ID:
Okay, you guys can stop twisting my arm now. I'm 80% of the way to having
all the multi-line functionality that you are asking for. I'll let you know
when I'm at 100%, but if you want a sneak peak, the current CVS version of
PyCrust now has the following features:
* Commands can be retrieved with Ctrl-Up or Alt-P for the previous command,
Ctrl-Down or Alt-N for the next.
* Command history retrieval now brings back the entire multi-line command,
which you can then modify, including adding and deleting lines.
* Commands retrieved from history are inserted into the existing text and
highlighted, rather than replacing the current command. This makes it much
easier to build new commands that use parts of old commands.
* Commands can be searched for by typing a few letters and hitting F8, which
then cycles through matching commands. Commands retrieved this way are also
inserted and highlighted.
The one feature that I don't yet have finished is being able to put the
cursor on a previous command, hit enter, and get back all the lines in the
command, rather than just the single line. That is next on my list. I'll
keep you posted.
The PyCrust CVS repository is available at:
http://sourceforge.net/cvs/?group_id=31263
---
Patrick K. O'Brien
Orbtech
"I am, therefore I think."
-----Original Message-----
From: edu-sig-admin@python.org [mailto:edu-sig-admin@python.org]On Behalf Of
Christian Mascher
Sent: Sunday, October 14, 2001 3:27 PM
To: edu-sig@python.org
Subject: [Edu-sig] Re: PyCrust, IDLE
> From: Kirby Urner
> Subject: [Edu-sig] PyCrust
>
> One thing that's cool about IDLE is if I have
> a multi-line function or class defined at the shell
> prompt, I can scroll back and click on any of these
> lines to get a full copy of the whole function or
> class -- which I may now edit/revise. Having only
> a single line copy down doesn't allow easy re-editing.
> If I use copy/paste, I can get multiple lines, but
> the interpreter seems to only recogize the last
> one.
I want to second this. When using python in the classroom, I've always
used IDLE
mostly because of this feature. I realized the importance of the
"multi-line recall by cursor movement" when I installed a Python-shell
on an old win3.1-laptop lately (no TK, no IDLE): editing is really no
fun in shell mode, so I couldn't work with it as before which is about
like this:
Together with a beamer, we often start by using one IDLE-shell as an
experimental interface, where one pupil can code an algorithm and test
it directly, while the class can follow the interaction on the projected
screen. Any occuring errors can be corrected by others, functions can be
modified step by step in hardly any time. This is a very efficient way
in working with a whole class. We seldom edit a file. In the case that
we do, the process is slowed down by the distraction of having to save
the file etc. In IDLE we stay focussed on building the
function-algorithm. And we can play around a lot even in a classroom
situation, because we don't have to type that much when we do a change.
Afterwards pupils had little difficulty in using idle when doing
problems on their own with a partner.
I must confess I haven't tried out pycrust yet though it sounds
promising.
Christian
_______________________________________________
Edu-sig mailing list
Edu-sig@python.org
http://mail.python.org/mailman/listinfo/edu-sig
From pobrien@orbtech.com Wed Oct 17 23:43:34 2001
From: pobrien@orbtech.com (Patrick K. O'Brien)
Date: Wed, 17 Oct 2001 17:43:34 -0500
Subject: [Edu-sig] Re: PyCrust, IDLE
In-Reply-To:
Message-ID:
Now I'm 99.9% done with advanced multi-line support. In addition to the
features listed below, putting the cursor on any part of a previous
multi-line command copies down the entire multi-line command, just like
IDLE. Even better, PyCrust displays the secondary prompt on all continuation
lines. I'm sure there might be some minor glitches to be worked out. So if
anyone wants to give it a spin and provide feedback, it would be much
appreciated. I'm beat. This was one tough nut to crack.
---
Patrick K. O'Brien
Orbtech
"I am, therefore I think."
-----Original Message-----
From: edu-sig-admin@python.org [mailto:edu-sig-admin@python.org]On Behalf Of
Patrick K. O'Brien
Sent: Wednesday, October 17, 2001 3:10 PM
To: mascher@crg.ha.nw.schule.de; edu-sig@python.org
Subject: RE: [Edu-sig] Re: PyCrust, IDLE
Okay, you guys can stop twisting my arm now. I'm 80% of the way to having
all the multi-line functionality that you are asking for. I'll let you know
when I'm at 100%, but if you want a sneak peak, the current CVS version of
PyCrust now has the following features:
* Commands can be retrieved with Ctrl-Up or Alt-P for the previous command,
Ctrl-Down or Alt-N for the next.
* Command history retrieval now brings back the entire multi-line command,
which you can then modify, including adding and deleting lines.
* Commands retrieved from history are inserted into the existing text and
highlighted, rather than replacing the current command. This makes it much
easier to build new commands that use parts of old commands.
* Commands can be searched for by typing a few letters and hitting F8, which
then cycles through matching commands. Commands retrieved this way are also
inserted and highlighted.
The one feature that I don't yet have finished is being able to put the
cursor on a previous command, hit enter, and get back all the lines in the
command, rather than just the single line. That is next on my list. I'll
keep you posted.
The PyCrust CVS repository is available at:
http://sourceforge.net/cvs/?group_id=31263
---
Patrick K. O'Brien
Orbtech
"I am, therefore I think."
From urnerk@qwest.net Thu Oct 18 00:32:04 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Wed, 17 Oct 2001 16:32:04 -0700
Subject: [Edu-sig] Re: PyCrust, IDLE
In-Reply-To:
References:
Message-ID: <4.2.0.58.20011017163109.019e5970@pop3.norton.antivirus>
At 05:43 PM 10/17/2001 -0500, Patrick K. O'Brien wrote:
>Now I'm 99.9% done with advanced multi-line support. In addition to the
>features listed below, putting the cursor on any part of a previous
>multi-line command copies down the entire multi-line command, just like
>IDLE. Even better, PyCrust displays the secondary prompt on all continuation
>lines. I'm sure there might be some minor glitches to be worked out. So if
>anyone wants to give it a spin and provide feedback, it would be much
>appreciated. I'm beat. This was one tough nut to crack.
>
>---
>Patrick K. O'Brien
>Orbtech
>"I am, therefore I think."
Your efforts are appreciated and I'll be giving it a whirl
soon -- looming project deadline at the moment, but I'm
looking forward to getting back to matters Pythonic in the
near future...
Kirby
From arthur.siegel@rsmi.com Fri Oct 19 18:36:44 2001
From: arthur.siegel@rsmi.com (arthur.siegel@rsmi.com)
Date: Fri, 19 Oct 2001 13:36:44 -0400
Subject: [Edu-sig] re: PyGeo Presentation
Message-ID:
I had written -
>Proud to note that I will be giving a presentation
>of PyGeo to a portion of the math faculty/students
>at PolyTechnic University in NY tomorrow evening.
Great fun to have gotten the right audience - and
some good feedback.
They were great good sports in seeing the best in
the efforts of an amateur - making up in passion
for a "mission" what he may be lacking in technical depth.
Except that the only non-departmental guest in the
audience was a tech heavyweight with an interest
in education and technology issues . Ironically,
after my presentation I overheard him talking to the
math department head,quoting Alan Kay - with whom he
apparently enjoys some personal relationship.
I mentioned I had heard he left Disney - and left it at
that. (Since it was only the Disney connection that
ever distrubed me.)
Despite my track record with the Python establishment,
I must say I thought I made an effective spokesman for
the case of Python and related goodies - including PyGeo
of course - as tools that quite well belong in a math department's
arsenal.
Art
From urnerk@qwest.net Fri Oct 19 21:28:46 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Fri, 19 Oct 2001 13:28:46 -0700
Subject: [Edu-sig] re: PyGeo Presentation
In-Reply-To:
Message-ID: <4.2.0.58.20011019132754.00c14940@pop3.norton.antivirus>
At 01:36 PM 10/19/2001 -0400, arthur.siegel@rsmi.com wrote:
>Despite my track record with the Python establishment,
>I must say I thought I made an effective spokesman for
>the case of Python and related goodies - including PyGeo
>of course - as tools that quite well belong in a math department's
>arsenal.
>
>Art
Thanks for keeping us abreast of developments re Pygeo
in academia, Art. This has been a fun adventure on
which to keep tabs.
Kirby
From urnerk@qwest.net Sat Oct 20 00:40:19 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Fri, 19 Oct 2001 16:40:19 -0700
Subject: [Edu-sig] Thanks for the tip
In-Reply-To: <00ec01c1529e$cb5f10c0$c3090740@megapathdsl.net>
References:
Message-ID: <4.2.0.58.20011019163921.00c70cf0@pop3.norton.antivirus>
>
>Who is Fourier? A mathematical Adventure with Python
I now have my copy and have been going through it.
Thanks for putting me on to this book. Quite and
interesting endeavour.
Kirby
From ajs@ix.netcom.com Sat Oct 20 16:05:36 2001
From: ajs@ix.netcom.com (Arthur Siegel)
Date: Sat, 20 Oct 2001 11:05:36 -0400
Subject: [Edu-sig] re: PyGeo presentation
Message-ID: <001701c15978$acc31c20$a9e1fea9@carol>
Kirby -
>Thanks for keeping us abreast of developments re Pygeo
>in academia, Art. This has been a fun adventure on
>which to keep tabs.
A fun adventure indeed.
Got an e-mail yesterday from one of the math professors
who attended, telling me he enjoyed the presentation
and the software and apologizing for not being able to join us
afterward for dinner.
Do a web search and find that he had co-authored
some math articles with the guy who is the Director
of the Institute for Advanced Studies at Princeton.
Occurred to me that he was just being polite,
but...
Immediately walked over to David's house to let him
know that I am too smart to be his friend anymore.
In celebration I hope to post up the new improved
PyGeo and see about getting the Edu-Sig page
link properly pointed.
Art
From jbloodworth@sc.rr.com Mon Oct 22 02:14:45 2001
From: jbloodworth@sc.rr.com (Jay Bloodworth)
Date: 21 Oct 2001 21:14:45 -0400
Subject: [Edu-sig] __init__ returning subclasses
Message-ID: <1003713285.1191.74.camel@cae88-126-210.sc.rr.com>
Hiya,
This is really more a general programming question than a python-in-edu
question, but it's related to project for education that I'm working on,
and based on lurking for a while I'm pretty sure some members of the
list will have some interest and expertise to answer.
Say I have some class definitions like this:
class Expression:
stuff
class LinearExpression(Expression):
stuff
class QuadraticExpression(Expression):
stuff
Is there any way to make the Expression constructor return an instance
of one of the subclasses (based on its arguments) rather than an
Expression instance. E.G.
e=Expression("3x+5")
e.__class__ ==
e=Expression("x^2-9")
e.__class__ ==
I can think of plenty of workarounds involving helper functions and I
can think of a number reason why idiom given above might not be The
Right Thing whether or not it is possible. But I can't help thinking
that there is an elegance to this approach: Let the superclass choose
the appropiate subclass as an implementation, based on what it is
supposed to represent.
Similarly, can a class constructor choose not to construct a class and
instead return a base type object? For example (assuming Fraction is a
suitably designed class for rationals), can you do:
f=Fraction(1,2) # Fraction(n,d) => n/d
type(f) ==
f=Fraction(2,1)
type(f) ==
Again, I can think of reasons not to do this, but it seems reasonable to
let the class pick the most appropriate implementation of itself as
possible, and if that is a builtin type, why not?
It's probably obvious from my examples that I'm interested in computer
algebra. I've found a few python CA systems: fewer than I'd expect,
more than I'd like to evaluate one by one, none well documented enough
for me to guess how easy to use/featureful they are. Anybody got any
advice/pointers for good, extensible computer algebra implementations
under python?
Thanks,
Jay
From dustin@cs.uchicago.edu Mon Oct 22 03:54:01 2001
From: dustin@cs.uchicago.edu (Dustin Mitchell)
Date: Sun, 21 Oct 2001 21:54:01 -0500 (CDT)
Subject: [Edu-sig] __init__ returning subclasses
In-Reply-To: <1003713285.1191.74.camel@cae88-126-210.sc.rr.com>
Message-ID:
The idiom you're asking about is called 'Virtual Constructors'. James
Coplien's 'Advanced C++ Programming Styles and Idioms' describes a
roundabout way to implement such things in C++. In Python, however, since
class creation looks like a function call, it would be just as easy to
implement this with (essentially) helper functions, e.g.,
def Expression(*args):
"Construct an object of the Expression class or a subclass"
if :
return cLinearExpression(*args)
elif :
return cQuadraticExpression(*args)
class cExpression:
blah blah blah
class cLinearExpression(cExpression):
blah blah blah
this could easily be extended so that each potential subclass
"registers" itself with the virtual constructor, so that multiple
independent modules could extend a single virtual superclass
constructor. In module expression.py:
Expression_subclasses = []
def Expression_register_subclass(subclass, test_fn):
Expression_subclasses.append((subclass, test_fn))
def Expression(*args):
for subclass, test_fn in Expression_subclasses:
if test_fn(*args):
return subclass(*args)
return None
class cExpression:
blah blah blah
and in module quadratic.py:
from expression import *
class cQuadraticExpression(cExpression):
blah blah blah
def is_quadratic(*args):
blah blah blah
Expression_register_subclass(cQuadraticExpression, is_quadratic)
Hope this helps.
--
Dustin Mitchell
dustin@cs.uchicago.edu
dustin@ywlcs.org
From urnerk@qwest.net Mon Oct 22 06:36:10 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Sun, 21 Oct 2001 22:36:10 -0700
Subject: [Edu-sig] __init__ returning subclasses
In-Reply-To: <1003713285.1191.74.camel@cae88-126-210.sc.rr.com>
Message-ID: <4.2.0.58.20011021222902.00c73650@pop3.norton.antivirus>
>
>It's probably obvious from my examples that I'm interested in computer
>algebra. I've found a few python CA systems: fewer than I'd expect,
>more than I'd like to evaluate one by one, none well documented enough
>for me to guess how easy to use/featureful they are. Anybody got any
>advice/pointers for good, extensible computer algebra implementations
>under python?
>
>Thanks,
>Jay
Although by no means a full fledged CA system, I've done
some stuff with algebra in Python. Here's an example
session:
>>> from mathobjects import *
>>> p = Poly([3,4,5])
>>> p
3*x**2 + 4*x + 5
>>> q = Poly([1,2,3,4])
>>> q
x**3 + 2*x**2 + 3*x + 4
>>> q.deriv()
3*x**2 + 4*x + 3
>>> p*q
3*x**5 + 10*x**4 + 22*x**3 + 34*x**2 + 31*x + 20
>>> p(10)
345L
>>> F = Fraction
>>> f = F(1,2)
>>> f
(1/2)
>>> f*p
(3/2)*x**2 + 2*x + (5/2)
>>> p.roots()
[(-0.66666666666666663+1.1055415967851332j),
(-0.66666666666666663-1.1055415967851332j)]
>>> A = Sqmatrix([[F(1,2),1],[F(3/2),-2]])
>>> A
[(1/2), 1]
[1, -2]
>>> A.inverse()
[1, (1/2)]
[(1/2), (-1/4)]
[q.roots() caused an error -- used to work but I
started stripping out conversions to longs when 2.2
made this automatic, then putting back in when I
decided to keep 2.1.1 back compatibility, and
there's still something broken around here. Hope
to fix it soon].
The current source code is at
http://www.oregon-tips.com/ under Curricula | Python.
There's also a bernoulli numbers piece.
Kirby
From kimtitu@yahoo.com Mon Oct 29 19:12:03 2001
From: kimtitu@yahoo.com (Titu Kim)
Date: Mon, 29 Oct 2001 11:12:03 -0800 (PST)
Subject: [Edu-sig] How to detect dst problem.
Message-ID: <20011029191203.27576.qmail@web14704.mail.yahoo.com>
Hi,
My program does not give correct time reading
because of day light time saving happened over last
weekend. I have to mannually add/subtract a -1
constant everytime this happens. Is there a way that i
can detect dst change so this add/subtract can happen
automatically? For instance, i can do an if statement
to determine what constant should be added when
computing a time value. Thanks a lot.
Regards
Kim Titu
__________________________________________________
Do You Yahoo!?
Make a great connection at Yahoo! Personals.
http://personals.yahoo.com
From dustin@cs.uchicago.edu Mon Oct 29 21:55:11 2001
From: dustin@cs.uchicago.edu (Dustin Mitchell)
Date: Mon, 29 Oct 2001 15:55:11 -0600 (CST)
Subject: [Edu-sig] How to detect dst problem.
In-Reply-To: <20011029191203.27576.qmail@web14704.mail.yahoo.com>
Message-ID:
On Mon, 29 Oct 2001, Titu Kim wrote:
> My program does not give correct time reading
> because of day light time saving happened over last
> weekend. I have to mannually add/subtract a -1
> constant everytime this happens. Is there a way that i
> can detect dst change so this add/subtract can happen
> automatically? For instance, i can do an if statement
> to determine what constant should be added when
> computing a time value. Thanks a lot.
Ordinarily, your operating system should detect this and adjust
accordingly. I would suggest checking & fixing your operating system's
configuration first, then using Python's 'time.localtime()' function,
which incorporates your operating system's knowledge of the time zone,
etc.
Dustin
--
Dustin Mitchell
dustin@cs.uchicago.edu
dustin@ywlcs.org
From kimtitu@yahoo.com Tue Oct 30 01:59:09 2001
From: kimtitu@yahoo.com (Titu Kim)
Date: Mon, 29 Oct 2001 17:59:09 -0800 (PST)
Subject: [Edu-sig] How to Improve code performance
Message-ID: <20011030015909.36953.qmail@web14706.mail.yahoo.com>
Hi,
I am little obssessed with my own coded after i
found out it is slow. I am trying to construct a html
table string from a result that i obtain from
database.My code segment look like this: assume result
holds 2D list.
******* method********************************
def f1(item):
return ""+str(item)+" | "
*****************************************
************main program piece***********
tab = "\n"
for x in result:
tab = tab + ""
tab = tab + string.join(map(f1,x),"")+"
\n"
tab = tab + "
"
print "Content-type:text/html\n"
print tab
**********************************************
Can anyone improve this code segment? Thanks alot
Regards,
Kim Titu
__________________________________________________
Do You Yahoo!?
Make a great connection at Yahoo! Personals.
http://personals.yahoo.com
From schoen@loyalty.org Tue Oct 30 06:11:12 2001
From: schoen@loyalty.org (Seth David Schoen)
Date: Mon, 29 Oct 2001 22:11:12 -0800
Subject: [Edu-sig] How to Improve code performance
In-Reply-To: <20011030015909.36953.qmail@web14706.mail.yahoo.com>
References: <20011030015909.36953.qmail@web14706.mail.yahoo.com>
Message-ID: <20011029221112.A6278@zork.net>
Titu Kim writes:
> Hi,
> I am little obssessed with my own coded after i
> found out it is slow. I am trying to construct a html
> table string from a result that i obtain from
> database.My code segment look like this: assume result
> holds 2D list.
> ******* method********************************
> def f1(item):
> return ""+str(item)+" | "
> *****************************************
> ************main program piece***********
> tab = "\n"
> for x in result:
> tab = tab + ""
> tab = tab + string.join(map(f1,x),"")+"
\n"
> tab = tab + "
"
> print "Content-type:text/html\n"
> print tab
> **********************************************
> Can anyone improve this code segment? Thanks alot
If all you do with tab is print it out, you don't need to do all
of those string operations, or function calls:
print "Content-type: text/html"
print ""
for x in result:
print ""
for item in x:
print ""+str(item)+" | "
print "
"
print "
"
Printing output right away would have lower overhead and use less
memory. If you know something about the data type of "item", you
could also use the % operator instead of the str function.
On a 500 by 500 array created via
result = []
for x in range(500):
result.append(range(500))
I timed my version at 3 seconds, and your version at 12 seconds
(both including the array setup time).
On a 1000 by 1000 array, my version took 12 seconds and your version
took about 95 seconds.
--
Seth David Schoen | Its really terrible when FBI arrested
Temp. http://www.loyalty.org/~schoen/ | hacker, who visited USA with peacefull
down: http://www.loyalty.org/ (CAF) | mission -- to share his knowledge with
http://www.freesklyarov.org/ | american nation. (Ilya V. Vasilyev)
From schoen@loyalty.org Tue Oct 30 06:43:12 2001
From: schoen@loyalty.org (Seth David Schoen)
Date: Mon, 29 Oct 2001 22:43:12 -0800
Subject: [Edu-sig] How to Improve code performance
In-Reply-To: <20011029221112.A6278@zork.net>
References: <20011030015909.36953.qmail@web14706.mail.yahoo.com> <20011029221112.A6278@zork.net>
Message-ID: <20011029224312.B6278@zork.net>
Seth David Schoen writes:
> If all you do with tab is print it out, you don't need to do all
> of those string operations, or function calls:
>
> print "Content-type: text/html"
> print ""
> for x in result:
> print ""
> for item in x:
> print ""+str(item)+" | "
> print "
"
> print "
"
>
> Printing output right away would have lower overhead and use less
> memory.
This can be a big deal for efficiency in a very high level language.
Building large or complex data structures could have very high
overhead; for example, dynamic allocation of space for strings can be
a real problem if you do it over and over again hundreds of thousands
of times!
Anyway, this also has me wondering about the relative speed of
different Python iteration idioms (for, while, map, recursion, and now
list comprehensions). They're not all applicable to the same
problems, but where there is overlap, which are faster than others?
--
Seth David Schoen | Its really terrible when FBI arrested
Temp. http://www.loyalty.org/~schoen/ | hacker, who visited USA with peacefull
down: http://www.loyalty.org/ (CAF) | mission -- to share his knowledge with
http://www.freesklyarov.org/ | american nation. (Ilya V. Vasilyev)
From kimtitu@yahoo.com Tue Oct 30 19:27:40 2001
From: kimtitu@yahoo.com (Titu Kim)
Date: Tue, 30 Oct 2001 11:27:40 -0800 (PST)
Subject: [Edu-sig] How to Improve code performance
In-Reply-To: <20011029224312.B6278@zork.net>
Message-ID: <20011030192740.11844.qmail@web14708.mail.yahoo.com>
I am also looking for the result on this question.
--- Seth David Schoen wrote:
> Seth David Schoen writes:
>
> > If all you do with tab is print it out, you don't
> need to do all
> > of those string operations, or function calls:
> >
> > print "Content-type: text/html"
> > print ""
> > for x in result:
> > print ""
> > for item in x:
> > print ""+str(item)+" | "
> > print "
"
> > print "
"
> >
> > Printing output right away would have lower
> overhead and use less
> > memory.
>
> This can be a big deal for efficiency in a very high
> level language.
> Building large or complex data structures could have
> very high
> overhead; for example, dynamic allocation of space
> for strings can be
> a real problem if you do it over and over again
> hundreds of thousands
> of times!
>
> Anyway, this also has me wondering about the
> relative speed of
> different Python iteration idioms (for, while, map,
> recursion, and now
> list comprehensions). They're not all applicable to
> the same
> problems, but where there is overlap, which are
> faster than others?
>
> --
> Seth David Schoen | Its really
> terrible when FBI arrested
> Temp. http://www.loyalty.org/~schoen/ | hacker, who
> visited USA with peacefull
> down: http://www.loyalty.org/ (CAF) | mission --
> to share his knowledge with
> http://www.freesklyarov.org/ | american
> nation. (Ilya V. Vasilyev)
>
> _______________________________________________
> Edu-sig mailing list
> Edu-sig@python.org
> http://mail.python.org/mailman/listinfo/edu-sig
__________________________________________________
Do You Yahoo!?
Make a great connection at Yahoo! Personals.
http://personals.yahoo.com
From schoen@loyalty.org Tue Oct 30 20:17:41 2001
From: schoen@loyalty.org (Seth David Schoen)
Date: Tue, 30 Oct 2001 12:17:41 -0800
Subject: Iteration and large lists (was: Re: [Edu-sig] How to Improve code performance)
In-Reply-To: <20011030192740.11844.qmail@web14708.mail.yahoo.com>
References: <20011029224312.B6278@zork.net> <20011030192740.11844.qmail@web14708.mail.yahoo.com>
Message-ID: <20011030121741.F2342@zork.net>
Titu Kim writes:
> I am also looking for the result on this question.
> --- Seth David Schoen wrote:
> >
> > Anyway, this also has me wondering about the
> > relative speed of
> > different Python iteration idioms (for, while, map,
> > recursion, and now
> > list comprehensions). They're not all applicable to
> > the same
> > problems, but where there is overlap, which are
> > faster than others?
In a trivial test, I noticed that the standard way to do an iteration
over an index,
for i in range(n):
pass
raises a MemoryError for sufficiently large n (on Unix with a ulimit
in effect, limiting how much memory any process can allocate). On the
other hand,
i = 0
while i < n:
pass
obviously has no such memory limitation. The memory problems arise
from trying to construct the enormous list -- I can reproduce them on
this particular system merely by writing
a = range(10**7)
Now, one thought is that you could simulate the behavior of list data
types by creating a class to represent "sparse lists" or the more
general "patterned lists", lists in which the nth item is given by a
function of n (instead of being calculated and stored beforehand).
The advantage here would be that you could say something like
r = PatternedList(lambda x: x, 0, 10**7)
for i in r:
pass
The PatternedList class is easy to implement _except_ that I don't
think a user-defined object -- other than a subclass of UserList --
can be used in a "for" loop. UserList doesn't seem to help here,
because it doesn't actually allow you to override the element lookup
behavior of the list, to change the way the list is represented in
memory.
Anyway, the general point was about resource requirements for
different iteration idioms. Recursion requires memory, iteration over
a sequence requires memory if you have to build the sequence just for
that purpose, and iteration with while _doesn't_ require more than a
constant amount of memory (well, maybe if you get up into long
integers). If we rewrote code to use a while instead of a "for i in
range", our code's memory profile could be much different.
--
Seth David Schoen | Its really terrible when FBI arrested
Temp. http://www.loyalty.org/~schoen/ | hacker, who visited USA with peacefull
down: http://www.loyalty.org/ (CAF) | mission -- to share his knowledge with
http://www.freesklyarov.org/ | american nation. (Ilya V. Vasilyev)
From urnerk@qwest.net Tue Oct 30 21:07:13 2001
From: urnerk@qwest.net (Kirby Urner)
Date: Tue, 30 Oct 2001 13:07:13 -0800
Subject: Iteration and large lists (was: Re: [Edu-sig] How to
Improve code performance)
In-Reply-To: <20011030121741.F2342@zork.net>
References: <20011030192740.11844.qmail@web14708.mail.yahoo.com>
<20011029224312.B6278@zork.net>
<20011030192740.11844.qmail@web14708.mail.yahoo.com>
Message-ID: <4.2.0.58.20011030124931.00949ef0@pop3.norton.antivirus>
>
>Anyway, the general point was about resource requirements for
>different iteration idioms. Recursion requires memory, iteration over
>a sequence requires memory if you have to build the sequence just for
>that purpose, and iteration with while _doesn't_ require more than a
>constant amount of memory (well, maybe if you get up into long
>integers). If we rewrote code to use a while instead of a "for i in
>range", our code's memory profile could be much different.
Seth makes good points about range() pre-allocating potentially
large chunks of memory. Historically, xrange() was provided to
allow a "lazy evaluation" approach -- instead of pre-allocating,
it would do more like Seth suggests, and compute the next "list"
element with each iteration.
Since Python 2.2, we have the yield keyword, which, when used
in a function definition, makes that function a "generator".
To 'yield' a value is akin to using a print statement, except
the argument is returned in a usable form (ala 'return') --
which ties this thread to an earlier one re 'return' vs.
'print' semantics.
When a function encounters a 'yield', execution stops and the
calling function gets the yielded falue. When the function
is next triggered using .next(), or is iterated over as an
object, as in 'for i in myfunction()', then execution picks
up right after the 'yield', as if "nothing had happened"
(i.e. there's no more disruption to local variables than if
a 'print' had been used -- the function behaves as if that's
what had happened).
So xrange() is being phased out, given 'yield' provides a
much more generic approach to lazy evaluation (means a
'just in time' approach to value generation, where you
get a next value just when you need it, without a lot of
pre-allocation of values -- which you might never get to,
if the loop has a break in it, for example).
To make this more concrete, here's a lazyrange() function
which behaves somewhat like range (lots of improvements
and variations possible):
>>> from __future__ import generators # make feature available
>>> def lazyrange(initial,final,inc):
while 1: # infinite loop
if inc < 0: # break condition
if initial <= final: return
else: # alternate break condition
if initial >= final: return
yield initial
initial += inc # increment using inc
>>> for i in lazyrange(10,1,-1): print i,
10 9 8 7 6 5 4 3 2
You see above that by containing a yield, lazyrange becomes
a generator, and therefore a kind of iterable object (something
you can iterate over using 'for').
Note this alternative syntax:
>>> f = lazyrange(1,10,1) # instantiate function object
>>> type(f) # note f's type
>>> dir(f) # note builtin generator method next()
['__class__', '__delattr__', '__getattribute__', '__hash__',
'__init__', '__iter__', '__new__', '__reduce__', '__repr__',
'__setattr__', '__str__', 'gi_frame', 'gi_running', 'next']
>>> for i in f: print i,
1 2 3 4 5 6 7 8 9
Kirby
From dethe@burningtiger.com Tue Oct 30 22:17:20 2001
From: dethe@burningtiger.com (Dethe Elza)
Date: Tue, 30 Oct 2001 14:17:20 -0800
Subject: Iteration and large lists (was: Re: [Edu-sig] How to Improve code performance)
References: <20011029224312.B6278@zork.net> <20011030192740.11844.qmail@web14708.mail.yahoo.com> <20011030121741.F2342@zork.net>
Message-ID: <3BDF26F0.50900@burningtiger.com>
> The PatternedList class is easy to implement _except_ that I don't
> think a user-defined object -- other than a subclass of UserList --
> can be used in a "for" loop. UserList doesn't seem to help here,
> because it doesn't actually allow you to override the element lookup
> behavior of the list, to change the way the list is represented in
> memory.
Any ordered sequence type can be used in a "for" loop. Built-in types
which qualify include list, tuple, and string. There are lots of
additional sequence types in the libraries, such as UserList (no longer
needed as of ver. 2.2 since you can subclass built-in types directly).
Generally speaking, any class or type which implements __getitem__(self,
key) with a numeric key should work in a "for" loop.
--
Dethe Elza (delza@burningtiger.com)
Chief Mad Scientist
Burning Tiger Technologies (http://burningtiger.com)
Living Code Weblog (http://livingcode.ca)
From Brent.Burley@disney.com Tue Oct 30 22:19:36 2001
From: Brent.Burley@disney.com (Brent Burley)
Date: Tue, 30 Oct 2001 14:19:36 -0800
Subject: [Edu-sig] How to Improve code performance
Message-ID: <3BDF2778.D27942E1@fa.disney.com>
> Hi,
> I am little obssessed with my own coded after i
> found out it is slow. I am trying to construct a html
> table string from a result that i obtain from
> database.My code segment look like this: assume result
> holds 2D list.
> ******* method********************************
> def f1(item):
> return ""+str(item)+" | "
> *****************************************
> ************main program piece***********
> tab = "\n"
> for x in result:
> tab = tab + ""
> tab = tab + string.join(map(f1,x),"")+"
\n"
> tab = tab + "
"
> print "Content-type:text/html\n"
> print tab
> **********************************************
> Can anyone improve this code segment? Thanks alot
The big problem is that tab=tab+"..." in a loop is expensive since
Python must allocate a new string and copy the old one each time. The
running time will increase with the square of the number of records,
i.e. O(n*n).
It may not be intuitive, but putting all the partial strings in a list
and then joining them at the end is more efficient as the running time
will increase only linearly with the number of records, i.e. O(n).
tab = []
tab.append("\n")
for x in result:
tab.append("")
for y in x:
tab.extend(("",y," | \n"))
tab.append("
")
tab.append("
")
print string.join(tab, "")
O(n) will always beat O(n*2) for large enough n, even if the individual
operations are slower.
Brent
From rkr_ii@yahoo.com Wed Oct 31 15:38:54 2001
From: rkr_ii@yahoo.com (Robert Rickenbrode II)
Date: Wed, 31 Oct 2001 10:38:54 -0500
Subject: [Edu-sig] Pybibliotheca
Message-ID: <5.0.2.1.0.20011031103307.00a76ec0@pop.mail.yahoo.com>
Folks - somehow I missed this, but I just looked at PyBibliotheca at
http://www.ibiblio.org/obp/. Very cool.
Does anyone know if there are going to be mechanisms to submit lesson
plans/programming projects/etc. to this repository?
Thanks, Rob
Robert K. Rickenbrode II
rkr_ii@yahoo.com
From jeff@elkner.net Wed Oct 31 19:11:19 2001
From: jeff@elkner.net (Jeffrey Elkner)
Date: 31 Oct 2001 14:11:19 -0500
Subject: [Edu-sig] Pybibliotheca
In-Reply-To: <5.0.2.1.0.20011031103307.00a76ec0@pop.mail.yahoo.com>
References: <5.0.2.1.0.20011031103307.00a76ec0@pop.mail.yahoo.com>
Message-ID: <1004555479.5657.24.camel@mdeicaza>
Hi Robert!
I'm sending this along to Lex Berezhny, who created and is maintaining
the Python Bibleotheca site.
I was glad to get your email, because the kinds of things you asked for
(submitting lesson plans, prjects, etc) are precisely the kind of things
the site was created to do.
There are two things holding us back:
1. No one has stepped forward yet with content to put on the site.
2. We haven't figured out the best mechanism for managing submissions.
Problem 1 is actually more important that problem 2 (which is a meer
technical problem easy to solve ;-)
If you have content to submit, please write to Lex at:
Lex Berezhny
You could be the first one to get things going.
Thanks!
jeff elkner
yorktown high school
arlington, va
On Wed, 2001-10-31 at 10:38, Robert Rickenbrode II wrote:
> Folks - somehow I missed this, but I just looked at PyBibliotheca at
> http://www.ibiblio.org/obp/. Very cool.
>
> Does anyone know if there are going to be mechanisms to submit lesson
> plans/programming projects/etc. to this repository?
>
>
> Thanks, Rob
>
>
> Robert K. Rickenbrode II
> rkr_ii@yahoo.com