Re: [Edu-sig] teaching python using turtle module

2009-11-30 Thread Gregor Lingl

Hello Brian,

I think the most natural use of the if statement (using turtle
graphics) occurs in recursive functions drawing trees,
fractals and the like. This is well known from Logo, where
recursion is the canonical way of doing repetitions. (But
note, that Logo has tail recursion optimizaton!)

If you are not yet ready to use recursion with your students,
probably many  of the problems coming to your mind that need
the examination of conditions  can be solved better by using
a conditional loop (i. e. a while -loop in Python) than by
using mere if statements.

That is not the case however, if you have to perform actions in
the body of a loop, that depend on the current situation.
I did a quick search in my repository of examples and found
a fairly short and simple script that demonstrates, what I mean:
a drunken turtle collecting coins (or whatever) on its random walk.


# Python script using turtle graphics

from turtle import Screen, Turtle
from random import randint

s = Screen()
s.setup(560,560)
s.title("A drunken turtle collecting ...")

s.tracer(False)
writer = Turtle(visible=False)
writer.penup()
writer.goto(0, -275)

coins = []
for i in range(-4,5):
   for j in range(-4, 5):
   if i == j == 0:
   continue
   c = Turtle(shape="circle")
   c.color("", "orange")
   c.shapesize(0.5)
   c.goto(40*i, 40*j)
   coins.append(c)
s.tracer(True)

DRUNKENNESS = 45   
t = Turtle(shape="turtle")

t.color("black","")
points = 0
while abs(t.xcor()) < 200 and abs(t.ycor()) < 200:
   t.forward(5)
   t.right(randint(-DRUNKENNESS, DRUNKENNESS))
   found = None
   for c in coins:
   if t.distance(c) < 10:
   found = c
   break
   if found:
   found.hideturtle()
   coins.remove(found)
   t.shapesize(1+points/5., outline=1+points)
   points += 1

writer.write("{0} points".format(points),
align="center", font=('Arial', 24, 'bold'))

## End of script


You can see a screenshot of a run of this script here:

http://www.dropbox.com/gallery/2016850/1/TurtleCollector?h=6b370a

The script could be expanded in several ways, e. g. for
doing statistical investigations or examinig how the
result depends on different parameters like drunkenness etc.
Or you distribute the coins randomly ... Does that alter
the average "harvest"?

Just a suggestion ...

Regards,
Gregor


Brian Blais schrieb:

Hello,

I was just playing with the turtle module, and thought it was an 
interesting way to augment the introduction to python (I teach college 
students, who haven't had any programming).  It's a great way to 
introduce functions, for-loops, and general program structures.


After a bit of playing, I realized that I couldn't think of many 
examples which use turtle with conditional structures (if- and while- 
statements), or functions that return values, as opposed to 
"procedures" like:


def square(length):
forward(length)
right(90)
forward(length)
right(90)
forward(length)
right(90)
forward(length)
right(90)


If-statements could possibly be used with some sort of random behavior 
(if rand()<0.5 ...).  Are there any other situations, using turtle, 
that these structures would be natural? 




thanks,

Brian Blais

--
Brian Blais
bbl...@bryant.edu 
http://web.bryant.edu/~bblais 





___
Edu-sig mailing list
edu-...@python.org
http://mail.python.org/mailman/listinfo/edu-sig
  

--
http://mail.python.org/mailman/listinfo/python-list


Re: [Edu-sig] teaching python using turtle module

2009-11-30 Thread Gregor Lingl



kirby urner schrieb:

I'm glad turtle graphics intersected my thinking re extended precision
decimals (Decimal type) on edu-sig just now.

I've updated my tmods.py to contain a turtle rendering the plane-net of a T-mod:

http://www.4dsolutions.net/ocn/python/tmod.py (runnable source)
http://www.flickr.com/photos/17157...@n00/4147429781/  (GUI view)
  

Nice tiny app! Albeit not an example for using the if statement ;-)
Just to show you how turtle.py enables you to implement this
using quite different approaches to doing geometry, I'd like to add
two more implementations.

