Re: [Tutor] Simple RPN calculator

2004-12-08 Thread Gregor Lingl

Terry Carroll schrieb:
On Mon, 6 Dec 2004, Chad Crabtree wrote:
 

Bob Gailer wrote:
   

For grins I just wrote one that takes '1 2.3 - 3 4 5 + * /' as
 

input 
   

and prints -0.0481481 8 lines of Python. That indeed is less
 

than 
   

100. Took about 7 minutes to code and test. 
 

I'm quite interested in seeing the sourcecode for that.
   

Me, too.  I'm always interested in cool little Python examples.
 

Not having read the thread,  this script prints the same result:
inp = raw_input("Gimmi an RPN-expression: ").split()
i=0
while len(inp)>1:
   while inp[i] not in "+-*/":
   i+=1
   print "**", i, inp #1 
   inp[i-2:i+1] = [str(eval(inp[i-2]+inp[i]+inp[i-1]))]
   i-=1
   print "***", i, inp#2
print inp[0]

If you delete the two numbered print statements it also has 8 lines
of code. (They are inserted to show what's going on!)
Excuse me if this posting suffers from redundancy.
I'm very interested in Bob's solution, too
Gregor


___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
 

___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] am I missing another simpler structure?

2004-12-16 Thread Gregor Lingl

Kent Johnson schrieb:
It's probably worth pointing out that these two functions are not 
entirely equivalent:
def t1():
  if condition:
return True
  return False

def t2():
  return condition
...
 >>> if t1(100) == True: print '100 is True'
...
100 is True
 >>> if t2(100) == True: print '100 is True'
...
(nothing prints)
If you really need this property, you may use
type-conversion with bool:
>>> t2(100)
100
>>> bool(t2(100))
True
>>>
So in this case
def t3(a):
return bool(a)
should work correctly
Regards,
Gregor
Remark for Brian: Please note, that Kent wrote about a feature
specific to Python, whereas the main part of this thread
contains considerations concerning boolean expressions in general.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A little Tkinter question

2004-12-15 Thread Gregor Lingl

Marilyn Davis schrieb:
Hi Tutors,
I'm reviewing GUIs and wondering:
When you pack a component, and you specify fill = BOTH, how is this
different from expand = YES?
Hi Marilyn,
This is a bit tricky and hard to explain, so I recommend playing around 
with this little program from John Grayson's Tkinter book:

from Tkinter import *
class App:
def __init__(self, master):
master.geometry("300x200")
fm = Frame(master)
Button(fm, text='Left').pack(side=LEFT, fill=BOTH, expand=1)
Button(fm, text='Center').pack(side=LEFT, fill=BOTH, expand=1)
Button(fm, text='Right').pack(side=LEFT, fill=BOTH, expand=1)
fm.pack(fill=BOTH, expand=YES)
root = Tk()
root.option_add('*font', ('verdana', 12, 'bold'))
root.title("Pack - Example 9")
display = App(root)
root.mainloop()
Modify the three lines with Button().pack(...)
for instance by setting expand = 0 (which is the default value)
Button(fm, text='Left').pack(side=LEFT, fill=BOTH, expand=0)
Button(fm, text='Center').pack(side=LEFT, fill=BOTH, expand=0)
Button(fm, text='Right').pack(side=LEFT, fill=BOTH, expand=0)
or by tropping the fill option:
Button(fm, text='Left').pack(side=LEFT, expand=1)
Button(fm, text='Center').pack(side=LEFT, expand=1)
Button(fm, text='Right').pack(side=LEFT, expand=1)
and so on.
These Examples are from Chapter 5, several others concerning the packer 
can be found at:

https://secure.manning.com/catalog/view.php?book=grayson&item=source
Hope this helps
Gregor

Thank you for any insight.
Marilyn Davis
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor

--
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien
Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27
Autor von "Python für Kids"
Website: python4kids.net
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A little Tkinter question

2004-12-15 Thread Gregor Lingl

Gregor Lingl schrieb:

Marilyn Davis schrieb:
Hi Tutors,
I'm reviewing GUIs and wondering:
When you pack a component, and you specify fill = BOTH, how is this
different from expand = YES?
Hi Marilyn,
This is a bit tricky and hard to explain, so I recommend playing around 
with this little program from John Grayson's Tkinter book:

and so on.
I forgot to mention, that you should also experiment with resizing the 
App-Window and see what different results you get with those different 
options.
Regards,
Gregor

--
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien
Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27
Autor von "Python für Kids"
Website: python4kids.net
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] am I missing another simpler structure?

2004-12-16 Thread Gregor Lingl

Brian van den Broek schrieb:
If my original bit of code, the structure was like:
output_value = False
if condition:
output_value = True
return output_value
Mine would be like yours if transformed to:
if condition:
return True
return False
Hi Brian!
Do you mean, that condition is something which is
True od False?
And if condition is True you want to return True?
And if condition is False you want to return False?
So why not simlpy:
return condition
?
Regards,
Gregor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Event Handling--Key Press, Mouse Movement ...

2009-04-13 Thread Gregor Lingl



Wayne Watson schrieb:
Sometime ago, one of my posts brought a response brief exchange on 
event handling*. Where might I find more about event handling with 
respect to the keyboard, and particularly with a mouse. In the latter 
case, I'm interested in finding the pixel position of the mouse on a 
canvas.



Hi Wayne,

there is some (limited) support of event handling in the turtle module 
of Python 2.6

Example:

>>> from turtle import *
>>> reset()
>>> def printpos(x,y):
   print x,y

  
>>> onscreenclick(printpos)

>>> -284.0 80.0# result of clicking

the turtle module's playground is a Tkinter Canvas.
Don't know if that fit's to your needs in some way.

The module runs as is also with Python 2.5 and yuo can download
it separately from here:

http://svn.python.org/view/python/trunk/Lib/lib-tk/

More information on:

http://docs.python.org/library/turtle.html#module-turtle

Examples are in the source distribution (along with a demoViewer program,
which also serves as an example on how to embed turtle graphics into a
Tkinter application. You can download it separately from here:

http://svn.python.org/view/python/trunk/Demo/turtle/

If you have enough time and if you are interested in it, here is a PyCon 
talk
on the turtle module, which - as 6th "way" - contains a section on event 
driven

programs followed by two examples of games:

http://blip.tv/file/1947495

Best regards,
Gregor

* I see from Alan Gauld, which refers to his web site. Still I'm 
curious about other sources. The few books I have on Python seem to 
avoid the subject. Perhaps it goes by another name in Python-ville.



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] beginners resources list, Python education events

2009-04-16 Thread Gregor Lingl



wesley chun schrieb:

hey all,
...
Python: Visual QuickStart Guide (Fehily, 2001)
  

This is outdated. There is a new one:

Toby Donaldson:  Python: Visual QuickStart Guide (2008)

Learn to Program Using Python (Gauld, 2000)

ONLINE
How to Think like a Computer Scientist
http://openbookproject.net/thinkCSpy

  

...

please let me know if i'm missing anything as well as if any
information is incorrect or out-of-date. also, does anyone know the
latest about Alice (in particular, did they switch from Python to
Java?) also, are there any good turtle ot vpython (or other 3D)
drawing tools? 
As I'm the author of Pythons new turtle module (2.6 and 3.0), I'm - 
naturally -
thinking that it is a good turtle drawing tool. In fact it is much more 
than merely a
turtle module and includes features to create event driven programs and 
other things.


As it is part of the Python standard distribution it can be used 'out of 
the box'


So I think this deserves to be mentioned.
(Did you not know about it or do you dislike it? If cou are really 
interested in it
have a look at this:  


http://pycon.blip.tv/file/1947495/

)

Generally the Edu-Sig page has been reorganized recently by Andre Roberge
and now contains a lot of up-to-date information on your topic.

Regards,
Gregor




also, are there any intros that use PyGame to teach
programming via game-writing?

on a somewhat related note, i'm doing 3 Python knowledge/education
events within the next few months.

1. APRIL: O'Reilly/Safari Books Online "What is Python?" webcast (FREE to all)
http://www.safaribooksonline.com/events/WhatIsPython.html

2. JUNE: Comprehensive Introduction to Python (3-day training course
in San Francisco open to everyone!)
http://mail.python.org/pipermail/python-list/2009-April/708428.html

3. JULY: O'Reilly Open Source Convention Tutorial instructor and
session speaker (San Jose, CA)
http://en.oreilly.com/oscon2009/public/schedule/speaker/44470

thanks!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] serious problem with graphics module

2009-05-25 Thread Gregor Lingl



roberto schrieb:

hello everyone
i have a problem with python 3.0 graphics module:

no problem while importing the module
  

import turtle



but when i issue any command like:
  

t = turtle.pen()
t = turtle.forward(60)



nothing appears on the screen, only a blank window, with nothing inside;
may you give me some hint ?
  

I know one situation in which can happen what you describe:

If you use IDLE, issue the above commands and your Idle-shell-window
covers the graphics window - then you have to move the shell window in order
to see what's on the graphics window. Alas, in this situation the graphics
window may get nonresponsive (to the Windows-event-queue) and may not
be refreshed. So it remains apparentl empty. You may also experience
problems when trying to close the window (because of the same reasons).

*Remedy*: if you use the turtle module interactively, you have to use Idle
with the -n flag, which prevents it from using subprocesses for 
executing scripts.


I recommend to prepare a special shortcut on your desktop, something
like this:

C:\Python30\pythonw.exe C:\Python30\Lib\idlelib\idle.pyw -n

When you fire up Idle with this link you will get the text:

 No Subprocess 

above your first input prompt.
Now you can enter your commands and everything should work fine.

hth
Gregor






OS: win Xp

thank you in advance !

  

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] serious problem with graphics module

2009-05-25 Thread Gregor Lingl



bob gailer schrieb:

roberto wrote:

hello everyone
i have a problem with python 3.0 graphics module:

no problem while importing the module
 

import turtle



but when i issue any command like:
 

t = turtle.pen()
t = turtle.forward(60)



Your code fails for me at turtle.pen AttributeError: 'module' object 
has no attribute 'pen'

Do you use Python 3.0?

>>> import turtle
>>> turtle.pen

>>>


If I replace pen with Pen then it works as desired.

Then you use the Pen-class to create a Turtle t. Then you
have to call the forward method for this turtle:

>>> import turtle
>>> t = turtle.Pen()
>>> t.forward(60)
>>>

Regards,
Gregor




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] serious problem with graphics module

2009-05-25 Thread Gregor Lingl



roberto schrieb:

hello everyone
  

Hello Roberto,

First question:

Do you use Python from the command line (terminal) or do you use IDLE?
I ask this, because these two show different behaviour.

i have a problem with python 3.0 graphics module:

no problem while importing the module
  

import turtle



but when i issue any command like:
  

t = turtle.pen()


After performing this command you should be able to observe
a blank window with a tiny black arrow - it's the turtle

pen() is a function in the module turtle. It returns a dictionary
of the attributes of the turtle's pen. Have a look at it:

>>> print(t)
{'pensize': 1, 'resizemode': 'noresize', 'pendown': True, 'fillcolor': 
'black',

'speed': 3, 'shown': True, 'outline': 1, 'tilt': 0.0, 'pencolor': 'black',
'stretchfactor': (1.0, 1.0), 'shearfactor': 0.0}
>>>


