comp.lang.python - 25 new messages in 12 topics - digest
comp.lang.python
http://groups.google.com/group/comp.lang.python?hl=en
comp.lang.python@googlegroups.com
Today's topics:
* Pyrhon2.5 to 2.4 conversion - 4 messages, 4 authors
http://groups.google.com/group/comp.lang.python/t/c95524ea08911c3d?hl=en
* Python dos2unix one liner - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/c4b63debe91d51c7?hl=en
* Docstrings considered too complicated - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/dea5c94f3d058e26?hl=en
* python dowload - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/83054f9fc83066f7?hl=en
* help with Python installation - 8 messages, 7 authors
http://groups.google.com/group/comp.lang.python/t/7b9dfd6f69a57931?hl=en
* scope of generators, class variables, resulting in global na - 1 messages, 1
author
http://groups.google.com/group/comp.lang.python/t/b1ff4d23cb5ec32c?hl=en
* stripping fields from xml file into a csv - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/978963344b473e2d?hl=en
* random.gauss: range - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/2225b0cb8f4784ba?hl=en
* Turtle graphics speed(). Seems broken - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/28f827015eb8fd8b?hl=en
* Signature-based Function Overloading in Python - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/7abc18970a1757e7?hl=en
* NOW Watch Hot Sexy Star Aishwarya rai Bathing Videos In All Angles - 1
messages, 1 author
http://groups.google.com/group/comp.lang.python/t/73473f287179e8d5?hl=en
* Creating variables from dicts - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/bb1797ffb6fc3bd7?hl=en
==============================================================================
TOPIC: Pyrhon2.5 to 2.4 conversion
http://groups.google.com/group/comp.lang.python/t/c95524ea08911c3d?hl=en
==============================================================================
== 1 of 4 ==
Date: Sat, Feb 27 2010 5:58 pm
From: Chris Rebert
On Sat, Feb 27, 2010 at 5:41 PM, tarekamr@gmail.com <tarekamr@gmail.com> wrote:
> Hi,
>
> I am currently using oauth2.py library, and it works fine on one of my
> PC's (python2.5), but later on when I tried to use it with python2.4
> the following line (line 332 in http://github.com/simplegeo/python-oauth2/blob/master/oauth2/__init__.py)
> showed a syntax error
>
> items = [(k, v if type(v) != ListType else sorted(v)) for k,v in
> sorted(self.items()) if k != 'oauth_signature']
>
> So it there a way to convert this line to a python2.4 compliant
> syntax.
This part is your problem:
(k, v if type(v) != ListType else sorted(v))
Conditional expressions like that were added in v2.5:
http://docs.python.org/whatsnew/2.5.html#pep-308-conditional-expressions
Here's an untested substitute:
def sort_or_tuple(k, v):
if type(v) != ListType:
return k, v
else:
return sorted(v)
items = [sort_or_tuple(k,v) for k,v in sorted(self.items()) if k !=
'oauth_signature']
Of course, the more obvious solution is just to upgrade your Python;
it's well worth it!
Cheers,
Chris
--
http://blog.rebertia.com
== 2 of 4 ==
Date: Sat, Feb 27 2010 6:02 pm
From: Steven D'Aprano
On Sat, 27 Feb 2010 17:41:09 -0800, tarekamr@gmail.com wrote:
> Hi,
>
> I am currently using oauth2.py library, and it works fine on one of my
> PC's (python2.5), but later on when I tried to use it with python2.4 the
> following line (line 332 in
> http://github.com/simplegeo/python-oauth2/blob/master/oauth2/
__init__.py)
> showed a syntax error
>
> items = [(k, v if type(v) != ListType else sorted(v)) for k,v in
> sorted(self.items()) if k != 'oauth_signature']
>
> So it there a way to convert this line to a python2.4 compliant syntax.
You would be better off installing Python2.5 on the PC rather than trying
to backport the library to 2.4. There could be thousands of changes
needed to backport the library.
--
Steven
== 3 of 4 ==
Date: Sat, Feb 27 2010 6:12 pm
From: MRAB
tarekamr@gmail.com wrote:
> Hi,
>
> I am currently using oauth2.py library, and it works fine on one of my
> PC's (python2.5), but later on when I tried to use it with python2.4
> the following line (line 332 in http://github.com/simplegeo/python-oauth2/blob/master/oauth2/__init__.py)
> showed a syntax error
>
> items = [(k, v if type(v) != ListType else sorted(v)) for k,v in
> sorted(self.items()) if k != 'oauth_signature']
>
> So it there a way to convert this line to a python2.4 compliant
> syntax.
>
I think the clearest is:
items = []
for k, v in sorted(self.items()):
if k != 'oauth_signature':
if type(v) == ListType:
v = sorted(v)
items.append((k, v))
== 4 of 4 ==
Date: Sat, Feb 27 2010 8:07 pm
From: Dennis Lee Bieber
On Sat, 27 Feb 2010 17:58:04 -0800, Dennis Lee Bieber
<wlfraed@ix.netcom.com> declaimed the following in
gmane.comp.python.general:
> Without checking change notices, I'd guess you'd have to change the
> generator expression "(k, v ... sorted(v))" into a list comprehension
> "[k, v ... sorted(v)]"... Which /may/ result in an increase in memory
> usage...
>
Okay... 50 lashes with the wet noodle...
I jumped on what initially looked like a generator expression... not
a ternary conditional expression...
--
Wulfraed Dennis Lee Bieber KD6MOG
wlfraed@ix.netcom.com HTTP://wlfraed.home.netcom.com/
==============================================================================
TOPIC: Python dos2unix one liner
http://groups.google.com/group/comp.lang.python/t/c4b63debe91d51c7?hl=en
==============================================================================
== 1 of 2 ==
Date: Sat, Feb 27 2010 6:03 pm
From: Steven D'Aprano
On Sat, 27 Feb 2010 11:27:04 -0600, John Bokma wrote:
> When do people learn that a
> language is just a tool to do a job?
When do people learn that there are different sorts of tools? A
professional wouldn't use a screwdriver when they need a hammer.
Perl has strengths: it can be *extremely* concise, regexes are optimized
much more than in Python, and you can do some things as a one-liner short
enough to use from the command line easily. Those are values, as seen by
the millions of people who swear by Perl, but they are not Python's
values.
If you want something which can make fine cuts in metal, you would use a
hacksaw, not a keyhole saw or a crosscut saw. If you want to cut through
an three foot tree truck, you would use a ripsaw or a chainsaw, and not a
hacksaw. If you want concise one-liners, you would use Perl, not Python,
and if you want readable, self-documenting code, you're more likely to
get it from Python than from Perl.
If every tool is the same, why aren't we all using VB? Or C, or
Javascript, or SmallTalk, or Forth, or ... ? In the real world, all these
languages have distinguishing characteristics and different strengths and
weaknesses, which is why there are still people using PL/I and Cobol as
well as people using Haskell and Lisp and Boo and PHP and D and ...
Languages are not just nebulous interchangeable "tools", they're tools
for a particular job with particular strengths and weaknesses, and
depending on what strengths you value and what weaknesses you dislike,
some tools simply are better than other tools for certain tasks.
--
Steven
== 2 of 2 ==
Date: Sat, Feb 27 2010 7:37 pm
From: staticd
> >Amusing how long those Python toes can be. In several replies I have
> >noticed (often clueless) opinions on Perl. When do people learn that a
> >language is just a tool to do a job?
>
> When do people learn that language makes a difference? I used to be a
> Perl programmer; these days, you'd have to triple my not-small salary to
> get me to even think about programming in Perl.
dude, you nailed it. many times, if not _always_, the correct output
is important. the method used to produce the output is irrelevant.
==============================================================================
TOPIC: Docstrings considered too complicated
http://groups.google.com/group/comp.lang.python/t/dea5c94f3d058e26?hl=en
==============================================================================
== 1 of 2 ==
Date: Sat, Feb 27 2010 6:23 pm
From: Gregory Ewing
Mel wrote:
> You could think of it as a not bad use of the design principle "Clear The
> Simple Stuff Out Of The Way First". Destinations are commonly a lot simpler
> than sources
That's not usually true in assembly languages, though,
where the source and destination are both very restricted
and often about the same complexity.
That's not to say that right-to-left is the wrong way
to do it in an assembly language, but there are less
misleading words than "move" that could be used.
Z80 assembly language uses "load", which makes things
considerably clearer:
LD A, B ; load A with B
--
Greg
== 2 of 2 ==
Date: Sat, Feb 27 2010 6:45 pm
From: MRAB
Gregory Ewing wrote:
> Mel wrote:
>
>> You could think of it as a not bad use of the design principle "Clear
>> The Simple Stuff Out Of The Way First". Destinations are commonly a
>> lot simpler than sources
>
> That's not usually true in assembly languages, though,
> where the source and destination are both very restricted
> and often about the same complexity.
>
> That's not to say that right-to-left is the wrong way
> to do it in an assembly language, but there are less
> misleading words than "move" that could be used.
>
> Z80 assembly language uses "load", which makes things
> considerably clearer:
>
> LD A, B ; load A with B
>
Some processors distinguish between "load" (memory to register) and
"store" (register to memory), and the destination and LHS operand of
binary operations might be the same register, for example:
CLC ; clear the carry
LDA first ; accumulator := byte at first
ADCA second ; accumulator := accumulator + byte at second + carry
STA result ; byte at third := accumulator
==============================================================================
TOPIC: python dowload
http://groups.google.com/group/comp.lang.python/t/83054f9fc83066f7?hl=en
==============================================================================
== 1 of 1 ==
Date: Sat, Feb 27 2010 6:19 pm
From: Tim Chase
Aahz wrote:
> monkeys paw <monkey@joemoney.net> wrote:
>> On 2/23/2010 3:17 PM, Tim Chase wrote:
>>> Sure you don't need this to be 'wb' instead of 'w'?
>> 'wb' does the trick. Thanks all!
>>
>> import urllib2
>> a = open('adobe.pdf', 'wb')
>> i = 0
>> for line in
>> urllib2.urlopen('http://www.whirlpoolwaterheaters.com/downloads/6510413.pdf'):
>> i = i + 1
>> a.write(line)
>
> Using a for loop here is still a BAD IDEA -- line could easily end up
> megabytes in size (though that is statistically unlikely).
Just so the OP has it, dealing with binary files without reading
the entire content into memory would look something like
from urllib2 import urlopen
CHUNK_SIZE = 1024*4 # 4k, why not?
OUT_NAME = 'out.pdf'
a = open(OUT_NAME, 'wb')
u = urlopen(URL)
bytes_read = 0
while True:
data = u.read(CHUNK_SIZE)
if not data: break
a.write(data)
bytes_read += len(data)
print "Wrote %i bytes to %s" % (
bytes_read, OUT_NAME)
-tkc
==============================================================================
TOPIC: help with Python installation
http://groups.google.com/group/comp.lang.python/t/7b9dfd6f69a57931?hl=en
==============================================================================
== 1 of 8 ==
Date: Sat, Feb 27 2010 6:26 pm
From: rantingrick
On Feb 27, 7:48 pm, gujax <rjngrj2...@gmail.com> wrote:
> Hi,
> I have been trying to install python on my Win ME system for over two
> years -
Wow 2 years!, you must have the patience of a saint!
> Installation does not proceed and I get a message
> saying "dll required for installation could not be run".
Did it say "what" dll did not run, did have a name?
> I do not even
> know what to do next. I also tried Activepython. It installs but when
> I try to open it from Start->Programs->ActivePython 2.6, I get an
> error window saying - upgrade windows.
Hmm, have you tried "upgrading windows, just a wild guess!
== 2 of 8 ==
Date: Sat, Feb 27 2010 6:36 pm
From: Rick Dooling
> Hi,
> I have been trying to install python on my Win ME system
Try this:
RD
== 3 of 8 ==
Date: Sat, Feb 27 2010 6:38 pm
From: "ssteinerX@gmail.com"
>> I do not even
>> know what to do next. I also tried Activepython. It installs but when
>> I try to open it from Start->Programs->ActivePython 2.6, I get an
>> error window saying - upgrade windows.
>
> Hmm, have you tried "upgrading windows, just a wild guess!
Hey, not everyone can afford to upgrade Windows and some hardware just can't handle the "new, improved" versions.
How about we all chip in to buy him a copy of Ubuntu? Oh, wait, it's free...
S
== 4 of 8 ==
Date: Sat, Feb 27 2010 6:55 pm
From: Steve Holden
Rick Dooling wrote:
>> Hi,
>> I have been trying to install python on my Win ME system
>
> Try this:
>
> http://tinyurl.com/w7wgp
>
That explains how to install Python on Windows *XP*. Windows ME is no
longer a supported platform - the tools used to create it just aren't
able to support platforms that old.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/
== 5 of 8 ==
Date: Sat, Feb 27 2010 6:56 pm
From: staticd
On Feb 27, 8:48 pm, gujax <rjngrj2...@gmail.com> wrote:
> I have been trying to install python on my Win ME system for over two
> years - gave up for a while and now I am back with a resolve to solve
> the problem.
Dude. Give up. There are a ton of __free__ distroz of linux out
there. Your troubles are not worth the effort. Why do I say this?
Let's say you do, eventually, figure out what's wrong. Now what?
Why are you so attached to this machine with ME on it?
nd
== 6 of 8 ==
Date: Sat, Feb 27 2010 7:14 pm
From: Arnaud Delobelle
On 28 Feb, 01:48, gujax <rjngrj2...@gmail.com> wrote:
> Hi,
> I have been trying to install python on my Win ME system for over two
> years - gave up for a while and now I am back with a resolve to solve
> the problem. I tried all versions of python but having installation
> problems for all. Installation does not proceed and I get a message
> saying "dll required for installation could not be run". I do not even
> know what to do next. I also tried Activepython. It installs but when
> I try to open it from Start->Programs->ActivePython 2.6, I get an
> error window saying - upgrade windows.
> Is there no solution at all to installing python on WinME. I have
> checked registry several times online and have sought professional
> help but so far no success.
> Thanks, I will appreciate any help
> gujax
The docs (*) say that Python 2.5 is still compatible with Windows 9X
and ME, but that support for these platform was dropped at 2.6. So
you should be able to install and run Python 2.5.
(*) http://docs.python.org/using/windows.html#installing-python
--
Arnaud
== 7 of 8 ==
Date: Sat, Feb 27 2010 9:46 pm
From: gujax
On Feb 27, 9:36 pm, Rick Dooling <rpdool...@gmail.com> wrote:
> > Hi,
> > I have been trying to install python on my Win ME system
>
> Try this:
>
> http://tinyurl.com/w7wgp
>
> RD
I gave it a shot but the site installs the same version of
ActivePython which did install on my computer but does not open any
command windows. See my earlier posted e-mail.
Thanks anyway,
== 8 of 8 ==
Date: Sat, Feb 27 2010 9:51 pm
From: gujax
On Feb 27, 9:56 pm, staticd <stat...@gmail.com> wrote:
> On Feb 27, 8:48 pm, gujax <rjngrj2...@gmail.com> wrote:
>
> > I have been trying to install python on my Win ME system for over two
> > years - gave up for a while and now I am back with a resolve to solve
> > the problem.
>
> Dude. Give up. There are a ton of __free__ distroz of linux out
> there. Your troubles are not worth the effort. Why do I say this?
> Let's say you do, eventually, figure out what's wrong. Now what?
>
> Why are you so attached to this machine with ME on it?
>
> nd
I agree with you. I have a CD of Xubuntu. I tried booting up with the
CD and was impressed. I noticed few problems with screen resolution,
window size etc. I am not yet sure which distroz is the best for an
instrument with a 512 Mb RAM, 700MHz pentium III chip and about 10Gb
mem. Not sure if this is the right forum for this topic though,
And no, I am not at all attached to Win, though wouldn't say the same
for my computer.
Cheers,
gujax
==============================================================================
TOPIC: scope of generators, class variables, resulting in global na
http://groups.google.com/group/comp.lang.python/t/b1ff4d23cb5ec32c?hl=en
==============================================================================
== 1 of 1 ==
Date: Sat, Feb 27 2010 6:44 pm
From: Steven D'Aprano
On Sat, 27 Feb 2010 15:57:15 -0800, dontspamleo wrote:
> I think a big part of the problem is that the scoping rules in Python
> are inconsistent because classes are a different kind of object. An
> example helps:
[...]
> But this doesn't work...
> class C:
> x = 1
> def f(self,y): return x + y
>
> ...although what was probably meant was this, which does work...
> class C:
> x = 1
> def f(self,y): return self.x + y
Yes, this is a deliberate design choice. See below.
> ...and really means this...
> class C:
> x = 1
> def f(self,y): return T.x + y
I don't understand what T is. Did you mean C?
If so, you are wrong. self.x is not the same as <class>.x due to
inheritance rules. Consider one example:
>>> class A:
... x = 1
... def __init__(self, x=None):
... if x is not None:
... self.x = x
...
>>> class B(A):
... def f(self, y): return self.x + y
...
>>> class C(A):
... def f(self, y): return C.x + y
...
>>>
>>> B(5).f(10)
15
>>> C(5).f(10)
11
I have no doubt that there will be other examples involving multiple
inheritance, but I trust I've made my point.
> I argue that it is more consistent to have the scope for classes be
> consistent with the scope of everything else, which makes the early/
> late binding point mute.
Yes, it would be more consistent, but less useful. Apart from methods
themselves, using class attributes is a relatively rare thing to do, but
using global level names inside methods is very common.
> I know this is a major change, that it would break existing code, etc.
> It would have been better to talk about these things before py3k. Still:
>
> 1. Has this been discussed before?
Yes.
> 1. What would this suggestion break?
Nearly all existing code using classes, which is nearly everything.
> 2. What are the advantages of making the scope of class variables
> different? Maybe is it just a historical trait?
See the discussion in the PEP for introducing nested scopes in the first
place:
http://www.python.org/dev/peps/pep-0227/
--
Steven
==============================================================================
TOPIC: stripping fields from xml file into a csv
http://groups.google.com/group/comp.lang.python/t/978963344b473e2d?hl=en
==============================================================================
== 1 of 1 ==
Date: Sat, Feb 27 2010 8:15 pm
From: Hai Vu
On Feb 27, 12:50 pm, Hal Styli <silly...@yahoo.com> wrote:
> Hello,
>
> Can someone please help.
> I have a sed solution to the problems below but would like to rewrite
> in python...
>
> I need to strip out some data from a quirky xml file into a csv:
>
> from something like this
>
> < ..... cust="dick" .... product="eggs" ... quantity="12" .... >
> < .... cust="tom" .... product="milk" ... quantity="2" ...>
> < .... cust="harry" .... product="bread" ... quantity="1" ...>
> < .... cust="tom" .... product="eggs" ... quantity="6" ...>
> < ..... cust="dick" .... product="eggs" ... quantity="6" .... >
>
> to this
>
> dick,eggs,12
> tom,milk,2
> harry,bread,1
> tom,eggs,6
> dick,eggs,6
>
> I am new to python and xml and it would be great to see some slick
> ways of achieving the above by using python's XML capabilities to
> parse the original file or python's regex to achive what I did using
> sed.
>
> Thanks for any constructive help given.
>
> Hal
Here is a sample XML file (I named it data.xml):
--------------------------
<orders>
<order customer="john" product="eggs" quantity="12" />
<order customer="cindy" product="bread" quantity="1" />
<order customer="larry" product="tea bags" quantity="100" />
<order customer="john" product="butter" quantity="1" />
<order product="chicken" quantity="2" customer="derek" />
</orders>
--------------------------
Code:
--------------------------
import csv
import xml.sax
# Handle the XML file with the following structure:
# <orders>
# <order attributes... /> ...
# </orders>
class OrdersHandler(xml.sax.handler.ContentHandler):
def __init__(self, csvfile):
# Open a csv file for output
self.csvWriter = csv.writer(open(csvfile, 'w'))
def startElement(self, name, attributes):
# Only process the <order ... > element
if name == 'order':
# Construct a sorted list of attribute names in order to
# guarantee rows are written in the same order. We assume
# the XML elements contain the same attributes
attributeNames = attributes.getNames()
attributeNames.sort()
# Construct a row and write it to the csv file
row = []
for name in attributeNames:
row.append(attributes.getValue(name))
self.csvWriter.writerow(row)
def endDocument(self):
# Destroy the csv writer object to close the file
self.csvWriter = None
# Main
datafile = 'data.xml'
csvfile = 'data.csv'
ordersHandler = OrdersHandler(csvfile)
xml.sax.parse(datafile, ordersHandler)
--------------------------
To solve your problem, it is easier to use SAX than DOM. Basically,
use SAX to scan the XML file, if you encounter the element you like
(in this case <order ...>) then you process its attributes. In this
case, you sort the attributes, then write to a csv file.
--------------------------
References:
SAX Parser:
http://docs.python.org/library/xml.sax.html
SAX Content Handler:
http://docs.python.org/library/xml.sax.handler.html
Attributes Object:
http://docs.python.org/library/xml.sax.reader.html#attributes-objects
==============================================================================
TOPIC: random.gauss: range
http://groups.google.com/group/comp.lang.python/t/2225b0cb8f4784ba?hl=en
==============================================================================
== 1 of 1 ==
Date: Sat, Feb 27 2010 8:27 pm
From: Gregory Ewing
Steven D'Aprano wrote:
> def pinned_gaussian(a, b, mu, sigma):
> """Return a Gaussian random number pinned to [a, b]."""
> return min(b, max(a, random.gauss(mu, sigma)))
>
> def truncated_gauss(a, b, mu, sigma):
> """Return a random number from a truncated Gaussian distribution."""
> while 1:
> x = random.gauss(mu, sigma)
> if a <= x <= b:
> return x
If it doesn't have to be strictly gaussian, another way is to
approximate it by adding some number of uniformly distributed
samples together. If you have n uniform samples ranging from
0 to a, the sum will be in the range 0 to n*a and the mean
will be n*a/2. The greater the value of n, the closer the
distribution will be to normal.
--
Greg
==============================================================================
TOPIC: Turtle graphics speed(). Seems broken
http://groups.google.com/group/comp.lang.python/t/28f827015eb8fd8b?hl=en
==============================================================================
== 1 of 2 ==
Date: Sat, Feb 27 2010 8:35 pm
From: "Dr. Phillip M. Feldman"
Stefan Behnel-3 wrote:
>
> Alexander.Oot@gmail.com wrote:
>> I think the speed function may be broken from the turtle graphics package
>>
>>
>> "from turtle import *
>>
>> speed('fastest')
>>
>> forward(50)"
>>
>>
>> I have tried all of the different speed settings, but I get no change
>> in the turtle's speed.... does anyone know how to fix this?
>
> Use "xturtle"? :)
>
> http://ada.rg16.asn-wien.ac.at/~python/xturtle/
>
> Stefan
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
The Python library's implementation of turtle graphics is slow to the point
that many applications are simply impractical. I recently converted a
program to Python/turtle graphics that was originally written by my son
using Processing; the result of the conversion is that the time to draw the
balls increased by a factor of roughly 50! (The Processing version takes
less than 0.1 seconds to generate the image, while the Python version takes
almost 5 seconds on the same computer). It would be good if this
performance problem can be fixed, either by patching the current
implementation of turtle graphics, or by replacing it with xturtle if that
is better. http://old.nabble.com/file/p27732940/balls.py balls.py
--
View this message in context: http://old.nabble.com/Turtle-graphics-speed%28%29.-Seems-broken-tp15504443p27732940.html
Sent from the Python - python-list mailing list archive at Nabble.com.
== 2 of 2 ==
Date: Sat, Feb 27 2010 9:49 pm
From: "Alf P. Steinbach"
* Dr. Phillip M. Feldman:
>
> Stefan Behnel-3 wrote:
>> Alexander.Oot@gmail.com wrote:
>>> I think the speed function may be broken from the turtle graphics package
>>>
>>>
>>> "from turtle import *
>>>
>>> speed('fastest')
>>>
>>> forward(50)"
>>>
>>>
>>> I have tried all of the different speed settings, but I get no change
>>> in the turtle's speed.... does anyone know how to fix this?
>> Use "xturtle"? :)
>>
>> http://ada.rg16.asn-wien.ac.at/~python/xturtle/
>>
>> Stefan
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>>
>
> The Python library's implementation of turtle graphics is slow to the point
> that many applications are simply impractical. I recently converted a
> program to Python/turtle graphics that was originally written by my son
> using Processing; the result of the conversion is that the time to draw the
> balls increased by a factor of roughly 50! (The Processing version takes
> less than 0.1 seconds to generate the image, while the Python version takes
> almost 5 seconds on the same computer). It would be good if this
> performance problem can be fixed, either by patching the current
> implementation of turtle graphics, or by replacing it with xturtle if that
> is better. http://old.nabble.com/file/p27732940/balls.py balls.py
Try to add
turtle.tracer( 0 )
before generating the graphics, and
turtle.update()
after.
It sort of speeds things up. :-)
To test it I had to rewrite your code a little, getting rid of the numpy
dependency since I don't have numpy installed. Looks like this:
<code>
#from numpy import *
def array( data, dtype ): return data # Emulate numpy array constructor
import random
from math import *
import sys
from time import time
import turtle # turtle graphics module
class Timer:
"""Track and record elapsed time, allowing an arbitrary number of timers."""
from time import time
# Constructor:
def __init__(self):
self.start= time()
# Report elapsed time:
def time(self):
# Compute elapse time:
elapsed= time() - self.start
# Print elapsed time in seconds:
print str(elapsed) + ' s',
# If total elapsed time exceeds 60 seconds, also print time as
# as minutes and seconds:
if elapsed >= 60.0:
minutes= numpy.floor(elapsed / 60.0)
elapsed-= 60 * minutes
print '= ' + num2str(minutes,0) + ' m ' + num2str(elapsed,3) + ' s'
else:
print
def main():
# Section 1: User inputs. All four arrays should have the same dimensions.
balls_of_type = array([20, 20], dtype=int)
radius_of_type= array([35, 25], dtype=float)
mass_of_type = array([4 , 2], dtype=float)
color_of_type = array([0 , 1], dtype=int)
canvas_width = 1000 # canvas width in pixels
canvas_height= 800 # canvas height in pixels
# Section 2: Setup.
# Section 2.1: Initialize graphics.
turtle.setup(width=canvas_width, height=canvas_height)
# Use units of pixels for specifying locations on the screen:
turtle.setworldcoordinates(0.0, 0.0, canvas_width, canvas_height)
# Set background color to black:
turtle.bgcolor("black")
# We want to specify R, G, and B using whole numbers from 0 to 255:
turtle.colormode(255)
# Turn off animation and hide the turtle to get maximum drawing speed:
turtle.speed('fastest')
turtle.tracer( 0 )
turtle.hideturtle()
# Section 2.2: Preliminaries.
ball_types= len(balls_of_type)
max_tries= 1000
tries= 0
# The following variable counts the number of time ticks:
tick= 0
colors= [
(255, 0, 0), # red
( 64, 64, 230), # blue, cobalt blue
(125, 0, 0), # maroon
( 0, 255, 255), # cyan,baby blue
(255, 140, 0), # orange
( 0, 255, 0), # green, light green
(204, 128, 0), # brown
(255, 200, 120), # light orange
(255, 255, 140), # cream
(0, 128, 0), # dark green, forest green
(255, 128, 128), # peach
(255, 255, 0), # yellow
(0, 0, 204), # dark blue, navy blue
(150, 355, 150), # light green
(128, 0, 230), # purple
(77, 204, 0), # avocado
(255, 128, 255), # magenta, pink
(0, 204, 204), # aqua, turquoise
(230, 192, 0), # gold
(255, 255, 255), # white
]
# Allocate 2-element lists for basis and velocity vectors:
u_hat= [0,0]
v_hat= [0,0]
uv_speed1b= [0,0]; # before the collision
uv_speed2b= [0,0]; # before the collision
uv_speed1a= [0,0]; # after the collision
uv_speed2a= [0,0]; # after the collision
# Section 2.3: Calculate the number of balls and allocate arrays whose sizes
# depend on this.
# `balls` is the total number of balls:
balls= sum( balls_of_type )
x = balls*[0.0] #zeros(balls, dtype=float)
y = balls*[0.0] #zeros(balls, dtype=float)
x_speed = balls*[0.0] #zeros(balls, dtype=float)
y_speed = balls*[0.0] #zeros(balls, dtype=float)
radius = balls*[0.0] #zeros(balls, dtype=float)
mass = balls*[0.0] #zeros(balls, dtype=float)
ball_type = balls*[0] #zeros(balls, dtype=int)
ball_color= [] # empty list
# Section 2.4: Assign a ball type, radius, mass, color, initial position,
# and initial velocity to each ball.
n= -1
for i in range(ball_types):
# Valid color numbers are 0-19. If the color number of a ball type is
# greater than 19, the following line of code fixes the problem by randomly
# assigning acolor number.
if color_of_type[i] >= 20: color_of_type[i]= random.randint(0, 20)
# In the following loop, j is the ball number for the ith type of ball:
for j in range(balls_of_type[i]):
# After the following statement executes, `n` will be one less than the
# number of balls generated.
n+= 1
ball_type[n]= i
radius[n]= radius_of_type[i]
mass [n]= mass_of_type [i]
ball_color.append( colors[color_of_type[i]] )
# Continue loop until center coordinates for ball[n] are such that this
# ball does not overlap any previously generated ball. If the number of
# iterations exceeds max_tries, then the program stops the loop if this
# happens, the program doesn't work because there is not enough space
# for all the balls in the container.
for tries in range(max_tries):
# generate random ball center coordinates:
keepout= radius[n] + 2.0
x[n]= random.uniform(keepout, canvas_width - keepout)
y[n]= random.uniform(keepout, canvas_height - keepout)
# Check to see if two balls have been generated on top of each other.
# First, we set good to True. True means that this ball does not
# overlap any of the other balls that we have checked so far. At the
# end of the inner loop, if good= False, this means that the ball did
# overlap at least one of the previous balls, and the program goes back
# to the top of the outer loop and generates new coordinates for the
# current ball.
good= True
for m in range(n): # innermost loop
dx= x[m] - x[n]
dy= y[m] - y[n]
d= sqrt(dx*dx + dy*dy)
if (d <= radius[m] + radius[n] + 10):
good= False
break
# end for inner for loop
if good: break
# end of loop over tries
if not good:
print "\nERROR: Not enough space for balls.\n"
sys.exit()
# Assign a random initial velocity to the current ball:
theta= random.uniform(0.0, 2.0*pi)
x_speed[n]= 2. * cos(theta)
y_speed[n]= 2. * sin(theta)
# end of loop over j (number of ball of current ball type)
# end of loop over i (number of ball type)
# Section 3: Draw the balls.
# Initialize timer:
t= Timer()
for n in range(balls):
turtle.penup()
turtle.goto(x[n], y[n])
turtle.pendown()
turtle.color(ball_color[n])
turtle.begin_fill()
turtle.circle(radius[n])
turtle.end_fill()
turtle.update()
# Display elapsed time:
print "Total drawing time: ",
t.time()
raw_input('Hit Enter to close figure window.')
if __name__ == "__main__":
msg = main()
print(msg)
</code>
Cheers & hth.,
- Alf
==============================================================================
TOPIC: Signature-based Function Overloading in Python
http://groups.google.com/group/comp.lang.python/t/7abc18970a1757e7?hl=en
==============================================================================
== 1 of 1 ==
Date: Sat, Feb 27 2010 10:07 pm
From: Michael Rudolf
Am 27.02.2010 10:00, schrieb alex23:
> Michael Rudolf<spamfres...@ch3ka.de> wrote:
>> In Java, Method Overloading is my best friend
>
> Guido wrote a nice article[1] on "multimethods" using decorators,
> which Ian Bicking followed up on[2] with a non-global approach.
>
> 1: http://www.artima.com/weblogs/viewpost.jsp?thread=101605
> 2: http://blog.ianbicking.org/more-on-multimethods.html
Nice!
I really liked
http://bob.pythonmac.org/archives/2005/03/30/five-minute-multimethods-in-python-using-dispatch/
==============================================================================
TOPIC: NOW Watch Hot Sexy Star Aishwarya rai Bathing Videos In All Angles
http://groups.google.com/group/comp.lang.python/t/73473f287179e8d5?hl=en
==============================================================================
== 1 of 1 ==
Date: Sat, Feb 27 2010 10:50 pm
From: MY NAME IS MY NAME
NOW Watch Hot Sexy Star Aishwarya rai Bathing Videos In All Angles at
http://blogcreationandhosting.blogspot.com/2009/11/earn-money-online.html
< Due to high sex content,I have hidden these videos inside an Image.
In that website,click on big vertical shining image on the right side
of website & watch the videos >
==============================================================================
TOPIC: Creating variables from dicts
http://groups.google.com/group/comp.lang.python/t/bb1797ffb6fc3bd7?hl=en
==============================================================================
== 1 of 1 ==
Date: Sat, Feb 27 2010 11:22 pm
From: aahz@pythoncraft.com (Aahz)
In article <mailman.145.1266968505.4577.python-list@python.org>,
Tim Chase <python.list@tim.thechases.com> wrote:
>Luis M. González wrote:
>>
>> If you want a list of items, you use tuples or lists. Examples:
>>
>> ('a', 'm', 'p') ---> this is a tuple, and it's made with
>> parenthesis ()
>
>Actually, a tuple is made with commas...the parens are just there
>to clarify the order of operations and make it easier to read :)
>
> >>> x = 1,2,3
> >>> x
> (1, 2, 3)
Almost true:
>>> x = ()
>>> x
()
Parentheses are definitely needed for the empty tuple.
--
Aahz (aahz@pythoncraft.com) <*> http://www.pythoncraft.com/
"Many customs in this life persist because they ease friction and promote
productivity as a result of universal agreement, and whether they are
precisely the optimal choices is much less important." --Henry Spencer
==============================================================================
You received this message because you are subscribed to the Google Groups "comp.lang.python"
group.
To post to this group, visit http://groups.google.com/group/comp.lang.python?hl=en
To unsubscribe from this group, send email to comp.lang.python+unsubscribe@googlegroups.com
To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.python/subscribe?hl=en
To report abuse, send email explaining the problem to abuse@googlegroups.com
==============================================================================
Google Groups: http://groups.google.com/?hl=en
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home