Besides you may notice that these do not rely on rather complicated
calculations of distances and angles, using the Pythagorean theorem
and trigonometrics but only on a few more fundamental properties of
the figure.

# Version 2 - using coordinate geometry without coordinates ;-)
# a different implementation for Kirby's "Plane Net for T-module"

from turtle import *
from math import sqrt

PHI = (sqrt(5)-1)/2

def planeNet(h=500): 
  setup(560,560)

  title("Plane Net for T-module")
  penup()
  back(h/2); left(90); back(h/2); right(90)
  pendown()

  forward(h); left(90)
  forward(h*PHI); A = pos(); forward(h-h*PHI); left(90)
  forward(h*PHI); B = pos(); forward(h-h*PHI); left(90)
  forward(h); C = pos()

  for P in A, B, C:
 goto(P)


# Version 3 - stamping simple transforms of the shape of
#  an isosceles rectangular triangle:

from turtle import Screen, Turtle
from math import sqrt

GOLDEN_RATIO = (sqrt(5)-1)/2

def planeNet(h=500.0, phi=GOLDEN_RATIO): 
  s = Screen(); s.setup(560,560); s.title("Plane Net for T-module")

  s.register_shape("recttriangle", ((0, 0), (h, 0), (0, h)))
  designer = Turtle(shape="recttriangle")
  designer.color("black","")
  designer.penup()
  designer.goto(-h/2, h/2)

  for width, height in ((1, 1-phi), (phi, 1-phi), (phi, 1)):
 designer.shapesize(width, height)
 designer.stamp()
 designer.forward(h)
 designer.right(90)
  designer.hideturtle()

Hoping, you will find this a bit interesting,
best regards

Gregor




Here's the graphical output:

http://www.flickr.com/photos/17157...@n00/4148139184/in/photostream/
(Python 3.1)

If you actually wanna fold the T, you need to snip off the cap and
reverse it, per this diagram:

http://www.rwgrayprojects.com/synergetics/s09/figs/f86515.html

120 of them, 60 folded left, 60 folded right, all of volume 1/24, make
the volume 5 rhombic triacontahedron.

http://www.rwgrayprojects.com/synergetics/s09/figs/f86419.html

If you blow up the volume by 3/2, to 7.5, the radius becomes phi /
sqrt(2) -- what we're showing with Decimals.

The reason this seems unfamiliar is the unit of volume is the
tetrahedron formed by any four equi-radiused balls in inter-tangency.

I'm spinning this as Martian Math these days, yakking on
math-thinking-l about it, learned it from Bucky Fuller, Dave Koski et
al.

Kirby

  

--
http://mail.python.org/mailman/listinfo/python-list


ANN: Python's turtle module: collection of examples + demoViewer

2009-08-04 Thread Gregor Lingl

Hi all,

A few days ago I've created a repository of turtle graphics 
demos/applications, that use Python's new turtle module.

You can find it at at google code:

http://python-turtle-demo.googlecode.com

There are two versions of the collection: one for use with Python 3.1
and one for use with Python 2.5 / 2.6. The latter contains a

***  backport of version 1.1 of the turtle module  ***
***  (from Python 3.1) to Python 2.5 / 2.6 *** 



Among others it contains all the examples I have demonstrated
at Pycon 2009 and at EuroPython 2009.

Moreover it contains the demoViewer (which is also in the source
distribution of CPython) that lets you select the examples via a menu,
display their source code and execute them in parallel.

If you are interested to amend some of these examples, add some
explanatory material or contribute additional examples, please tell
me so I could add you as a committer to the project.

I'd be glad to expand the repository whith interesting examples
and applications using the turtle module.

If you have questions concerning the examples, feel free to ask
here or ask me directly via my email-address.

I hope this collection will prove to be useful.

Best regards,
Gregor

P.S.: I tried to announce it at comp.lang.python.announce
but for some unknown reason it was not accepted there


--
http://mail.python.org/mailman/listinfo/python-list


Re: Announcing PythonTurtle

2009-08-04 Thread Gregor Lingl