t = turtle.forward(60)



nothing appears on the screen, only a blank window, with nothing inside;
may you give me some hint ?
  
Hmm, in my window the turtle goes 60 pixels to the right and draws a 
black line.

The statement

>>> t = turtle.forward(60)

doesn't make much sense, though. It calls the forward() function of the
turtle module and names it's return value t. Alas:

>>> print(t)
None
>>>

Not really useful.

>>> turtle.forward(60)

is sufficient.

What happens if you do this?

>>> from turtle import *
>>> for i in range(4):
   forward(100)
   left(90)

Regards,
Gregor




OS: win Xp

thank you in advance !

  

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] serious problem with graphics module

2009-06-02 Thread Gregor Lingl



Lie Ryan schrieb:

roberto wrote:
  

On Tue, May 26, 2009 at 12:45 AM, Gregor Lingl  wrote:


I know one situation in which can happen what you describe:
  

...

ok, it works all right now

the minor issue is that i could not create the shortcut with the -n
flag as you pointed out, that's why i issued both commands:
C:\Python30\pythonw.exe
C:\Python30\Lib\idlelib\idle.pyw -n

via the C: prompt

and the graphic window finally worked correctly

thank you again



Be aware though that using IDLE without subprocess also has its own
problems such as leaked variables from previous execution. 
That's certainly true, and it was the reason for introducing Idle's 
feature to execute scripts

in their own subprocesses with Python 2.3

Despite of this I like to use Idle when working interactively with the 
turtle module and

also when developing small programs as it is much more comfortable than a
cmd-shell window. But I reglularly run them (during development)
from the 'normal' Idle (or from a cmd-shell) to assure that effects like 
those you mention

below are not present.

Does anyone have experience with using IPython with Tkinter?

Regards,
Gregor



Although IDLE
tries to clear itself up sometimes there are things that still leaves
various odd effects here and there especially with Tkinter itself. The
real solution would be to give up IDLE and use python from cmd.exe

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] serious problem with graphics module

2009-06-04 Thread Gregor Lingl



Alan Gauld schrieb:


"W W"  wrote


Do you (or sombody else) know how to get ipython working with Python 2.6
(you know, the Python release, which has that new turtle module ;-)   )

doesn't install on my Windows box... other than that I've got no 
experience

with it


I thought the new turtle module could be made to work on 2.5
as well as 2.6? And IPython plays with 2.5 OK. So if its only the turtle
module thats needed it should work?

Or am I mistaken in the 2.5 turtle compatibility?

Not at all.

But possibly I'mgoing to give a tutorial on turtle.py at EuroPython
(depending on the number of attendees). There I'd like to use
Python 2.6 (as it is the most recent release of the 2.x branch and
contains turtle.py already). That's why I asked.

(There are some postings in some forums on using IPython
with Python 2.6 but the advice to install it I found there
didn't work for me)

And, Alan, some months ago you complained not to come to
Pycon. Will you attend EuroPython? Would be nice to meet
you there.

Regards,
Gregor



Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New to programming and python first minimilistic program (Bottles of beer), , please comment!

2009-06-17 Thread Gregor Lingl

matthew andriani schrieb:


Hi Guys,

I wrote this program for some practice to get into python..I'm trying 
to find fun ways to learn the language so if anyone has a challenge on 
this basic level using loops that sounds exciting please let me know.. 
If you think this program can be improved please let me know too :)


b = "bottles of beer"
w = "on the wall"
a = 100
while a != 0:
a = a-1
print a,b,w,a,b,"if one of those bottles should happen to fall 
there'll be",a-1,b,w



If you don't want the output of your program to be considered as a 
somewhat strange joke, you should better write:


b = "bottles of beer"
w = "on the wall"
a = 100
while a != 0:
  print a,b,w,a,b,"if one of those bottles should happen to fall 
there'll be",a-1,b,w

  a = a-1

That means: determine carefully the order of statements in the body of a 
loop.


Regards,
Gregor


Thanks for the feedback..

Cheers,
Skellem.




What can you do with the new Windows Live? Find out 




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
  



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] window graphics

2009-07-02 Thread Gregor Lingl

Hi David,

Python 3 (preferably 3.1)  has a very easy to use graphics module in the 
standard library:
the turtle module. It has a lot of capabilities, but alas, its working 
with geometrical

objects and   doesn't allow to adress single pixels  .

Get started by writing:

>>> from turtle import *
>>> forward(100)

You can find the docs in Python Docs'  global module index

You can find example scripts in the Demo directory of the source code 
distribution

or here:

http://svn.python.org/view/python/branches/py3k/Demo/turtle/

If you want to give it a try and need more information, please feel free 
to ask


Regards,
Gregor

David H. Burns schrieb:
I am new to Python and I'm looking for help on graphics in Python3.0. 
All the graphics libraries I've seen are far to complex (and don't 
seem compatible with 3. What I really need to know is two things (1) 
how to set up a graphic window and (2)how to plot a pixel. Basically 
that's all a "graphics package" needs. Is this the right group?


Any help appreciated,

David

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Replace a character by index

2009-07-16 Thread Gregor Lingl



Christian Witts schrieb:

Wayne wrote:

Hi,
...


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
  
Strings are essentially a list already of characters.  What would be 
slowing down your preferred method #1 would be your explicit cast to a 
list and then re-joining that list.  Strings support item assignment 
so you can save quite a few cycles just doing


word = 'cat'
word[1] = '_'

which would result in word printing 'c_t'.  


That's simply not true in Python. Try it out!

>>> word = "cat"
>>> word[1] = "_"
Traceback (most recent call last):
 File "", line 1, in 
   word[1] = "_"
TypeError: 'str' object does not support item assignment
>>>
Gregor
I'm assuming your use case would be just a call to random with bounds 
zero -> length of string - 1 and then using that index to replace the 
character with an underscore and it is much simpler and faster to just 
use the strings build in index and item assignment.


Hope that helps.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] demo/turtle

2009-07-22 Thread Gregor Lingl



roberto schrieb:

On Wed, Jul 22, 2009 at 7:06 PM, Alan Gauld wrote:
  

"roberto"  wrote


i'd like to download the demo/turtle directory but i could not find
the correct link;

i need it to run the exampled cited in
http://docs.python.org/library/turtle.html

can you tell me where to find it ?
my version is 2.6.2
  

I believe the new turtle module should be installed as standard on 2.6.
So the example code should just work.

Which OS are you on? Some Linux versions of Python don't have Tkinter loaded
and that  will probably prevent turtle from running...
What happens when you try it? Do you get an error message?


the os is Xp;
the problem is simply i cannot find this directory  in my current
python installation folder ...
  
If you want only to download the demos (including the demoViewer) you 
can do it from here:


http://svn.python.org/view/python/trunk/Demo/turtle/

or if you use Python 3.1 from here (with two additional examples):

http://svn.python.org/view/python/branches/py3k/Demo/turtle/

The turtle module in Python 3.1 has a few enhancements (see docs)
and also two bugfixes.

Regards,
Gregor

  

--





  

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to use Python 2.6 with IDLE?

2009-07-27 Thread Gregor Lingl

Dick Moores schrieb:

I've taken a long break from Python, and now I want to try scripting
with 2.62. I downloaded and installed 2.62, changed Win XP
environmental variables to use Python26. Entering python at the
command line shows I'm using 2.62:

C:\Documents and Settings\Riley>python
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
  


So I'm able to try out the new features of 2.6 (I had been using
2.51), but I can't get IDLE to use 2.6. When I click on
E:\Python26\Lib\idlelib\idle.pyw, I get an IDLE instance that says:
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

And of course, the new 2.6 features don't work.

Advice, please.
  

I suggest you have to change the association of *.pyw files to the
program, which is used to 'open' it.

In Windows explorer choose menu extras/directory options,
then choose tab file types and select PYW type
then press button 'advacned...' or somethng like this at the bottom
of the tab, chose 'open' and the button to change this.

If you see the entry

"C:\Python25\pythonw.exe" "%1" %*

change this to Python26

My translations from the German button captions to
English might not be correct. Hope this helps anyway.

Regards,
Gregor



Thanks,

Dick Moores
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list comprehensions

2009-10-08 Thread Gregor Lingl



Christer Edwards schrieb:

I've been studying python now for a few weeks and I've recently come
into list comprehensions. Some of the examples that I've found make
sense, and I find them readable and concise. In particular I'm
referring to the python docs on the topic
(http://docs.python.org/tutorial/datastructures.html#list-comprehensions).
Those make sense to me. The way I understand them is:

do something to x for each x in list, with an optional qualifier.

On the other hand I've seen a few examples that look similar, but
there is no action done to the first x, which confuses me. An example:

print sum(x for x in xrange(1,1000) if x%3==0 or x%5==0)

In this case is sum() acting as the "action" on the first x?

No.

>>> (x for x in xrange(1,100) if x%3==0 or x%5==0)
 at 0x011C1990>

Is a generator expression. If you want to see what it generates, create 
e.g. a tuple


>>> tuple(x for x in xrange(1,100) if x%3==0 or x%5==0)
(3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 
42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 
81, 84, 85, 87, 90, 93, 95, 96, 99)


So you see that the generator selects those integers that are divisible 
by 3 or 5


>>> sum(x for x in xrange(1,100) if x%3==0 or x%5==0)
2318

This calculates the some of those.
There are quite a couple of functions in Python that accept generator 
expressions

as arguments

Regards,
Gregor

  
 Can

anyone shed some light on what it is I'm not quite grasping between
the two?

Christer
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

  

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] German Tutorials auf Deutsch