cool-RR schrieb:

Hello,

I wanted to announce that I have just released my little side project,
PythonTurtle.
Here is its website:
http://pythonturtle.com

Its goal is to be the lowest-threshold way to learn (or teach) Python.
You can read more about it and download it on the website.

Ram.


Hi Ram,

that's indeed a nice starting point for kids to doing turtle graphics, 
although currently it seems to implement only a very small subset of 
Python's turtle module's capabilities, even less than those of the old 
turtle module (that shipped with Python upto 2.5).


Moreover I have to complain that you decided to use different commands 
for the turtle's actions - go instead of forward, turn instead of left 
and right etc. First I think left and right are more intuitive than turn 
as they do not need negative angles as arguments, which might matter for 
young children. Also I cannot see the advantage of cammands like 
visible() or invisible() over showturtle() and hideturtle()


But second even kids - when learning how to program - will arrive at a 
point where it's no more problem to use an editor like IDLE so they
could easily switch to Python's turtle module. That would be even easier 
if they had not to learn a new command set.


Moreover a learning environment like PythonTurtle needs something like 
an editor - at least a simple one - in order to create programs that can 
be run repeatedly. Coding, that's creating programs - not only issuing

a sequence of cammands interactively.

It would be certainly a good thing if one had a similar environment 
using Tkinter, preferably also as part of the standard distribution of 
Python accompanying the turtle module. I think it should not be that 
difficult to create a GUI of this sort combining IDLE's shell window, 
its editor and turtle.py. Alas, at the moment I'm too busy with some 
othr work to start a project like this. Perhaps someone else might be 
interested? I'd enjoy to join a team doing it.


Finally I'd like to stress, that the aims of PythonTurtle and Python's
turtle module are quite different - as one could grasp easily by trying
out the collection of examples at python-turtle-demo.googlecode.com that 
I posted in another posting. Anyway they could very well complement one 
another in some more mature state of development.


Best regards,
Gregor





--
http://mail.python.org/mailman/listinfo/python-list


Re: Announcing PythonTurtle

2009-08-04 Thread Gregor Lingl

cool-RR schrieb:

On Aug 4, 7:12 am, John Posner  wrote:

... I would also venture to say a key-map



...

If you're asking WHY I put it in a wxPython application, the answer is
pretty much what "r" said: To make it like any other "over the
counter" Windows application, making people feel more comfortable with
it.
Also, not requiring them to install Python+packages, but just
PythonTurtle.
Fortunately it's not necessary to install 'packages' to use Python's 
turtle module as it is one of it's 'batteries included'. And I think 
it's not so a bad idea to install Python if one want's to learn it, anyway.


Regards,
Gregor



Ram.

--
http://mail.python.org/mailman/listinfo/python-list


Re: Announcing PythonTurtle

2009-08-04 Thread Gregor Lingl

cool-RR schrieb:

Hi Ram,

that's indeed a nice starting point for kids to doing turtle graphics,
although currently it seems to implement only a very small subset of
Python's turtle module's capabilities, even less than those of the old
turtle module (that shipped with Python upto 2.5).

...

A text editor would be a good feature for future versions.
Regarding the naming of functions: I named them in the way that seemed
best to me. You seem not to agree, you like the way your functions are
named better, and there's little point in arguing over which
convention is truly better. The convention I chose is the one that
seemed ideal to me.
I did consider naming the functions the same way you did for
consistency, but I decided not to compromise the quality of
PythonTurtle just to be compatible with a module that my users may not
even use.


That's the advantage of not developing for the standard library. In fact 
those elementary commands you use were present already in the old turtle 
module. When I decided to extend the old turtle module a primary 
requirement was that it remains 100% compatible to the old one. New 
versions of a module in the standard library must not break code of 
previous users of that module. In short: I did not name these functions 
but I had to use the names that already were there.


Nevertheless I'd prefer left and right over turn even today, especially 
for kids as I argued before.


Regards,
Gregor




It would be certainly a good thing if one had a similar environment
using Tkinter, preferably also as part of the standard distribution of
Python accompanying the turtle module. I think it should not be that
difficult to create a GUI of this sort combining IDLE's shell window,
its editor and turtle.py. Alas, at the moment I'm too busy with some
othr work to start a project like this. Perhaps someone else might be
interested? I'd enjoy to join a team doing it.


I agree that it shouldn't be difficult; The question is whether
someone will step up and do it.


Finally I'd like to stress, that the aims of PythonTurtle and Python's
turtle module are quite different - as one could grasp easily by trying
out the collection of examples at python-turtle-demo.googlecode.com that
I posted in another posting. Anyway they could very well complement one
another in some more mature state of development.

Best regards,
Gregor


Thank you for your feedback Gregor.

Ram Rachum.

--
http://mail.python.org/mailman/listinfo/python-list


Re: Overlap in python

2009-08-04 Thread Gregor Lingl

Jay Bird schrieb:

Hi everyone,

I've been trying to figure out a simple algorithm on how to combine a
list of parts that have 1D locations that overlap into a non-
overlapping list.  For example, here would be my input:

part name   location
a  5-9
b  7-10
c  3-6
d  15-20
e  18-23

And here is what I need for an output:
part name   location
c.a.b3-10
d.e   15-23



Suppose you have your data given as a dictionary:

data = {'a':(5,9),
'b':(7,10),
'c':(3,6),
'd':(15,20),
'e':(18,23)}

Then the following not particularly elegant
but very simple and straight forward
algorithm will solve your problem:

def values(key):
return set(range(data[key][0], data[key][1]+1))

keys = list(data.keys())
result = []
while keys:
k = [keys[0]]
keys = keys[1:]
v = values(k[0])
for l in keys[:]:
if v.intersection(values(l)):
v.update(values(l))
k.append(l)
keys.remove(l)
result.append((k,v))

# print(result) ## if you like

for k, v in result:
print(".".join(sorted(k)), "%d-%d" % (min(v), max(v)))

Regards,
Gregor



I've tried various methods, which all fail.  Does anyone have an idea
how to do this?

Thank you very much!
Jay

--
http://mail.python.org/mailman/listinfo/python-list


Re: Overlap in python

2009-08-04 Thread Gregor Lingl

DuaneKaufman schrieb:

On Aug 4, 1:15 pm, Jay Bird  wrote:

...

For instance the interval module found at: 
http://members.cox.net/apoco/interval/
can be put to use:

Given your data above:

part name   location
a  5-9
b  7-10
c  3-6


from interval import Interval

a_int=Interval(5,9)
b_int=Interval(7,10)
c_int=Interval(3,6)
a_int.overlaps(b_int)

True

a_int.overlaps(c_int)

True

b_int.overlaps(c_int)

False


As my proposed solution shows this approach can
be done with on board means of Python (namely
the set type). This would be quite different though,
if you had floating point boundaries of the intervals.

Regards,
Gregor



Duane

--
http://mail.python.org/mailman/listinfo/python-list


Re: Overlap in python

2009-08-04 Thread Gregor Lingl

Gregor Lingl schrieb:


As my proposed solution shows this approach can
be done with on board means of Python (namely
the set type). This would be quite different though,
if you had floating point boundaries of the intervals.


... or if the intgers involved were very big  :-(


Regards,
Gregor



Duane

--
http://mail.python.org/mailman/listinfo/python-list


Re: Turtle Graphics are incompatible with gmpy

2009-08-05 Thread Gregor Lingl

Mensanator schrieb:

I hadn't noticed this before, but the overhaul of Turtle Graphics
dating
back to 2.6 has been broken as far as gmpy is concerned.

I hadn't noticed because I usually have tracing turned off (tracing
off
takes 3-4 seconds, tracing on takes 6-7 minutes).

In 3.1, tracing is now a screen attribute, not a turtle atribute.
I have no idea why

  tooter = turtle.Turtle()
  tooter.tracer(False)

doesn't give me an error (I thought silent errors were a bad thing).



Hi,

on my machine I get:

Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit 
(Intel)] on win32