2005-01-10 Thread Gregor Lingl
Hallo Michael - und alle!
Hello Mike - and all!
You can find several links to Python ressources for beginners
in German on the website
http://python4kids.net
(or http://www.rg16.asn-wien.ac.at/~python/ )
(Du kannst mehrere Links zu deutschen Python-Einführungen auf
oben erwähnter Website finden.)
Moreover there you will find information about and sample-chapters
of my book "Python for Kids". If you are just beginning to learn
how to program, this may be useful for you?
(Außerdem findest du dort Informationen und Probekapitel
zu meinem Buch "Python für Kids". Wenn du ein Programmieranfänger
bist, ist das vielleicht was für dich?)
Best wishes,
Gregor
(Beste Grüße
Gregor)

Kooser, Ara S schrieb:
Pardon to the non-german speaking (or readers) on the list.
Guten Tag. Mein Deutsch ist nicht so gut (ich habe keinen Deutsche in 
sieben Jahren geschreiben). Mann kann Python Tutorials auf Deutsch heir 
http://www.freenetpages.co.uk/hp/alan.gauld/german/index.htm
und
http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index_ger.html
und
http://starship.python.net/crew/gherman/publications/tut-de/
finden.
I habe Alan Gauld Tutorial vorgelesen. Es is gut und es abdeckt zimliche 
viele Themen.

Ara

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
--
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien
Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27
Autor von "Python für Kids"
Website: python4kids.net
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to sum rows and columns of a matrix?

2005-01-31 Thread Gregor Lingl
Hi all of you,
I'm representing a 4x4 matrix as a 16-element list, e.g.
m=range(16)
first 4 elements first row, second four elements second row etc.
I want to sum rows and columns like
i-th row:
sum(m[4*i:4*i+4])
and ith column:
sum(m[i::4])
This seems to be slow because of the formation of the slices.
I wonder if there is a way using generators or generator-expressions
(which I didn't study yet) to compute these sums without copying
parts of the matrix to a new list. (I'd guess that there should exist
some canonical generator for sequences, which produces their elements 
..., maybe also for slices ?)

All comments, hints, solutions are welcome.
Regards,
Gregor
--
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien
Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27
Autor von "Python für Kids"
Website: python4kids.net
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to read from a txt file

2005-02-17 Thread Gregor Lingl

Brian van den Broek schrieb:
Brian van den Broek said unto the world upon 2005-02-17 03:51:
 > jrlen balane said unto the world upon 2005-02-17 02:41:
sir, what seemed to be the problem with this:
def process(list_of_lines):
data_points = []
for line in list_of_lines:
data_points.append(int(line))
return data_points
data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r')
data = data_file.readline()
print process(data)


Traceback (most recent call last):
  File "C:\Python23\practices\opentxt", line 12, in -toplevel-
process(data)
  File "C:\Python23\practices\opentxt", line 6, in process
data_points.append(int(line))
ValueError: invalid literal for int(): 


The immediate one, due to my advice, is that each line of your file 
ends with a newline character ('\n'). So, you cannot call int on 
'1000\n'.

Bollocks! Nobody read any thing I write where I am claiming to answer 
anyone!
Unfortunately I read it. So I'll try a modest advice, too.
If I read "invalid literal for int" in the error-message,
I try out, what this literal is, by inserting one or two
simple print-statements ;-) :
def process(list_of_lines):
data_points = []
print list_of_lines
for line in list_of_lines:
print (line,)
data_points.append(int(line))
return data_points
Running the program n oe yields:
>>>
1000
('1',)
('0',)
('0',)
('0',)
('\n',)
Traceback (most recent call last):
  File "C:/_/Tutorstuff/intprog.py", line 12, in -toplevel-
print process(data)
  File "C:/_/Tutorstuff/intprog.py", line 6, in process
data_points.append(int(line))
ValueError: invalid literal for int():
>>>
which indicates, that your suspicion (readline - readlines)
was right
Regards
Gregor
IDLE 1.1
 >>> int('1000\n')
1000
 >>>
So, sorry, I don't know what's wrong with the code you sent me, and I 
fear that if I tried to work it out, I'd do more damage. I yield the 
floor as I am off to write "Don't post untested code 1000 times.

(I will say I suspect it is the readline vs. readlines, but then 
hopefully no one is reading this ;-)

Sheepishly,
bran vdB
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

--
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien
Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27
Autor von "Python für Kids"
Website: python4kids.net
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trying out Tkinter with problems

2005-02-19 Thread Gregor Lingl
Hi Adam!
I'm not a Tkinter expert, so I probably cannot provide
the best solution for your problem.
Nevertheless I tried two corrections, which adress your
problem seeminly successfully
Adam Cripps schrieb:
I'm trying out Tkinter as one of my first forays into GUI programming.
However, I'm having a couple of problems.
My intitial efforts can be seen at:
http://www.monkeez.org/code/python/tkinter/min.txt or here [1].
Firstly, I'm trying to grab the contents of Entry widget entry1 with a
StringVar and take that value to another function to print the value
to the command line. However, my function 'printentry' always runs
when the application is run, without the button being pressed. Then,
when I do press the button, the function isn't called. However, this
button is just the same as all the other buttons. Why is this?
This is because of
command=self.printentry(self.content.get())
in createWidgets. Here you don't assign the method pintentry
to command, but the result of executing this method. (So it is
ececuted, when createWidget is called, but not when the command
is executed.
Remedy:
self.save2Button = Button(self, text = "Submit",
  command=self.printentry)
*and*
def printentry(self):
print "ok - the submit has been pressed - \
   I need to get  it's value"
print self.content.get()
Secondly, when I try to exit the app, the quit button doesn't kill the
root, window, but just the widgets. How do I reference the root window
and all, instead of just exiting the widgets?
self.destroy destroys the frame, not the root window.
Remedy:
def exiting(self):
if tkMessageBox.askokcancel("Quit",
   "Do you really wish to quit?"):
self.master.destroy()
I'm not sure if this is the canonical way of exiting a
Tkinter-App :-(   (Perhaps somebody knows more.)
Hope this helps,
Gregor
TIA - Adam
--
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien
Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27
Autor von "Python für Kids"
Website: python4kids.net
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Instance into another instance

2005-02-19 Thread Gregor Lingl

Ismael Garrido schrieb:
Hello.
This is my code:
class Node:
   def __init__(self, tag, value=None, **kwargs):
   self.tag = tag
   self.value = value
   self.kwargs = kwargs
   self.childs = []
   def addChild(self, tag, value=None, **kwargs):
   node = Node(tag, value, kwargs)
   self.childs.append(node)
   def __repr__(self):
   return "Tag %s ; value %s ; kwargs %s ; childs %s" % (self.tag, 
self.value, self.kwargs, self.childs)
   And this is what I do to test it:
 >>> ppal = Node("Test", value="Test")
 >>> ppal.addChild("test", value=2)

Traceback (most recent call last):
 File "", line 1, in -toplevel-
   ppal.addChild("test", value=2)
 File "...node.py", line 10, in addChild
   node = Node(tag, value, kwargs)
TypeError: __init__() takes at most 3 arguments (4 given)
This means, afaik, __init__() takes at most 3 non-keyword arguments
(plus an arbitrary number of keyword-arguments).
You passed 4 non-keyword - arguments, the first beeing (implicitely)
self (i. e. node), and then three more: tag, value, kwargs.
(In your case kwargs is the empty dictionary.)
I suppose you wanted to pass addChild's **kwargs
to Node's **kwargs, which goes like this:
   def addChild(self, tag, value=None, **kwargs):
   node = Node(tag, value, **kwargs)
   self.childs.append(node)
HTH,
Gregor
I don't understand. Why 4 arguments are given? What can I do to solve that?
The idea of the class is to be able to create a "tree". Where each node 
can have subnodes, which in turn can have their subnodes...

Thanks
Ismael
_______
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

--
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien
Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27
Autor von "Python für Kids"
Website: python4kids.net
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Advanced Calculator Program...

2005-02-19 Thread Gregor Lingl

. Sm0kin'_Bull schrieb:
I want to make caculator program which enables me to
enter 2numbers and mathsmatics sign and calculates it.
I think this is too difficult for newbie like me...
Please input data
Number1:
Mathsmetics Sign:
Number2:
(Number1) (Sign) (Number2) = (Result)
I wrote this but, Error occurs
print "Please input data"
number1 = int(raw_input("\nNumber1: "))
sign = (raw_input("\nMathsmetics Sign: "))
number2 = int(raw_input("\nNumber2: "))
total = number1 sign number2
print number1, sign, number2, '=', total
hey, bull! that's a bit tricky. You had a nice
idea, but it doesn't work in Python. The point is,
that you must not use names for operators in
arithmetic expressions. Those operators have
to be used literally.
*One* way to solve your problem is, e. g., to
use a branching statement for checking, which
operator is used.
So replace the line
total = number1 sign number2
by something similar to
if sign == "+":
total = number1 + number2
elif sign == "-":
total = numer1 - number2
... (for other operators ..)
HTH,
Gregor

please help me

Cheers! :)
_
Express yourself instantly with MSN Messenger! Download today it's FREE! 
http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

--
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien
Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27
Autor von "Python für Kids"
Website: python4kids.net
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] primes

2005-03-17 Thread Gregor Lingl
Hi!
Who knows a more concise or equally concise but more efficient
expression, which returns the same result as
[x for x in range(2,100) if not [y for y in range(2,x) if x%y==0]]
Gregor
P.S.: ... or a more beautiful one ;-)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] primes (generator)

2005-03-18 Thread Gregor Lingl
Hi all of you!
Many thanks for your remarks, ideas and experiments.
When I posted my input yesterday:
[x for x in range(2,100) if not [y for y in range(2,x) if x%y==0]]
my intention was indeed to find a "shortest" a program, disregarding
efficiency. Thus range instead of xrange etc.
(About one year ago I was involved in a "coding contest" at Linux-Tag
in Karlsruhe, where the goal was to achive a certain output with a
shortest program ;-) Strange. I used Python, but I didn't win :-(  )
Clearly there are several criteria concerning the quality of programs
as e. g. conciseness, clarity, efficiency, beauty(!) etc. which may not
be achieved optimally all together ...
I definitely intend to sum up your contibutions (for me) later, but for
now (because of lack of time) I'll only present one more idea,
induced by Danny's (unfortunately buggy - because of recursion overflow) 
contribution:

Thought it would be nice to use Python's new generator-expressions
instead of itertool module. First idea:
##
# infinite prime generator
# induced by ideas of Danny Yoo,
# which themselves were induced by material of SICP
import math
def prime(n):
return [x for x in range(2,1+int(math.sqrt(n))) if n%x==0]==[]
def infrange(n):
while True:
yield n
n+=1
primes = (p for p in infrange(2) if prime(p))
###  The generator primes works like this:
>>> primes.next()
2
>>> primes.next()
3
>>> primes.next()
5
>>> [primes.next() for i in range(10)]
[7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
>>> [primes.next() for i in range(100)]
[43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 
113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 
193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 
271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 
359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 
443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 
541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617]
>>>
>>> ### You may also use it this way:
>>> for p in primes:
	if p > 1000: break
	print p,

	
619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 
743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 
863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997

With a fresh generator
[primes.next() for p in xrange(1)]
produces (on my machine) a list of the first 1 primes (upto 104729)
within 4.68 secs.
Now for a bit of optimization: instead of building a list of
all divisors use a loop and get out as soon as possible:
So I replace prime by:
def prime(n):
for d in range(2,1+int(math.sqrt(n))):
if n%d == 0: return  False
return True
This makes the generator nearly 4 times as fast. I get my list in
1.33 secs.
Lets optimize a bit more: test only 2 and odd numbers:
def infrange(n):
yield 2
n=3
while True:
yield n
n+=2
and do a similar thing for searching for divisors:
def prime(n):
if n==2: return True
for d in [2]+ range(3,1+int(math.sqrt(n)),2):
if n%d == 0: return  False
return True
Now the first 1  primes get computed in 0.67 secs.
Again double speed. Together seven times as fast as
first version. But IMO at the cost of clarity
and conciseness.
Maybe you have amendments (of course a matter of taste)
to this code. I'd be interested in them ..
Maybe sombody likes to compare these algorithms to the
ones mentioned before in this thread. I would be
interested in the results.
Regards,
Gregor

Danny Yoo schrieb:
On Thu, 17 Mar 2005, Gregor Lingl wrote:

Hi!
Who knows a more concise or equally concise but more efficient
expression, which returns the same result as
...
##
from itertools import ifilter, count
def notDivisibleBy(n):
... def f(x):
... return x % n != 0
... return f
...
def sieve(iterable):
... nextPrime = iterable.next()
... yield nextPrime
... restOfPrimes = sieve(ifilter(notDivisibleBy(nextPrime), iterable))
... for prime in restOfPrimes:
... yield prime
...
primes = sieve(count(2))
primes.next()
2
primes.next()
...
primes.next()
23
##
The neat thing about this code is that it produces an infinite iterator of
prime numbers.  The original code in Scheme is itself quite concise and
quite nice.  It is described here:
http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-24.html#call_footnote_Temp_455
Best of wishes to you!

--
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien
Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27
Autor von "Python für Kids"
Website: python4kids.net
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] primes (Cautious remark on Python and Scheme)

2005-03-18 Thread Gregor Lingl
Hi Danny!
Preliminary remark: I know that "beautiful" and "beauty"
are concepts very seldom applied to computer programs or
programming languages. I suppose mainly because they are
to a large extent a matter of taste ...
Nevertheless: regardeless of the fact that I'm not a very
skilled scheme-programmer, for me Scheme is the most beautiful
programming language I know, mainly because of the clear
and simple concepts which are purely realized. (I do *not* want
to discuss here questions like functional versus object-oriented
languages etc...)
However - Python - for me - is a programming language for
the "pragmatic lover". Do you consider this expression as
self explanatory? Lover -- because it makes so much fun
to use it. Pragmatic -- because it is a language for the
real world ;-)
im*h*o the primes - examples we are just discussing shows,
that going *the Python way* may well be more successful
or rewarding than trying to translate, traduce, ...er ..
adapt Scheme-concepts quasi trying to show that Python is
at least as good as Scheme. This is not the question. (I
suppose that this also was not your goal?) A deeper
question perhaps would be to what degree the content of
cs texts depends on the choice of the mainly used language
therein.
On the contrary - we may learn from this example that Python
is a *very* good language in its own right - with carefully chosen
concepts and syntax and a very slow, serious and publicly
controlled development process resulting in a more and more
easily and efficiently usable language.
Finally I'd like to stress that your contribution for me
was very valuable and constructive - as are most of your
innumerable contributions to the discussions on this list.
Thanks an regards,
Gregor
post scriptum: as always when writing not only about technical
facts but about opinions and values in English, I'm a bit axious
if I was able to express correctly what I wanted to say. Hmmm.
Hope that I didn't create any misunderstandings ....
Danny Yoo schrieb:
On Thu, 17 Mar 2005, Gregor Lingl wrote:

Hi!
Who knows a more concise or equally concise but more efficient
expression, which returns the same result as
[x for x in range(2,100) if not [y for y in range(2,x) if x%y==0]]

Hi Gregor,
Here is one that's traduced... er... adapted from material from the
classic textbook "Structure and Interpretation of Computer Programs":
##
from itertools import ifilter, count
def notDivisibleBy(n):
... def f(x):
... return x % n != 0
... return f
...
def sieve(iterable):
... nextPrime = iterable.next()
... yield nextPrime
... restOfPrimes = sieve(ifilter(notDivisibleBy(nextPrime), iterable))
... for prime in restOfPrimes:
... yield prime
...
primes = sieve(count(2))
primes.next()
2
primes.next()
3
primes.next()
5
primes.next()
7
primes.next()
11
primes.next()
13
primes.next()
17
primes.next()
19
primes.next()
23
##
The neat thing about this code is that it produces an infinite iterator of
prime numbers.  The original code in Scheme is itself quite concise and
quite nice.  It is described here:
http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-24.html#call_footnote_Temp_455
Best of wishes to you!

--
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien
Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27
Autor von "Python für Kids"
Website: python4kids.net
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] primes (Cautious remark on Python and Scheme)

2005-03-18 Thread Gregor Lingl

Concerning my previous posting - perhaps it
would suffice to summarize:
While Python is a language for the "pragmatic" lover,
Scheme is much more "fundamentalistic".
(thought-) *PROVOKING*?
Gregor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] primes (generator)

2005-03-20 Thread Gregor Lingl
Karl Pflästerer schrieb:
On 19 Mrz 2005, [EMAIL PROTECTED] wrote:
[Code]
Maybe sombody likes...

I did it ... :
def sieve (max):
max = max + 1
border = round(max**0.5)
nums = range(0, max)
nums[0] = nums[1] = None
for p in nums:
if p:
if p >= border: break 
for i in xrange(p+p, max, p):
nums[i] = None
return filter(None, nums)

Hi Karl!
The following variation of your sieve, using
extended slice assignment  seems to
be sgnificantly faster. Try it out, if you like.
def sieve (maximum):
limit = int(maximum**0.5)
nums = range(maximum+1)
nums[0] = nums[1] = None
for p in nums:
if p:
if p > limit: break
nums[p*p:maximum+1:p] = [False]*(1-p+maximum//p)
return filter(None, nums)
Regards
Gregor


   Karl
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] primes - sieve of odds

2005-03-20 Thread Gregor Lingl
Hi Sean!
Thanks for your measurements.
In the meantime I did another amendment,
leaving out the even numbers from the sieve.
It goes like this:
def sieve(maximum):
nums = range(3, maximum+1, 2)
for p in nums:
if p:
if p*p > maximum: break
start = (p*p-2)//2
nums[start::p] = [False]*(1+((maximum-3)//2-start)//p)
return [2] + filter(None, nums)
Perhaps not very elegant. But approximately twice as fast as
the former version.
Best wishes,
Gregor
Sean Perry schrieb:
Gregor Lingl wrote:
The following variation of your sieve, using
extended slice assignment  seems to
be sgnificantly faster. Try it out, if you like.
Here are the numbers:
Primes 1 - 1,000,000 timing:
   extendedSliceSieve: 0.708388 seconds
   listPrimes: 0.998758 seconds
karlSieve: 1.703553 seconds
primeConciseOptimized: 5.133922 seconds
 setSieve: 7.564576 seconds
 primeConcise: 1644.683214 seconds --> 27 minutes 24 seconds
if __name__ == '__main__':
# setup timers as a list of tuples (name, timeit instance)
results = []
longest = 0
for t in timers:
result = t[1].timeit(1)
longest = max(longest, len(t[0]))
results.append((t[0], result))
results.sort(lambda x, y: cmp(x[1], y[1]))
print "Primes 1 - 1,000,000 timing:"
format_str = "%%%ds: %%f seconds" % longest
for i in results:
print format_str % i
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

--
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien
Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27
Autor von "Python für Kids"
Website: python4kids.net
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] primes - sieve of odds

2005-03-23 Thread Gregor Lingl

C Smith schrieb:
Hi Gregor,
I had done the same thing.  I also noted that assigning (or inserting) 
an element into a list is faster than creating a new list: l.insert(0,2) 
is faster than l = [2]+l.

###
def sieve (maximum):
 if maximum < 2: return []
 limit = int(maximum**0.5)
 nums = range(1,maximum+1,2)
 nums[0] = None
 for p in nums:
 if p:
 if p > limit: break
 nums[(p*p)//2::p] = [False]*(1+(maximum//p- p)//2)
 nums[0] = 2
 return filter(None, nums)
###
/c
Well done!
Now it would be fine to have an *equally fast*
infinite prime number generator.
Has anybody any suggestions?
Gregor
--
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien
Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27
Website: python4kids.net
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] SORRY (wrong adress) - (appearance of old postings)

2005-03-25 Thread Gregor Lingl
Ooops, I put the wrong address into my recent posting,
which was intended to go to the edu-sig list.
Forget it!
Sorry for the inconvenience,
Gregor

--
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien
Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27
Website: python4kids.net
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] appearance of old postings

2005-03-25 Thread Gregor Lingl
Hi,
there just appeared a couple of postings from a Jan 2004 thread
(on primes) on this list again. (two of them by me)
To me it's completely unclear why and how this could
happen.
Does anybody know ...?
Gregor
--
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien
Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27
Website: python4kids.net
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] one line code

2005-04-05 Thread Gregor Lingl

Pierre Barbier de Reuille schrieb:
Mmmhhh ... not strictly one line but ...
import re
float_str = re.compile(r"^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$")
val = [ ( (float_str.match(s) and [float(s)]) or [s])[0] for s in l2 ]
It's not really "readable" but well ... it works ^_^
Pierre
This can be done in strictly 1 line (having already imported re):
>>> l = ['1','2','3','abc','0', '','4']
>>> [(re.match(r"^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$",s) 
and [float(s)] or [s])[0] for s in l]
[1.0, 2.0, 3.0, 'abc', 0.0, '', 4.0]

or, if one doesn't have to take into account exponential format:
>>> [(x and not[y for y in x if y not in "0123456789."] and 
x.count(".")<2 and [float(x)] or [x])[0] for x in l]
[1.0, 2.0, 3.0, 'abc', 0.0, '', 4.0]
>>>

hmmm, unfortunately "Useless Python" isn't maintained anymore...
(^o^)
Gregor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to improve

2007-07-12 Thread Gregor Lingl
taserian schrieb:
> I've been programming for years before encountering Pythoin, but in 
> much more verbose languages, and I appreciate the fact that Python is 
> so terse and still accomplishes so much. Still, I have difficulty 
> thinking in Python, and tend to revert to longer programs for what 
> seems to be simple tasks. Sometimes it's because I'm just not aware of 
> a library function, but many times it's because there's just some 
> elegant way to solve my kludge.
>
> As an exercise in Python, I decided to solve a toy problem called 
> "interleave". The idea is that I want to determine how many words in 
> the English language are decomposable into two words by taking it 
> apart one letter at a time. So the word "theorems" could be decomposed 
> into "term" and "hoes" (original word = abababab, decomposed words = 
>  and , with all letters in the same order as in the original 
> word).
>
> I'd like to see how I could improve the program below for this, and 
> make it more Python-ish.
>
Hi taserian,

I've just produced an alternative solution of your problem
(based on your ideas). The main difference is, that I use
a wordlength-dictionary. This version has the advantage, that
it doesn't make an assumption about the max word length.
I don't consider it to be an improvement, just an example
that uses different language elements of Python in some places.
Hope you enjoy it.

 START

wordlengthdict = {}

for word in open("wordlist.txt").read().split():
wordlengthdict.setdefault(len(word),[]).append(word)

outfile = open('InterleaveEnglishYAWL.txt', 'w')

for l in sorted(wordlengthdict.keys()):
print l
for w in wordlengthdict[l]:
wordtriple = (w1, w2, dummy)  = w[0::2], w[1::2], w
if  w1 in wordlengthdict.get(len(w1),[]) and w2 in 
wordlengthdict.get(len(w2),[]):
outfile.write("(%s, %s, %s)\n" % wordtriple)
print wordtriple
  
outfile.close();

 END

Best regards,
Gregor

> = = = = START
>
> def decompose(longword):
> word1 = longword[0::2]
> word2 = longword[1::2]
> return (word1, word2)
>
> wordlengthlist = [None] * 31
> for i in range(0,len(wordlengthlist)):
> wordlengthlist[i] = []
> results = []
>
> for lineread in open("word.list"):
> for word in lineread.split():
> if len(word)<31:
> wordlengthlist[len(word)].append(word)
>
> outfile = open('InterleaveEnglishYAWL.txt', 'w')
>
> for x in range(4, 31):
> print x
> for i in wordlengthlist[x]:
> twowords = decompose(i)
> word1 = twowords[0]
> word2 = twowords[1]
> if word1 in wordlengthlist[len(word1)] and word2 in 
> wordlengthlist[len(word2)]:
> outfile.write("(" + word1 + ", " + word2 + ", " + i + ")\n")
> print (word1, word2, i)
>
> outfile.close();
>
> = = = = END
>
> Tony R.
>
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>   

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Annoying problem when importing a file (caused by IDLE?)