Type "copyright", "credits" or "license()" for more information.
>>> import turtle
>>> tooter = turtle.Turtle()
>>> tooter.tracer(False)
Traceback (most recent call last):
  File "", line 1, in 
tooter.tracer(False)
AttributeError: 'Turtle' object has no attribute 'tracer'
>>>

I'd like to help with your problem but I'd much better be
able to analyze it, if I had a version of your script,
which works as you intended with Python 2.5 and the old
turtle module. Could you please post it?

(The one you posted below uses some commands of the
turtle 2.6 module which are not present in 2.5, so it
doesn't run with Python 2.5)

Regards,
Gregor



Had to change to

  tooter = turtle.Turtle()
  tooter.screen.tracer(False) # tracer now a screen attribute

to turn tracing off in 3.1.

Naturally, having tracing on caused my program to crash. The 2.6
version
seemed to work, but only because turning off tracing as a turtle
attribute
works in 2.6.

So I turned it back on and it crashed too.

2.5 worked okay.

The reason is that code in turtle.py was chabged from

v2.5
if self._drawing:
if self._tracing:
dx = float(x1 - x0)
dy = float(y1 - y0)
distance = hypot(dx, dy)
nhops = int(distance)

to

v3.1
   if self._speed and screen._tracing == 1:
diff = (end-start)
diffsq = (diff[0]*screen.xscale)**2 + (diff[1]
*screen.yscale)**2
nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)
*self._speed))

Unfortunately, that calculation of nhops is illegal if diffsq is
an .mpf (gmpy
floating point). Otherwise, you get

Traceback (most recent call last):
  File "K:\user_python26\turtle\turtle_xy_Py3.py", line 95, in

tooter.goto(the_coord)
  File "C:\Python31\lib\turtle.py", line 1771, in goto
self._goto(Vec2D(*x))
  File "C:\Python31\lib\turtle.py", line 3165, in _goto
nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed))
ValueError: mpq.pow fractional exponent, inexact-root

So when using gmpy, you have to convert the .mpz to int before calling
turtle
functions. (if tracing is on).

demo code (fixed code commented out)

import gmpy

##   (even) hi|
##|
##lo (odd)
## or
##
##   (even) lo
##   |
##   |
##   hi (odd)
##
##
##
##

import turtle

tooter = turtle.Turtle()

tooter.hideturtle()
tooter.speed('fast')
turtle.update()
# make tracer false and it works
#tooter.screen.tracer(False) # tracer now a screen attribute
tooter.penup()
tooter.color('black')

s = ['1','0']
while len(s[0])<1:
s = [''.join(s), s[0]]


origin = [0,0]
if s[0] == '0':
  tooter.goto(origin)
  tooter.dot(1)
if s[1] == '0':
  tooter.goto([1,0])
  tooter.dot(1)

print(len(s[0]))

for i,j in enumerate(s[0]):
  the_coord=[]
  cur_root = gmpy.sqrt(i)
  lo__root = gmpy.sqrt(i)**2
  hi__root = ((gmpy.sqrt(i)+1)**2)
##  cur_root = int(gmpy.sqrt(i))
##  lo__root = int(gmpy.sqrt(i)**2)
##  hi__root = int(((gmpy.sqrt(i)+1)**2))

  if hi__root%2==0:
side = 'northeast'
  else:
side = 'southwest'

  elbow = (hi__root - lo__root)//2 + lo__root + 1

  if i>= elbow:

side_len = i - elbow
elbow_plus = True
  else:
side_len = elbow - i
elbow_plus = False

  if side == 'northeast':
elbow_offset = [(gmpy.sqrt(elbow)-1)//2 +1,-((gmpy.sqrt(elbow)-1)//
2) +1]
  else:
elbow_offset = [-((gmpy.sqrt(elbow)-1)//2 +1),((gmpy.sqrt
(elbow)-1)//2 +1)]
##  if side == 'northeast':
##elbow_offset = [int((gmpy.sqrt(elbow)-1)//2 +1),-int(((gmpy.sqrt
(elbow)-1)//2) +1)]
##  else:
##elbow_offset = [-int(((gmpy.sqrt(elbow)-1)//2 +1)),int
(((gmpy.sqrt(elbow)-1)//2 +1))]

  elbow_coord = [origin[0]+elbow_offset[0],origin[1]+elbow_offset[1]]

  if i != hi__root and i != lo__root:
if i == elbow:
  the_coord = elbow_coord
else:
  if elbow_plus:
if side == 'northeast':
  the_coord = [elbow_coord[0]-side_len,elbow_coord[1]]
else:
  the_coord = [elbow_coord[0]+side_len,elbow_coord[1]]
  else:
if side == 'northeast':
  the_coord = [elbow_coord[0],elbow_coord[1]+side_len]
else:
  the_coord = [elbow_coord[0],elbow_coord[1]-side_len]
  else:
if i % 2 == 0:  # even square
  n = gmpy.sqrt(i)//2 - 1
##  n = int(gmpy.sqrt(i)//2) - 1
  the_coord = [-n, -n-1]
else:
  n = (gmpy.s

Re: Turtle Graphics are incompatible with gmpy

2009-08-05 Thread Gregor Lingl

Steven D'Aprano schrieb:

On Wed, 5 Aug 2009 03:49 pm Mensanator wrote:


In 3.1, tracing is now a screen attribute, not a turtle atribute.
I have no idea why

  tooter = turtle.Turtle()
  tooter.tracer(False)

doesn't give me an error (I thought silent errors were a bad thing).


What makes it an error? Do you consider the following an error?


class Test:

... pass
...

t = Test()
t.tracer = 5



Perhaps you mean, it's an API change you didn't know about, and you wish to
protest that Turtle Graphics made an incompatible API change without
telling you?



It didn't form 2.5 to 2.6 (at least not intentionally). But with the 
indroduction of the TurtleScreen class and the Screen class/object 
(singleton) a few of the turtle methods were also implemented as screen 
methods and as turtle methods declared deprecated (see docs of Python 
2.6). These deprecated turtle methods do not occur as turtle methods any 
more in Python 3.x.


Among them is the tracer method, which in fact does not control single 
turtle objects but all the turtles on a given screen.


So there is an icompatibility beween 2.6 and 3.x

But as far as I have understood, this doesn't concern the problem 
reported by mensator.


Regards,
Gregor




Naturally, having tracing on caused my program to crash. 


It seg faulted or raised an exception?


[...] 

Unfortunately, that calculation of nhops is illegal if diffsq is
an .mpf (gmpy floating point). Otherwise, you get


How does diffsq get to be a mpf? Are gmpy floats supposed to be supported?




--
http://mail.python.org/mailman/listinfo/python-list


Re: Turtle Graphics are incompatible with gmpy

2009-08-05 Thread Gregor Lingl

Mensanator schrieb:

It didn't form 2.5 to 2.6 (at least not intentionally). But with the
indroduction of the TurtleScreen class and the Screen class/object
(singleton) a few of the turtle methods were also implemented as screen
methods and as turtle methods declared deprecated (see docs of Python
2.6). These deprecated turtle methods do not occur as turtle methods any
more in Python 3.x.


More info.

Yes, there is no tracer attribute...when the object is created.

But watch this (Python 3.1):


import turtle
tooter = turtle.Turtle()
tooter.tracer

Traceback (most recent call last):
  File "", line 1, in 
tooter.tracer
AttributeError: 'Turtle' object has no attribute 'tracer'

tooter.hideturtle()
tooter.speed('fast')
turtle.update()
turtle.tracer



Now, after setting hide, speed, update, a tracer exists.


No,

>>> import turtle
>>> turtle.tracer

>>> help(turtle.tracer)
Help on function tracer in module turtle:

tracer(n=None, delay=None)
Turns turtle animation on/off and set delay for update drawings.

Optional arguments:
n -- nonnegative  integer
delay -- nonnegative  integer

If n is given, only each n-th regular screen update is really 
performed.

(Can be used to accelerate the drawing of complex graphics.)
Second arguments sets delay value.)

Example:
>>> tracer(8, 25)
>>> dist = 2
>>> for i in range(200):
fd(dist)
rt(90)
dist += 2

>>>

The reason for this is, that the turtle module (the new one as well as 
the old one) has a vers special design: The methods of class Turtle are 
also available as functions (which are in fact methods calls of an 
anonymous turtle). The same holds for the methods of TurtleScreen.


The intention behind this design is that you can use the module in an 
OOP way as well as with procedural programming (especially for beginners).


When using objects I normally use

from turtle import Turtle, Screen
screen = Screen()
# that creates  singleton object, the screen the turtle acts on
and I create as many turtles as I need from the Turtle class

So turtle.tracer() doesn't make sense anymore



Is that supposed to happen? That explains why there was no error
when I set the turtle attribute instead of the screen attribute.


You do not 'set the turtle attribute', you call the tracer function of 
the turtle module



And, of course, setting the turtle attribute accomplishes nothing,
as actual tracing is controlled by the screen attribute as you say.


Among them is the tracer method, which in fact does not control single
turtle objects but all the turtles on a given screen.

So there is an icompatibility beween 2.6 and 3.x

But as far as I have understood, this doesn't concern the problem
reported by mensator.


Only that the problem is hidden when tracing is off, as the nhops
variable is never evaluated when trace is off.


Nevertheless I'd like to see a working Python 2.5 version of your script.

Regards,
Gregor
--
http://mail.python.org/mailman/listinfo/python-list


Re: Turtle Graphics are incompatible with gmpy

2009-08-05 Thread Gregor Lingl

Mensanator schrieb:

On Aug 5, 5:31 pm, Mensanator  wrote:

I fixed this to produce the actual image I'm looking
for instead of that stupid black square. All I did was
use up() & dowm() in place of penup(), pendown() and
replace dot(2) with forward(1).

I'll be posting a followup report later.



http://www.mensanator.com/mensanator/PythonTurtle/turtle.htm


Hi Mansanator,

Thanks for that thorough investigations.
I hope I'll soon find time to study it in detail.

I've just one idea, but I don't know if you might
be intersted in it or if it's rewarding at all:

What would be the results when using the old turtle
module with Python 3.1 (it will certainly not run
out of the box, but perhaps 2to3 might do it?)

That would clarify the question if there is some
impact of new division or some changes in Tkinter.

Best regards,
Gregor
--
http://mail.python.org/mailman/listinfo/python-list


Re: Splitting a string into substrings of equal size

2009-08-15 Thread Gregor Lingl



What is the pythonic way to do this ?


For my part, i reach to this rather complicated code:


# --

def comaSep(z,k=3, sep=','):
z=z[::-1]
x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1]
return sep.join(x)

# Test
for z in ["75096042068045", "509", "12024", "7", "2009"]:
print z+" --> ", comaSep(z)



Just if you are interested, a recursive solution:

>>> def comaSep(z,k=3,sep=","):
return comaSep(z[:-3],k,sep)+sep+z[-3:] if len(z)>3 else z

>>> comaSep("7")
'7'
>>> comaSep("2007")
'2,007'
>>> comaSep("12024")
'12,024'
>>> comaSep("509")
'509'
>>> comaSep("75096042068045")
'75,096,042,068,045'
>>>

Gregor
--
http://mail.python.org/mailman/listinfo/python-list


Re: Splitting a string into substrings of equal size

2009-08-15 Thread Gregor Lingl



What is the pythonic way to do this ?


For my part, i reach to this rather complicated code:


# --

def comaSep(z,k=3, sep=','):
z=z[::-1]
x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1]
return sep.join(x)

# Test
for z in ["75096042068045", "509", "12024", "7", "2009"]:
print z+" --> ", comaSep(z)



Just if you are interested, a recursive solution:

>>> def comaSep(z,k=3,sep=","):
return comaSep(z[:-3],k,sep)+sep+z[-3:] if len(z)>3 else z

>>> comaSep("7")
'7'
>>> comaSep("2007")
'2,007'
>>> comaSep("12024")
'12,024'
>>> comaSep("509")
'509'
>>> comaSep("75096042068045")
'75,096,042,068,045'
>>>

Gregor
--
http://mail.python.org/mailman/listinfo/python-list


Re: Splitting a string into substrings of equal size

2009-08-15 Thread Gregor Lingl

Emile van Sebille schrieb:

On 8/14/2009 5:22 PM candide said...

...

What is the pythonic way to do this ?


I like list comps...

 >>> jj = '1234567890123456789'
 >>> ",".join([jj[ii:ii+3] for ii in range(0,len(jj),3)])
'123,456,789,012,345,678,9'
 >>>

Emile



Less beautiful but more correct:

>>> ",".join([jj[max(ii-3,0):ii] for ii in
 range(len(jj)%3,len(jj)+3,3)])
'1,234,567,890,123,456,789'

Gregor
--
http://mail.python.org/mailman/listinfo/python-list