2005-09-12 Thread Gregor Lingl
Hi pythonistas!

Recently I've encountered a very annoying problem when developing a 
program - more exactly a module - of several hundred lines using Idle. 
Of course I have a __name__=="__main__" section to test my classes,
which ran successfully every time, (except when there were bugs :-( in 
the code. ;-) )

moreover I use several test programs, which import that module.
When running these I got (repeatedly after doing some modifications) 
syntax error - messages, pointing to randomly scattered positions in the 
module file. Only random-hacking like deliberately inserting spaces in 
some expressions or deleting empty lines or comment-lines solved this
problem, which tends to re-occur after some more changes.

1) Did anybody experience similar behaviour?

2) Can anybody *explain* how it comes, that a module as a program for 
itself runs without problems, while it doesn't when imported by another 
program instead delivering incomprehensable syntax error messages? This 
occurs in the same way when running them from the commandline and even 
on different computers (running WindowsXP as os.)

3) Probably my file is contaminated by some non printing characters - 
although I don't know where they come from. Is there a simple way to 
check this assumption (e.g. using some simple editor, which shows these
"unfriendly" characters.)

4) I urgently feel, that I have to stop these annoyances. Do you know 
how I can do this?

Desperately

Gregor



-- 
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien

Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] triangulation

2005-11-09 Thread Gregor Lingl



Alex Hunsley schrieb:

Shi Mu wrote:



is there any sample code of triangulation? many thanks!




Yes, probably.




Indeed, there is.
See attachment

regards
Gregor



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor




--
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien

Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27

Website: python4kids.net
## Run this program and create a polygon without
## intersecting edges by clicking the vertices with the mouse

from Tkinter import *

def area2(A,B,C):
"""2 * Flaeche des 2D-Dreiecks ABC"""
return (A[0]-C[0])*(B[1]-C[1]) - (A[1]-C[1])*(B[0]-C[0])

def insideTriangle(A, B, C, P):
"""Liegt P im Dreieck ABC?,
ABC sind im Gegenuhrzeigersinn angenommen!"""
return area2(A,B,P)>=0 and area2(B,C,P)>=0 and area2(C,A,P)>=0

def triangulate(poly):
tri = []
while len(poly) > 2:
triaFound = False
count = 0
while not triaFound and count < len(poly): #n:
count += 1
A, B, C = poly[:3] 
if area2(A, B, C) >= 0:
for P in poly[3:]: 
if insideTriangle(A,B,C,P):
break
else:
tri.append( (A,B,C) )
poly.remove(B)
triaFound = True
poly.append(poly.pop(0))
if count == len(poly): # n:
print "Not a simple polygon"
return None
return tri


class CvDefPoly(Canvas):
def __init__(self, root):
Canvas.__init__(self, root, bg="white", cursor="crosshair")
self.v = ()
self.rWidth, self.rHeight = 10.0, 7.5

self.bind("", self.repaint)
self.bind("", self.mousePressed)

self.done = False

def mousePressed(self, event):
if self.done:
self.done = False
self.v = ()
x ,y = self.fx(event.x), self.fy(event.y)
if self.v:
x0, y0 = self.v[:2]
if abs(x-x0) 1:
x,y = self.v[:2]
self.create_rectangle(self.iX(x)-2, self.iY(y)-2,
  self.iX(x)+2, self.iY(y)+2, outline="green")
if len(self.v) > 3:
if self.done:
v = []
sv = self.v[:]
while sv:
a,b=sv[:2]
v.extend([self.iX(a), self.iY(b)])
sv = sv[2:]
self.create_polygon( v, fill="", outline="blue")
else:
coo = list(self.v[2:])
while coo:
x1,y1 = coo[:2]  
self.create_line(self.iX(x),self.iY(y),
 self.iX(x1),self.iY(y1),fill="blue")
x,y=x1,y1
coo  = coo[2:]

def ccw(poly):
n = len(poly)
k = poly.index(min(poly))
return area2(poly[k-1], poly[k], poly[(k+1)%n]) > 0

def color(n):
return "#%02x%02x%02x" % (255-n,0,n)

class PolyTria(Tk):
def __init__(self):
Tk.__init__(self)
self.geometry("500x300-10+50")
self.title("Define polygon vertices by clicking")
CvPolyTria(self).pack(expand=1, fill="both")

class CvPolyTria(CvDefPoly):
def repaint(self, event):
doit = False
if len(self.v)>3 and self.done:
poly = []
v = self.v[:]
while v:
p = tuple(v[:2])
poly.append(p)
v = v[2:]
if not ccw(poly):
poly.reverse()
tri = triangulate(poly)
doit = True
CvDefPoly.repaint(self, event)
if doit:
anz = len(tri)
diff = 255//anz
for i,t in enumerate(tri):
(x1,y1),(x2,y2),(x3,y3) = t
t = 
(self.iX(x1),self.iY(y1),self.iX(x2),self.iY(y2),self.iX(x3),self.iY(y3))
self.create_polygon(t, fill=color(i*diff), outline="black")
 
if __name__ == "__main__":
PolyTria().mainloop()
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] any code to draw parabola or curve?

2005-11-09 Thread Gregor Lingl

Both!
See attachment

Regards,
Gregor

Shi Mu schrieb:

any code to draw parabola or curve?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor




--
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien

Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27

Website: python4kids.net
# -*- coding: cp1252 -*-
# Minimalversion eines scalierenden Funktionsplotters  --- V.4c

# Mit Realisierung Erich Neuwirth'scher Anregungen
# und einem kleinem Plus an OOP
# und einem Minus an FP

# Autor: Gregor Lingl, 9. 11. 2005
#
# Inbetriebnahme:
# Rechter Mausklick, Edit with IDLE
# Editor-Fenster aktivieren, F5 drücken

# FUNTKIONEN und KURVEN

import Tkinter, math

MARGIN = 20

## helper-function

def minmax(tuplist, index):
values = [tup[index] for tup in tuplist]
return min(values), max(values)


class Graph:
def __init__(self, rmin, rmax, steps, f, g=None):
d = 1.0*(rmax-rmin)/steps
rrange = [rmin+i*d for i in range(steps+1)]
if g is None:
self.plist = [(x, f(x)) for x in rrange]
else:
self.plist = [(f(t), g(t)) for t in rrange]
self.x_range = minmax(self.plist,0)
self.y_range = minmax(self.plist,1)

class PlotCanvas(Tkinter.Canvas):
def setCooSys(self, (xmin, xmax), (ymin, ymax)):
self.ex = (float(self["width"])-2*MARGIN)/(xmax-xmin)
self.ey = (float(self["height"])-2*MARGIN)/(ymin-ymax)
self.ox = MARGIN-xmin*self.ex
self.oy = MARGIN-ymax*self.ey
def screencoos(self,(x, y)):
return self.ox + x * self.ex, self.oy + y * self.ey
def plot(self, rmin, rmax, f, g=None, steps=50):
graph = Graph( rmin, rmax, steps, f, g)
self.setCooSys(graph.x_range, graph.y_range)
self.create_line([self.screencoos(p) for p in graph.plist])
def clear(self):
for item in self.find_all(): self.delete(item)


cv = PlotCanvas(width=240,height=240,bg="white")
cv.pack()

# Beispiel 1

cv.plot(-3.5, 3.5, math.sin)
cv.plot(-2, 2, lambda x: x**3-2*x)
raw_input("Press ENTER to continue!")

# Beispiel 2

cv.clear()
cv.plot(0, 2*math.pi, math.sin, math.cos)
raw_input("Press ENTER to continue!")

# Beispiel 3

cv.clear()
cv.plot(0, 2*math.pi, lambda t:math.sin(2*t), lambda t:math.cos(3*t), steps=100)
raw_input("Press ENTER to finish!")

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [OT] triangulation

2005-11-09 Thread Gregor Lingl


Liam Clarke-Hutchinson schrieb:
> German is an awesome language, I love the compound words (if that's what
> they are). What does 'Gegenuhrzeigersinn' mean in English?
> 

counterclockwise

but Shi Mu didn't ask for a program in English ;-)
Gregor


> 
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
> Of Gregor Lingl
> Sent: Thursday, 10 November 2005 1:44 p.m.
> To: tutor@python.org
> Subject: Re: [Tutor] triangulation
> 
> 
> 
> 
> Alex Hunsley schrieb:
> 
>>Shi Mu wrote:
>>
>>
>>
>>>is there any sample code of triangulation? many thanks!
>>>
>>>
>>
>>Yes, probably.
>>
> 
> 
> 
> Indeed, there is.
> See attachment
> 
> regards
> Gregor
> 
> 
>>___
>>Tutor maillist  -  Tutor@python.org 
>>http://mail.python.org/mailman/listinfo/tutor
>>
>>
> 
> 

-- 
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien

Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27

Website: python4kids.net
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [OT] triangulation

2005-11-09 Thread Gregor Lingl


Ismael Garrido schrieb:
> John Fouhy wrote:
...
> 
> I believe there was a version of Qbasic translated to French or Spanish. 
> By "translated" I mean that the keywords (reserved words) were, for 
> instance, "para" instead of "for", that is, their French/Spanish 
> counterpart.
> 

I know that this definitely (still) exists for Logo in German
Gregor

> Ismael
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien

Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] two ways

2005-11-11 Thread Gregor Lingl
Liam Clarke schrieb:

>Hi Shi,
>
>For what you're doing, nothing at all.
>
>When you use a colon, slice syntax, it defaults to [start:end] so p =
>a[:] is the same as
>p = a[0:len(a)]
>
>  
>
But in fact there is a difference. I'll show you:

 >>> a=range(5)### creates a list-object
 >>> id(a) ### which has an identity
14716520  
 >>> p=a  ### creates the new name p for the same object
 >>> id(p)### let's see
14716520   ### o.k. really the same
 >>> q=a[:]  ### this names a *copy* of a q
 >>> id(q)### identity?
14714840   ### different!
 >>> a is p   ### check if objects named a and p are identical
True### yes
 >>> a is q  ### check if objects named a and q are identical
False  ### no!
 >>> a == q 
True   ### but have the same "content", i. e. two 
different list-objects with the same elements
 >>>
 >>>### Beware, lists are mutable:
 >>>
 >>> a
[0, 1, 2, 3, 4]
 >>> a[1]=1001
 >>> a
[0, 1001, 2, 3, 4]
 >>> p
[0, 1001, 2, 3, 4]### object named a *and* p is changed
 >>> q ### copy q of a is not changed!°
[0, 1, 2, 3, 4]
 >>>
regards
Gregor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter, Frame and Canvas question.

2006-02-23 Thread Gregor Lingl
Hi Hugo,

some experiments showed, that the following code - using borderwidth=-2 
-  works as you desired, at least on my windows machine:

import Tkinter
from Tkconstants import *

class App(Tkinter.Frame):
   def __init__(self, master=None):
 Tkinter.Frame.__init__(self, master)
 self.pack()
 canvas1 = Tkinter.Canvas(self, background='#00', borderwidth=-2)
 canvas2 = Tkinter.Canvas(self, background='#00', borderwidth=-2)
 canvas1.pack(pady=0)
 canvas2.pack(pady=0)

if __name__ == '__main__':
  myapp = App()
  myapp.mainloop()


Alas, there is some strange anomaly: it only does so (i. e. doesn't
display that gray bar between the canvases) when run from IDLE or
by double-clicking the renamed file test.pyw or run from the
command window with the command: python test.py.
Double-clicking test.py performs differently(!) and still shows the 
border between the two canvases. Who understands? (Or do you think my
python installation is in a corrupted state?)

Regards, Gregor



Hugo González Monteverde schrieb:
> Hi all,
> 
> I'm running into trouble displaying some Tkinter Canvases, they keep a 
> border between themselves and there's no way I can have them display 
> without a grey gap between them.
> 
> I've narrowed the problem to the following example. I've tried all kind 
> of padding and border parameter to the Frame's pack() method and the 
> Canvas' pack() method.
> 
> Is there something I'm missing or plainly not understanding? I'd like to 
>   display canvases one next to the other without some kind of background 
> showing throug.
> 
> Thanks for taking a look, here's the example:
> 
> ===
> 
> import Tkinter
> from Tkconstants import *
> 
> class App(Tkinter.Frame):
>  def __init__(self, master=None):
>  Tkinter.Frame.__init__(self, master)
>  self.pack(pady=0, ipady=0)
>  canvas1 = Tkinter.Canvas(self, background='#00', borderwidth=0)
>  canvas2 = Tkinter.Canvas(self, background='#00', borderwidth=0)
> 
>  canvas1.pack(pady=0)
>  canvas2.pack(pady=0)
> 
> if __name__ == '__main__':
>  myapp = App()
>  myapp.mainloop()
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien

Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27

Website: python4kids.net
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] question concerning deepcopy

2006-04-28 Thread Gregor Lingl
Hi all of you,

I've some Vector class, which is a subclass of tuple and which is 
working satisfactorily since long in different contexts. Now I've 
constructed objects with attributes of Vec-type, which I wanted to 
deepcopy. But that doesn't work, because I can't (deep)copy Vec-s:

 >>> from copy import deepcopy
 >>> class Vec(tuple):
def __new__(cls, x, y):
return tuple.__new__(cls, (x,y))
def __abs__(self):
return (self[0]**2+self[1]**2)**0.5
 ## more methods ...


 >>> a=Vec(3,4)
 >>> abs(a)
5.0
 >>> b = deepcopy(a)

Traceback (most recent call last):
   File "", line 1, in -toplevel-
 b = deepcopy(a)
   File "C:\Python24\lib\copy.py", line 204, in deepcopy
 y = _reconstruct(x, rv, 1, memo)
   File "C:\Python24\lib\copy.py", line 336, in _reconstruct
 y = callable(*args)
   File "C:\Python24\lib\copy_reg.py", line 92, in __newobj__
 return cls.__new__(cls, *args)
TypeError: __new__() takes exactly 3 arguments (2 given)

Explanation? Remedy? Bug? Workaround?

Regards,
Gregor


-- 
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien

Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27

Website: python4kids.net
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question concerning deepcopy

2006-04-29 Thread Gregor Lingl


Kent Johnson schrieb:
> Gregor Lingl wrote:
> 
>>Hi all of you,
...
>>> from copy import deepcopy
>> >>> class Vec(tuple):
>>  def __new__(cls, x, y):
>>  return tuple.__new__(cls, (x,y))
>>  def __abs__(self):
>>  return (self[0]**2+self[1]**2)**0.5
>> ## more methods ...
>>
>> >>> a=Vec(3,4)
>> >>> abs(a)
>>5.0
>> >>> b = deepcopy(a)
>>
>>Traceback (most recent call last):
...
>>TypeError: __new__() takes exactly 3 arguments (2 given)
> 
> 
> Apparently you need to define __getnewargs__() for your class. This works:
>  def __getnewargs__(self):
>  return (self[0], self[1])
> 
> __getnewargs__() is documented with the pickle module but it is used by 
> deepcopy() as well.
> http://docs.python.org/lib/pickle-inst.html

Thanks, Kent  for the hint. It works (of course).
Skimming through this part of the docs I discovered, that there is a 
special method __deepcopy__. So I also  tried using this, adding

def __deepcopy__(self,visit):
return self

to my Vec class, which also seems to work. (I think this not to
be harmful as Vecs should be, like tuples, immutable).
And, indeed, it also seems to work.

Do you think this is also a correct way? If so, do you see there any 
advantages of one solution over the other one?

Regards,
Gregor



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question concerning deepcopy

2006-04-29 Thread Gregor Lingl



Kent Johnson schrieb:
> Gregor Lingl wrote:
> 
>>Thanks, Kent  for the hint. It works (of course).
>>Skimming through this part of the docs I discovered, that there is a 
>>special method __deepcopy__. So I also  tried using this, adding
>>
>>  def __deepcopy__(self,visit):
>>  return self
>>
>>to my Vec class, which also seems to work. (I think this not to
>>be harmful as Vecs should be, like tuples, immutable).
>>And, indeed, it also seems to work.
> 
> 
> That is not a correct deep copy, it is a shallow copy. Although Vec 
> objects are immutable they may contain mutable objects. The point of 
> deep copy is to copy "all the way down" so the objects contained by a 
> Vec should also be copied.

O.k. I understand. It's just that my Vec class invariably has two
numbers as elements (otherwise the abs-method wouldn't make sense.
That's what I meant with 'Vecs are immutable'). So in my case it works,
but would have to be considered bad style?

Thanks, again
Gregor

> Kent
> 
> _______
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien

Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27

Website: python4kids.net
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] simple question about numeric types

2006-05-02 Thread Gregor Lingl
Hi!

Is there a simpler/fster way to check if a value
has int or float type (i.e. is a "real number") than:

v=
if isinstance(v, int) or isinstance(v, float):
 

(v must not be complex)

Regards,
Gregor




-- 
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien

Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27

Website: python4kids.net
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Argument check

2006-05-04 Thread Gregor Lingl
Hi all,

I've a class with a lot of methods, for which I'd like to check argument types. 
To show you, what I mean, I've written a prototype I'm not really content with.
It goes like this (a bit revised in order to have short codelines (*mail* ;-)):

class BadArgError(Exception):
 def __init__(self, fname, var, typ, val):
 self.fname = fname
 self.var = var
 self.typ = typ
 self.val = val
 def __str__(self):
 return """
 %s: argument %s must be %s!
 %s of %s given.""" % ( self.fname, self.var,
 self.typ, repr(self.val), type(self.val))

def checkargs(fun,locs,*typelist):
 varnames=fun.im_func.func_code.co_varnames[1:]
 fn = fun.__name__
 for var, typ in zip(varnames, typelist):
 ok = isinstance(locs[var],typ)
 if not ok:
 raise BadArgError(fn, var, typ, locs[var])

## classe for testing:

class Z(object):
 pass

class A(object):
 def f(self,x,y):
 checkargs(self.f, locals(), int, str)
 def g(self,a,b,c):
 checkargs(self.g, locals(), (int,float), Z, tuple)


BadArgError works like this (interactive session):

 >>> bae = BadArgError("myfun", "myvar", str, 3)
 >>> raise bae

Traceback (most recent call last):
   File "", line 1, in -toplevel-
 raise bae
BadArgError:
 myfun: argument myvar must be !
 3 of  given.

You see, I want to the error-message to display the name of the function, which 
got the bad argument, the name of the parameter and it's expected type as well 
as the wrong argument.

Examples for it's use:

 >>> z=Z()
 >>> a=A()
 >>> a.f(1,"a")   #ok
 >>> a.f(1,2)

Traceback (most recent call last):
   File "", line 1, in -toplevel-
   ...
 raise BadArgError(fn, var, typ, locs[var])
BadArgError:
 f: argument y must be !
 2 of  given.
 >>> a.g(.5, z, ())#ok
 >>> a.g(.5, a, ())

Traceback (most recent call last):
   File "", line 1, in -toplevel-
   ...
 raise BadArgError(fn, var, typ, locs[var])
BadArgError:
 g: argument b must be !
 <__main__.A object at 0x00C92F70> of  given.

(One could easily tidy up this output - that's *not* the problem)

I feel it to be cumbersome and ugly, to have to pass the function (method) and 
the locals() dictionary to every call of checkargs.

I'd very much prefer a usage of checkargs similar to:

class A(object):
 def f(self,x,y):
 checkargs(int, str)
 def g(self,a,b,c):
 checkargs((int,float), Z, tuple)

but then chackargs had to get information about its caller (name, locals) from 
elsewhere (the callstack?). I don't know if this is possible at all, not to say 
how to accomplish it.

Do you have some hints?
Where could I find code-examples which solve similar problems?
Would you recommend a different approach?

Regards,

Gregor





-- 
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien

Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27

Website: python4kids.net

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How do I do cubic roots and cubic exponents (and higher roots and exponents) in Python?

2006-05-09 Thread Gregor Lingl
Danny Yoo schrieb:

>  
>
>>How do I do cubic (and higher) roots ...
>>
>
>I think you're looking for the '**' operator.  Like addition and 
>multiplication, it can take in two numbers.
>
>##
>  
>
2 ** 2


>4
>  
>
And they also can be floating point numbers

 >>> 2 ** 0.5
1.4142135623730951
 >>> 2 **(1.0/3)
1.2599210498948732
 >>> 1.2599210498948732**3
2.0

:-)

gregor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] for teachers and students: xturtle.py a new tutle graphics module

2006-06-25 Thread Gregor Lingl
xturtle.py, extended turtle graphics
a new turtle graphics module for Python and Tkinter

Version 0.9 of xturtle.py has been released.  It can be found at:

http://ada.rg16.asn-wien.ac.at/~python/xturtle

xturtle should work properly on all major platforms (Mac, Linux and
Windows) Feedback would be appreciated to take it into account for
polishing it to a final version 1.0.

--
Learning to program computer should be fun, for adults and children
alike. xturtle.py is a module designed to help you learn computer
programming using Python. Turtle graphics provides a means for the 
beginning programmers to get immediate visual feedback about the 
correct working of her programs. It's main goal is to provide
easy access to a sufficiently rich graphics toolkit. 
 
It needs only the standard distribution of python (incl. Tkinter) and 
imho it (or some descendant of it) once could (and should?) replace 
turtle.py which is contained in the current standard distribution.

xturtle - delivered as a zip-file - contains four main elements:
1. the module xturtle.py .
2. set of 25+ sample scripts of great variety to show possible
uses of xturtle.py
3. A simple demoViewer to run and view those sample scripts
4. documentation in form of *.txt files, which also can be viewed
with the demoViewer. Docs are derived from doc strings. thus Python's
help utility works fine with the module xturtle.py

For more information (e.g. some screenshots) see the web page 
mentioned above.

Gregor

(It was very convenient for me to use Andre Roberge's last
posting as a pattern.  You don't mind, Andre?)


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] no loops

2006-07-11 Thread Gregor Lingl
Christopher Spears schrieb:

IF you know that it's 2 seconds after midnight,
how many hours, minutes, seconds after midnight ist this.

If you should compute this by hand, how would you proceed?

Best wishes,
Gregor

> I am working on another problem from "How To Think
> Like A Computer Scientist".  Here is a function:
>
> def increment(time, seconds):
>   time.seconds = time.seconds + seconds
>
>   while time.seconds >= 60:
> time.seconds = time.seconds - 60
> time.minutes = time.minutes + 1
>
>   while time.minutes >= 60:
> time.minutes = time.minutes - 60
> time.hours = time.hours + 1 
>
> Here is the function in action:
>
>   
 from time import *
 atime = Time()
 atime.hours = 1
 atime.minutes = 60
 atime.seconds = 120
 printTime(atime)
 