Re: getting the fractional part of a real?

2009-08-15 Thread Gregor Lingl

Christian Heimes schrieb:

Roy Smith schrieb:
What's the best way to get the fractional part of a real?  The two 
ways I can see are r % 1 and r = int(r), but both seem a bit hokey.  
Is there something more straight-forward that I'm missing, like 
fraction(r)?



import math
math.modf(1.5)

(0.5, 1.0)

Christian


Or without the need to import something:

>>> divmod(1.5, 1)
(1.0, 0.5)
>>>

Gregor
--
http://mail.python.org/mailman/listinfo/python-list


Re: Splitting a string into substrings of equal size

2009-08-16 Thread Gregor Lingl

Mark Tolonen schrieb:


"Gregor Lingl"  wrote in message 
news:4a87036a$0$2292$91cee...@newsreader02.highway.telekom.at...

Emile van Sebille schrieb:

On 8/14/2009 5:22 PM candide said...

...

What is the pythonic way to do this ?


I like list comps...

 >>> jj = '1234567890123456789'
 >>> ",".join([jj[ii:ii+3] for ii in range(0,len(jj),3)])
'123,456,789,012,345,678,9'
 >>>

Emile



Less beautiful but more correct:

>>> ",".join([jj[max(ii-3,0):ii] for ii in
 range(len(jj)%3,len(jj)+3,3)])
'1,234,567,890,123,456,789'

Gregor


Is it?


jj = '234567890123456789'
",".join([jj[max(ii-3,0):ii] for ii in range(len(jj)%3,len(jj)+3,3)])

',234,567,890,123,456,789'


Schluck!

Even more ugly:

 ",".join([jj[max(ii-3,0):ii] for ii in
   range(len(jj)%3,len(jj)+3,3)]).strip(",")
'234,567,890,123,456,789'

Gregor



At least one other solution in this thread had the same problem.

-Mark



--
http://mail.python.org/mailman/listinfo/python-list


Re: Splitting a string into substrings of equal size

2009-08-17 Thread Gregor Lingl

Simon Forman schrieb:

On Aug 14, 8:22 pm, candide  wrote:

Suppose you need to split a string into substrings of a given size (except
possibly the last substring). I make the hypothesis the first slice is at the
end of the string.
A typical example is provided by formatting a decimal string with thousands
separator.

What is the pythonic way to do this ?


...

Thanks


FWIW:

def chunks(s, length=3):
stop = len(s)
start = stop - length
while start > 0:
yield s[start:stop]
stop, start = start, start - length
yield s[:stop]


s = '1234567890'
print ','.join(reversed(list(chunks(s
# prints '1,234,567,890'


or:

>>> def chunks(s, length=3):
i, j = 0, len(s) % length or length
while i < len(s):
yield s[i:j]
i, j = j, j + length

>>> print(','.join(list(chunks(s
1,234,567,890
>>> print(','.join(list(chunks(s,2
12,34,56,78,90
>>> print(','.join(list(chunks(s,4
12,3456,7890

Regards,
Gregor
--
http://mail.python.org/mailman/listinfo/python-list