> 1:60:120
>   
 increment(atime,1)
 printTime(atime)
 
> 2:2:1
>
> Now the exercise is:
> As an exercise, rewrite this function so that it
> doesn't contain any loops.
>
> I have been staring at this function and drawing a
> blank.  Something tells me that I need to use
> iteration, but I am not sure how I could implement it.
>
> -Chris
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Alias for a class name

2006-07-12 Thread Gregor Lingl
Hi everyoen,

say in some module I have defined a class Pen
and I want an alias for the class name, say
Turtle

I can do this:

class Turtle(Pen):
pass

or simply (after having defined Pen):

Turtle = Pen

Are those two variants different in effect?
Are there pros or cons for one of both
variants?

Regards,
Gregor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] arguments

2007-02-15 Thread Gregor Lingl
[EMAIL PROTECTED] schrieb:

>Hi list,
>
>I have a function with two arguments (say f(x,y))
>and second which returns tuple (say def g(): return (xx,yy))
>
>my question is how to put returned values from g() as
>arguments to f ?
>  
>
There is a special *-operator, which inserts the components of an Argument
(which must be a sequence) into the parametersof the calling function:
 >>> def f(x,y):
print x,y

   
 >>> def g():
return -5,1001

 >>> f(*g())
-5 1001
 >>>
Regards,
Gregor



>the direct way generates error:
>
>f(g())
>TypeError: ff() takes exactly 2 arguments (1 given)
>
>and the hard way is
>x, y = g()
>f(x,y)
>
>is ok but it uses two extra variables. Is there a simple way
>to do this?
>
>BTW f(g()[0], g()[1]) works too, but calls function g()
>twice ...
>
>thanks in advance
>e.
>
>
>
>-
>
>SCENA - Единственото БЕЗПЛАТНО списание за мобилни комуникации и технологии.
>http://www.bgscena.com/
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Stupid Pythony Newbie Question: Basic Operators;

2008-03-16 Thread Gregor Lingl

Michael Lim schrieb:
> Sorry guys, this is a newbie question... can someone please help me 
> with what the following 2 basic operators do in like simple english:
>
> 1.
>
> ^
This operator performs a logical operation, the exclusive or, also xor, 
for the binary digits af two integer numbers. The operation will be 
performed bitwise. You will understand this only if you know what the 
binary  representation of a integer is. It goes like this:

xor of two digits 0 or 1 returns 1 if these are different and 0 else.

12--->'1100'(which means 12 = 8 + 4)
9 --->'1001'(which means 9 = 8 + 1)
  xor:'0101'so the result is 4 + 1 = 5

 >>> 12 ^ 9
5
 >>>

>
> 2.
> %
This is simpler: % returns the remainder you get if you perform an 
integer division. Example 17 divided by 5 results in the quotient 3 and 
the remainder 2.

 >>> 17 % 5
2

If you want to know both, quotient and remainder, you can use the divmod 
function:

 >>> divmod(17,5)
(3, 2)

With best regards,
Gregor

> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] returning two values

2008-03-21 Thread Gregor Lingl

elis aeris schrieb:

is it possible to return two values?


Yes:
>>> def return2():
   return "this", "that"

>>> return2()
('this', 'that')
>>> a,b=return2()
>>> a
'this'
>>> b
'that'
>>>
Regards,
Gregor




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
  


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by a bug in turtle.py

2008-08-06 Thread Gregor Lingl



Kent Johnson schrieb:

On Tue, Aug 5, 2008 at 6:49 PM, Dick Moores <[EMAIL PROTECTED]> wrote:
  

For a while now I've had trouble with end_fill(). Sometimes I can use
it to fill a figure such as a square, triangle or rectangle, but
sometimes not.

Here's a barebones script using end_fill(). As you can see, it draws a
square twice, but fails to fill it. Pleas show me how to use it
correctly in tandem with begin_fill().



  

Hi all,

Kent's version below repairs the problem more or less accidentally
and moreover not completely:

(1) the first square is not filled properly; instead a filled pentagon 
appears

after the first traversal of the loop.
(2) the filling takes place due to the goto() call after the end_fill() 
call and

before the clear() call.

This is due to a bug in turtle.py - interestingly after so many years of use
and improvement of turtle.py there still appear new bugs from time to time.

The bug consists in a missing update of the Canvas in the fill() function
You can repair it by inserting a line at line#309 in turtle.py in the
fill method as follows:

   if self._filling:
   path = tuple(self._path)
   smooth = self._filling < 0
   if len(path) > 2:
   item = self._canvas._create('polygon', path,
   {'fill': self._color,
'smooth': smooth})
   self._items.append(item)
   self._canvas.update()  #  <=== bug-fix
   self._path = []

Now for the good news:

(1) If you have done this, not only Dick's program works as
intended, but you may also write the square_filling program
in a cleaner way, for instance like this:

from turtle import *
import time

setup(width=1000, height=700, startx=0, starty=0)
color_name = 'red'
x, y = 50, 50
color(color_name)
print color_name
up()
goto(x, y)
down()
for n in range(2):
  begin_fill()
  goto(x, -y)
  goto(-x, -y)
  goto(-x, y)
  goto(x, y)
  end_fill()
  print "end_fill()"
  time.sleep(1)
  clear()

(2) Python 2.6 will have a new turtle module - formerly known to some
as xturtle.py - which has much more capabilities and which at least 
doesn't show
this bug. Presumably there will appear others, especially in the 
beginning of

it's use. It is contained in Python2.6 beta2, it runs also under Python2.5
and it should be (nearly?) 100%-compatible with the old turtle module.

Its documentation can be found here:
http://docs.python.org/dev/library/turtle.html#module-turtle

It would be really very helpful, if those of you who use to use turtle
graphcis would work with this new module in order to reveal as many
bugs as possible before the final release of Python 2.6 scheduled for
early october 2008.

Of course I'd assist if questions or problems would arise.

Regards
Gregor

Here is a version that does fill:
from turtle import *
import time

setup(width=1000, height=700, startx=0, starty=0)
for n in range(2):
   color_name = 'red'
   x, y = 50, 50
   color(color_name)
   print color_name
   up()
   goto(x, y)
   down()
   begin_fill()
   goto(x, -y)
   goto(-x, -y)
   goto(-x, y)
   end_fill()
   print "end_fill()"
   goto(x, y)
   time.sleep(1)
   clear()

I have no idea why this one works and yours doesn't. Your program is
very similar to the filled square in turtle.demo() which does work.

The filling is implemented by drawing a polygon on a Tkinter Canvas;
is there something strange about polygons?

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Ongoing trouble with Turtle's end_fill()

2008-08-07 Thread Gregor Lingl

Alan Gauld schrieb:

"Dick Moores" <[EMAIL PROTECTED]> wrote


1. The turtle has some behavior I don't see how to eliminate. If you
refer to lines 223, 225, 227, 229, etc., you'll see that the turtle
always faces in the direction it is moving when drawing a rectangle.


That is correct behaviour for a turtle!
Remember turtle graphics are notionally about moving a physical
drawing device (the turtle) around on the floor or desk. If the turtle
doesn't turn to face the direction of travel it can't travel that way!

IMHO that's just a feature of the technology and any other behaviour
would be out of keeping with the intent.


Hi all,
development of this rectangle pattern program is going verry fast and
as I see Dick has managed to abridge his program by some
fifty lines (using the new turtle module).

Most of his questions got superb answers by Alan, so I'll add only
a few remarks:

In fact Dick doesn't use any turtle graphics functions in it's precise 
original

meaning. Instead he uses a (global) Cartesian coordinate system and
moves the turtle only by calling goto().
(This approach is perfectly ok for his task, of course).

Turtle graphics by contrast uses a local coordinate system of the "turtle"
and moves it by calling only forward(), back(), left() and right() 
functions.



Using the Python2.6 beta2 version of turtle.py, the turtle can be seen
at each corner spinning to orient itself to the new direction. I don't
want this.

So you eliminated the superfluous setheading() calls.


While far from common in turtle implementations (I have only seen
it in my old CP/M Logo version) it is a feature that would be true
of a physical turtle too. Its not really a bug but a "feature" I guess!


2. The turtle can also be seen moving from the last corner of the last
rectangle to the first corner of the next. I don't want this.

This is ideed an intended difference between the new and the old
turtle module. I consider this to be an improvement of the animation
of the turtle. (You can observe another improvement by trying out
e. g. left(1080) ) The intention is that the beginning programmer
can visually observe what he or she has programmed and thus more
easily identify errors in his/her program. To that end the turtle
moves and turns at the specified speed regardless of the state of
the pen (up or down).

If you don't like this you can set speed to 0 which - paradoxically -
means that the animation is turned off and the turtle jumps instantaneously.
(Think of something like speed(False))

Again true of a physical turtle... But if you set speed to fastest
does that work? 

Yes, that is speed(0). See above

Also in the old turtle moduile there was a way to
hide the turtles movements completely and just draw the finished
graphic - which was orders of magnitude faster for complex
shapes - is that still available in turtle26?

Yes it is (of course ;-) ). Use tracer in the same way as in the old one.



One way to hide the turtle would be top change colour to the
background color. That would make themoving turtle invisible...


As Dick discoverd you can use  hideturtle() and showturtle()

3. When the screen is cleared between cycles by line 367, the blank
screen shows for a second or so. I don't want this.
In my program using the old turtle I've had to create
colored-backgrounds by drawing a rectangle almost as large as the
screen (see my draw_background() beginning at line 365). With the new
turtle, the background color can be set by, for example,
screen.bgcolor("orange"). But even so, in the V16 I was trying to
write, that blank screen still shows for a second or so. With the old
turtle, the transition from one "background" to another seems
instantaneous. No white blank screen visible at all.


Sounds like a valid complaint that one...

This again is a result of the animation of the turtle. Of course a correct
use of bgcolor() solves this problem - as Dick did now -, but also use 
of speed(0)

or tracer(False) would have solved it.

Regards,
Gregor

P.S.: If you are interested, you can download a series of sample programs
covering a broad range from very easy to fairly advanced, which
intend to show some features and capabilities of the new turtle module
from here:

http://svn.python.org/view/python/trunk/Demo/turtle/

These will be included in the source distribution - but not in the Windows
installer.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by abug in turtle.py

2008-08-07 Thread Gregor Lingl

Hi Dick,

first of all, thanks for your efforts using the new turtle module
and reporting about your experiences and the problems you ran into.

I've already made some remarks on it in a former reply in this thread.

On Thu, Aug 7, 2008 at 11:26 AM, Alan Gauld <[EMAIL PROTECTED]> wrote:
  
...

2. The turtle can also be seen moving from the last corner of the last
rectangle to the first corner of the next. I don't want this.
  

Again true of a physical turtle... But if you set speed to fastest
does that work? Also in the old turtle moduile there was a way to
hide the turtles movements completely and just draw the finished
graphic - which was orders of magnitude faster for complex
shapes - is that still available in turtle26?


Here better tracer() should come in!


Yes, penup(). 
  


Maybe more not understanding(remembering) the origin of turtle graphics.
It was for kids to understand computer graphics... Seeing the shapes
being drawn is a big part of that.

That's why now turtles have got a better animation. (That means: the 
resulting drawing should be
the same weather you use the old module or the new one, but *not* what 
you see, when you observe
the turtles at work. Therfore I wrote (nearly?) 100% compatible. And of 
course, the now one

has a lot of additional enhacements.)

Best regards,
Gregor

Well, I also want to see the rectangles being drawn--by an invisible turtle. ;-)

Actually, I got interested in this because of the colors. I had just
bought my first LCD monitor, a 22-incher. And I wrote the program so
that it prints the color names to the console window. I had been
ignorant about colors--had no idea what magenta, chartreuse,
turquoise, cyan were, just to mention a few.

Thanks, Alan.

Dick
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by abug in turtle.py

2008-08-08 Thread Gregor Lingl

Dick Moores schrieb:


Here better tracer() should come in!



'Deprecated in version 2.6'?? And the doc gives nary a clue how to use it.
http://docs.python.org/dev/library/turtle.html#turtle.tracer
  
tracer is only deprecated as a Turtle-method, because it doesn't concern 
single turtles but
all the turtles on the screen. It will stay as Screen-method and of 
course also as function.
(As a turtle-method it's only there because of compatibility with the 
old turtle module.)


Gregor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Ongoing trouble with Turtle's end_fill() - Important note!

2008-08-08 Thread Gregor Lingl




P.S.: If you are interested, you can download a series of sample programs
covering a broad range from very easy to fairly advanced, which
intend to show some features and capabilities of the new turtle module
from here:

http://svn.python.org/view/python/trunk/Demo/turtle/

These will be included in the source distribution - but not in the 
Windows

installer.



IMPORTANT NOTE!
In order to have the examples working correctly you have to have turtle.cfg
in the directory where the example scripts are (or in that with turtle.py).
An easy way to have a look at all the examplescripts is using turtleDemo.py

Gregor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by abug in turtle.py

2008-08-08 Thread Gregor Lingl

Hi Dick,

just to show you a bit of the versatility of the new turtle module
I've prepared to tiny rectangle-generator program examples.

They intentionally use different programming styles and also
turtle graphics techniques different from the ones you used
to accomplish something similar to what you did, of course
in a very simplified way and without your eleborated user
interface and colormanagement.

---
Version 1: procedural, using stamp()
---

from turtle import *
from random import random, randint
from time import sleep

MAXLEN = 30
MAXWID = 25

def randomcolor():
   return random(), random(), random()

reset()
title("Python turtle graphics: random rectangle generator")
hideturtle()
resizemode("user")
shape("square")
for cycle in range(randint(3, 5)):
   bgcolor(randomcolor())
   for rect in range(randint(5,10)):
   shapesize(3 + random()*MAXLEN, 3 + random()*MAXWID,
  randint(3, 10))
   color(randomcolor(), randomcolor())
   stamp()
   sleep(0.5)
   sleep(1)
   clearstamps()


---
Version 2: object oriented, uses a list of turtles,
which change their properties (size, color, visibility)
---

from turtle import Screen, Turtle
from random import random, randint
from time import sleep

MAXLEN = 30
MAXWID = 25

def randomcolor():
   return random(), random(), random()

class RectGenerator(object):
   def __init__(self):
   self.s = s = Screen()
   s.reset()
   s.title("Python turtle graphics: random rectangle generator")
   self.rectturtles = []
   for n in range(10):
   t = Turtle(visible=False)
   t.hideturtle()
   t.resizemode("user")
   t.shape("square")
   self.rectturtles.append(t)
   def run(self):
   for cycle in range(randint(3, 5)):
   self.s.bgcolor(randomcolor())
   n  = randint(5,10)
   for index in range(n):
   t = self.rectturtles[index]
   t.shapesize(3 + random()*MAXLEN, 3 + random()*MAXWID,
randint(3, 10))
   t.color(randomcolor(), randomcolor())
   t.showturtle()
   sleep(0.5)
   sleep(1)
   for t in self.s.turtles():
   t.hideturtle()

if __name__ == "__main__":
   rg = RectGenerator()
   rg.run()


Hope you like it
Gregor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Questions about the new turtle module in Python 2.6b2

2008-08-09 Thread Gregor Lingl

Dick Moores schrieb:

At 03:12 AM 8/9/2008, Dick Moores wrote:
4. For my random_rectangles.py program I've started to try out the 
new turtle. (See the current state of random_rectanglesV16_web.py at 
< http://py77.python.pastebin.com/d3e842821>.) 
 The only 
downside I've found is that the new turtle is much faster that the 
old. I want to set the speed so that the outlines of rectangles are 
drawn slowly enough that the user (me at present) can both appreciate 
the colors and have time to check the names of the colors being 
printed in the console window. Using the old turtle, I found that a 
default delay of 1 ((delay(1)) was just right; with the new turtle, 
setting a delay of even 50 affects only the first cycle of 
rectangles. So I don't use delay at all. Setting the slowest speed of 
1 (speed(1)) is still too fast. How can I slow down the drawing of 
the rectangles?


I seem to have solved #4.

I had been using tracer() as tracer(True) in my function draw_rect(). 
In rereading the doc, I noticed that < 
http://docs.python.org/dev/library/turtle.html#turtle.tracer>

has
"turtle.tracer(/flag=None/, /delay=None/)"

so in draw_rect() I tried changing tracer(True) to tracer(True, dly). 
(See the new version, random_rectanglesV17_web.py, at < 
http://py77.python.pastebin.com/f54c9211f>, lines 220, 230, 240, etc.)


Then I enabled the user to enter both speed and delay, with a default 
speed of 1 and a default delay of 15 (see the new function 
get_speed_and_delay_from_user(), lines 153-179). On my computer, these 
defaults seemed to be ideal.



That's fine!
But now I have another puzzle: As long as delay is kept constant, it 
doesn't seem to matter what speed is chosen -- from the slowest of 1 
to the fastest of 0. Why is speed irrelevant?

Did you observe that faster speeds need arguments in the range from 2 to 10?
That means speed(10) is fastest speed.

Gregor


Dick

BTW at < http://py77.python.pastebin.com/f54c9211f>, if you click on 
the 'view diff' link just above the code, you'll get a diff with the 
immediately previous version.








___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
  


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Questions about the new turtle module in Python 2.6b2

2008-08-15 Thread Gregor Lingl

Hi Dick,
as I promised some days ago, here is an event driven version of
a rectangle generator, which is based on my first example:

from turtle import *
from random import random, randint
from time import sleep

MAXLEN = 30
MAXWID = 25

def randomcolor():
   return random(), random(), random()

def pause(x,y):
   global running
   running = not running
   if running:
   title("RUNNING... - CLICK TO HALT")
   else:
   title("HALTED... - CLICK TO CONTINUE")
  
def squares(x,y):

   clear()
   title("RUNNING... - CLICK TO HALT")
   onscreenclick(pause)
   for cycle in range(randint(3, 5)):
   bgcolor(randomcolor())
   for rect in range(randint(5,10)):
   shapesize(3 + random()*MAXLEN, 3 + random()*MAXWID,
  randint(3, 10))
   color(randomcolor(), randomcolor())
   stamp()
   update()
   sleep(1)
   update()
   while not running:   # now pausing
   sleep(0.5)
   update()
   sleep(1)
   clearstamps()
   bgcolor("white")
   pencolor("black")
   write("Click to exit!", align="center", font=("Arial", 24, "bold"))
   title("")
   exitonclick()
  
  
reset()

title("Python turtle graphics: random rectangle generator")
hideturtle()
resizemode("user")
shape("square")
running = True
onscreenclick(squares)
listen()
write("Click me!", align="center", font=("Arial", 24, "bold"))
mainloop()

 end of program

A short explanation:
In event driven programs you have to ecapsulate all actions in
functions (or methods when using oop-techniques) which have to
be bound to some events. In this example this happens via the
onscreenclick() function.

The functions that perform the desired actions are not called
in the  main program. Instead the main program calls the
mainloop() which is a loop waiting for events. If such an
event - like a mouse click - occurs the function bound to
this event will be called. This function may rebind the event
to another action - as is done in squares - line three.
So in this example the first click starts the rectangle
generator, subsequent clicks will swith the running-state.
(The last click wil terminate the program.)

Making a program pause needs a special trick:
the pause() function + boolean variable running.
update() is used  to make the program check the
event-queue.  (This would not be necessary, I think,
if you draw rectangles slowly using goto(), because in
this case the animation itself automatically uses update()
frequently.)

Hope this helps - if not feel free to aks again

Gregor



Gregor Lingl schrieb:

Dick Moores schrieb:

Gregor,

<http://docs.python.org/dev/library/turtle.html#turtle.setup>
1. I want the window to open with the right edge 0 pixels from the 
right edge of my screen.
However, setup(width=.75, height=.915, startx=-0, starty=0) doesn't 
work. I have to do the nearest thing,
setup(width=.75, height=.915, startx=-1, starty=0). A small thing, 
but what's wrong with perfection.



Hi Dick,
a good observation, but I think this cannot be changed, because  of

>>> -0 == 0
True

in Python

2. There's a lot I don't understand in
turtle.setup(width=_CFG[, "width"], height=_CFG[, "height"], 
startx=_CFG[, "leftright"], starty=_CFG[, "topbottom"])


What is '_CFG'? And how should anyone know what it is?
What is "leftright"? And how to use it?
What is "topbottom"? And how to use it?

_CFG is an internal dictionary, which contains configuration data. You 
can change these
by editing adding or editing the turtle.cfg file (an example is in the 
Demo directory).

How to do this you can find here:

http://docs.python.org/dev/library/turtle.html#how-to-configure-screen-and-turtles 


3. http://docs.python.org/dev/library/turtle.html#turtle.stamp

"turtle.stamp()
Stamp a copy of the turtle shape onto the canvas at the current 
turtle position. Return a stamp_id for that stamp, which can be used 
to delete it by calling clearstamp(stamp_id)."


But in your version 1 
(<http://article.gmane.org/gmane.comp.python.tutor/49805>), the 
turtle is hidden by hideturtle()! What are you stamping? It seems the 
shape, or rectangle. If so, why does the doc say 'turtle'?


there will be stamped the shape of the turtle, that appeared  if it 
were not hidden.


General remark: you can investigate Python and especially its turtle 
module interactively
using IDLE. But note: in the case of graphics (Tkinter and especially 
turtle.py) you have to
use the -n switch of IDLE. So the link calling idle must look 
something like this:


/... ../... ../python  /... ../.../.../idle.pyw -n

the dotted parts representig the path according to your system 
configuration


If you have 

Re: [Tutor] TOT: what does the "@" operator mean?

2008-12-16 Thread Gregor Lingl



Marc Tompkins schrieb:

By the way, (totally off-topic, of course, my apologies): what do all
y'all call the "@" operator?  Here in the States, we call it the
"at-sign", which I find boring; I believe "sleepycat" is a
Scandinavian thing (I picked it up in some long-forgotten article);
some Russians refer to it as собака ("sobaka", dog) - again because it
looks like an animal with its tail curled up.

  

In German we call it 'Klammeraffe' - which means 'spider monkey':
http://en.wikipedia.org/wiki/Spider_monkey
Don't know why, perhaps also because of it's long tail
Regards,
Gregor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor