[Tutor] Could I have used time or datetime modules here?

2004-12-05 Thread Dick Moores
I'm wondering if my timer3.py could have been written more simply and 
easily by using the time or datetime modules to get the number of seconds 
separating the time now and the time to which the alarm is set.
IOW, is there an easier way to calculate the time difference between the 
time now, say 08:51 and say, tomorrow at 03:45, to take an example of the 
most difficult case?

See timer3.py at
<http://www.rcblue.com/Python/timer3_ForWeb.py>
Thanks, tutors.
Dick Moores
[EMAIL PROTECTED]
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Could I have used time or datetime modules here?

2004-12-05 Thread Dick Moores
Thanks, Brian. I looked at your code a long time, and also read the 11/26 
thread you started. I can see how I could use datetime() and your t2 - t1 
to get the seconds for time.sleep(), but  the resulting code I have in 
mind is more convoluted than the heart of my timer3.py, which I quote 
below.  (I don't need the alarm time to be more than 24 hours from 
current time--therefore I want to ignore the year, month, and day.)

===
import time
alarm = raw_input("Enter alarm time as hhmm: ")
now = time.strftime("%X")  # produces current time in format  hh:mm:ss
nowSecond = int(now[6:])
nowMinute = int(now[3:5])
nowHour = int(now[0:2])
alarmMinute = int(alarm[2:4])
alarmHour = int(alarm[0:2])
hoursDiff = alarmHour - nowHour
minutesDiff = alarmMinute - nowMinute
if hoursDiff < 0 or (hoursDiff == 0 and minutesDiff <= 0):
hoursDiff = hoursDiff + 24 # add a day
sleepSeconds = hoursDiff*3600 + minutesDiff*60 - nowSecond
time.sleep(sleepSeconds)

If I'm wrong, could someone please set me right?
Dick
Brian van den Broek wrote at 09:54 12/5/2004:
Dick Moores said unto the world upon 2004-12-05 11:17:
I'm wondering if my timer3.py could have been written more simply and 
easily by using the time or datetime modules to get the number of 
seconds separating the time now and the time to which the alarm is set.
IOW, is there an easier way to calculate the time difference between 
the time now, say 08:51 and say, tomorrow at 03:45, to take an example 
of the most difficult case?
See timer3.py at
<http://www.rcblue.com/Python/timer3_ForWeb.py>
Thanks, tutors.
Dick Moores
[EMAIL PROTECTED]
Hi Dick and all,
as you may recall, it was a week or so ago that I was show how to use 
datetime, so I'd be cautious about using my suggestion without testing :-)

But, does this do what is wanted?

import datetime
def dif_in_seconds(dif):
return dif.days * (24 * 60 * 60) + dif.seconds
t1 = datetime.datetime(2004, 12, 5, 8, 51, 00)
t2 = datetime.datetime(2004, 12, 6, 15, 45, 00)
dif = t2 - t1
seconds_dif = dif_in_seconds(dif)
print seconds_dif

with output
>>>
111240
I didn't check your link, or read your thread closely, so I don't know 
if this counts as "easier". But it does look pretty darned easy :-)

Best,
Brian vdB

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


Re: [Tutor] Could I have used time or datetime modules here?

2004-12-05 Thread Dick Moores
Brian van den Broek wrote at 16:53 12/5/2004:
Dick Moores said unto the world upon 2004-12-05 15:03:
Thanks, Brian. I looked at your code a long time, and also read the 
11/26 thread you started. I can see how I could use datetime() and your 
t2 - t1 to get the seconds for time.sleep(), but  the resulting code I 
have in mind is more convoluted than the heart of my timer3.py, which I 
quote below.  (I don't need the alarm time to be more than 24 hours 
from current time--therefore I want to ignore the year, month, and day.)
===
import time
alarm = raw_input("Enter alarm time as hhmm: ")
now = time.strftime("%X")  # produces current time in format  hh:mm:ss
nowSecond = int(now[6:])
nowMinute = int(now[3:5])
nowHour = int(now[0:2])
alarmMinute = int(alarm[2:4])
alarmHour = int(alarm[0:2])
hoursDiff = alarmHour - nowHour
minutesDiff = alarmMinute - nowMinute
if hoursDiff < 0 or (hoursDiff == 0 and minutesDiff <= 0):
hoursDiff = hoursDiff + 24 # add a day
sleepSeconds = hoursDiff*3600 + minutesDiff*60 - nowSecond
time.sleep(sleepSeconds)

If I'm wrong, could someone please set me right?
Dick
Hi Dick and all,
sorry I was too lazy to follow your link before, Dick. Thanks for 
posting the relevant portions.

I took another run, but my code is a lot longer as I put in some error 
checking on the input request -- hope you don't mind ;-) (I might have 
gone overboard -- I did it to learn how as much as anything else.)

I suspect that my way is easier than yours. (I don't know about Liam's. 
His came in as I was writing mine, and I've not read his closely yet.)

In mine, the key bit is that if you have two datetime objects, d1 and 
d2, d1 - d2 gives a timedelta object expressing the time difference 
between them in the form (days, seconds, microseconds). So, the datetime 
module seems to do the work you want -- just make the current time a 
datetime object, use the user input to get a datetime object in the 
future and then find their timedelta and ask it for its seconds 
attribute. This disregards any difference in days and gives only the 
hour + minute + seconds difference expressed in seconds.

That logic is near the bottom, though, as first you've got to read 
through my error checking code ;-)

I tested it pretty well, but as always, undetected errors entitle you to 
a full refund of purchase price. (Minus a reasonable handling fee, of 
course.)

I hope this is of some use to you.
Best to all,
Brian vdB
CODE:
import datetime
import time
def get_alarm_time():
'''Asks user for a time in the form 'hh:mm' and return tuple of ints.
Includes error checking to make sure user input really is of form
'hh:mm' where the values of 'hh' and 'mm' are appropriate.
'''
while True:
alarm_time = raw_input("Enter alarm time as hh:mm")
er_msg = '''
An alarm time must be entered in the format 'hh:mm' where 'hh'
is a number between 0 and 23 inclusive and mm is a number
between 0 and 59 inclusive.
You entered: '%s', which is not of that form.
Please try again.
''' %alarm_time
alarm_time_list = alarm_time.split(':')
# yields a list with first element the characters from before
# the ':' and second from after.
try:
alarm_hour, alarm_minute = (int(alarm_time_list[0]),
int(alarm_time_list[1]) )
except ValueError:
# raised if the user entered something like "silly:input"
print er_msg
continue
if len(str(alarm_minute)) == 1:
alarm_minute_string = '0' + str(alarm_minute)
# if the user entered, say, 12:05, str(alarm_minute) would
# give '5' rather than the needed '05'.
else:
alarm_minute_string = str(alarm_minute)
if ( (alarm_hour > 24 or alarm_hour < 0)
 or (alarm_minute > 59 or alarm_minute < 0)
 or str(alarm_hour) + ':' + alarm_minute_string != alarm_time):
# The first two clauses check that minutes and hours are
# within the expected ranges. The final clause checks that
# the inputs were string representations of integers.
# (Without it, the user could have entered something like
# 16.845:57.343.)
print er_msg
else:
return alarm_hour, alarm_minute
alarm_hour, alarm_minute = get_alarm_time()
now = datetime.datetime.now()
alarm_datetime = datetime.datetime(now.year + 4, now.month, now.day,
   alarm_hour, alarm_minute)
# now.year + 4 to ensure that the alarm_d

[Tutor] psyco 1.3 is out, with support for Python 2.4

2004-12-06 Thread Dick Moores
<http://psyco.sourceforge.net/>
And "The Ultimate Psyco Guide" for 1.3 is at
<http://psyco.sourceforge.net/psycoguide/index.html>
Dick Moores
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] psyco 1.3 is out, with support for Python 2.4

2004-12-06 Thread Dick Moores
Liam,
Kent Johnson was of great help in getting me started with psyco.
psyco's easy to implement, it seems, and can make an enormous difference 
in speed. The best example I've seen is my simple 
<http://www.rcblue.com/Python/spinForWeb.py>, where psyco speeds up the 
tiny while loop of spin(),

while k < max:
k += 1
by 2 orders of magnitude. (But keep max <= 2**31-1).
In mine and Kent's 
<http://www.rcblue.com/Python/factorIntegers-forWeb-WithPsyco8.py> psyco 
also makes an important, but much lesser, difference to the speed of the 
workhorse function, factorsOfInteger(n). Here's an example: for
"4139252 4139300", my time using psyco is 22 seconds; 
without psyco, 34 seconds.

Here's what I learned from Kent about installing psyco (for Windows):
Download psyco from http://psyco.sourceforge.net. Unzip the zip file. 
Copy the folder psyco-1.3/psyco into Python24/Lib/site-packages. (Create 
site-packages if you don't already have it.) Should be good to go then.

Dick
Liam Clarke wrote at 02:18 12/6/2004:
Have you used Pysco much Dick? Is it n00bie friendly?
Or, to put it another way, at what point in a programme's size/speed
does it become worthwhile to implement Pysco?
Regards,
Liam Clarke
On Sun, 05 Dec 2004 23:49:03 -0800, Dick Moores <[EMAIL PROTECTED]> wrote:
> <http://psyco.sourceforge.net/>
>
> And "The Ultimate Psyco Guide" for 1.3 is at
> <http://psyco.sourceforge.net/psycoguide/index.html>
>
> Dick Moores

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


[Tutor] Python 2.3.5 out in January??

2004-12-07 Thread Dick Moores
Just saw this on comp.lang.python.announce.
<http://tinyurl.com/5egud>
I don't understand this. Why is a new version of 2.3 being worked on 
after 2.4 has been released?

I see Tim Peters has said this on python-list:
===begin Tim Peters' post===
[Brett C]
>> Anthony Baxter, our ever-diligent release manager, mentioned this 
past week
>> that Python 2.3.5 will most likely come to fruition some time in January
>> (this is not guaranteed date).

[Roy Smith]
> Interesting.  Does that mean that 2.3 and 2.4 will be maintained in
> parallel for a while?  That would be awesome.
They'll be maintained in parallel through 2.3.5 in January, which is
all Brett said.  If history is a guide, after 2.3.5 nobody will
volunteer to work on a 2.3.6, and 2.3.5 will be the last release in
the 2.3 line.  It's *possible* that volunteers for 2.3.6 will appear.
That would be unprecedented, but not impossible ...
end TP's post
I ask here because I'm sure it's a newbie question. It's got me wondering 
if Microsoft is still working on Windows 3.1..  ;-)

Thanks,
Dick Moores
[EMAIL PROTECTED] 

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


Re: [Tutor] Re: Could I have used time or datetime modules here?

2004-12-07 Thread Dick Moores
To Liam and Brian,
Liam, actually, Brian did Sunday. See his post in this thread of Date: 
Sun, 05 Dec 2004 19:53:01 -0500. But you've done is interesting, and I 
thank you.

Here's Brian's script in it's bare bones, without the input error 
checking and his extensive and helpful comments:

===begin code
import datetime
import time
alarm_time = raw_input("Enter alarm time as hh:mm ")
alarm_time_list = alarm_time.split(':')
alarm_hour, alarm_minute = (int(alarm_time_list[0]),
int(alarm_time_list[1])) 

now = datetime.datetime.now()
alarm_datetime = datetime.datetime(now.year+4, now.month, now.day,
   alarm_hour, alarm_minute)
print alarm_datetime
alarm_in_seconds = (alarm_datetime - now).seconds
print "I should wake up in %d seconds" % alarm_in_seconds
time.sleep(alarm_in_seconds)
print "I'm awake!"
end code=
You can see that he gets the number-of-seconds difference directly with 
the line,

"alarm_in_seconds = (alarm_datetime - now).seconds",
and doesn't need to compute the seconds to sleep from the difference 
expressed as hours, minutes and seconds.

I like your alarm clock a lot, 
. I first tried to run 
it with IDLE, then remembered that mscvrt won't catch keypresses if run 
with IDLE. Works fine in the console!

Instead of your beeps in the second while loop, I think I'd need
winsound.PlaySound('SystemAsterisk', winsound.SND_ALIAS)
winsound.PlaySound('SystemHand', winsound.SND_ALIAS)
and turn my speakers way up!
Brian, where did you learn about the ".seconds". And the .year, .month, 
.day of

"alarm_datetime = datetime.datetime(now.year + 4, now.month, now.day,
   alarm_hour, alarm_minute)"?
Does this come from a general knowledge of OOP, or is it somewhere in the 
Python docs? The only thing I've seen, and it's not an explanation, is in 
note (1) on http://docs.python.org/lib/datetime-date.html

It seems I've missed out on something important
BTW I'm not sure you need the +4 of "now.year + 4". I've run this without 
the +4 and it doesn't seem to be needed. And notes (1) and (4) on that 
page seem to say this, as far as I understand them.

Dick
Liam Clarke wrote at 03:56 12/6/2004:
Hey Dick, don't know if anyone actually answered your original question.
>IOW, is there an easier way to calculate the time difference between the
>time now, say 08:51 and say, tomorrow at 03:45, to take an example of the
>most difficult case?
So, you need two datetime.datetime objects.
>>>now = datetime.datetime(year, month, day, hours, minutes, seconds)
>>>now = datetime.datetime(2004, 12, 7*, 8*, 51, 00)
>>> later= datetime.datetime(2004, 12, 8*, 3*, 45, 00)
 *Can't start with zero. Must be 8 not 08
>>> difference = later - now
>>> print difference
18:54:00
>>> type(difference)

>>> timeList=str(difference).split(":")
>>> print timeList
['18', '54', '00']
>>> 
timeinSecs=(int(timeList[0])*3600)+(int(timeList[1])*60)+int(timeList[2])
>>> print timeinSecs
68040

Now, to check if that's right...
>>> timeChange=datetime.timedelta(seconds=68040)
>>> checkVal=now + timeChange
>>> print checkVal
2004-12-08 03:45:00
Looks good to me.
So, to summarise the code part -
now = datetime.datetime(2004, 12, 7, 8, 51, 00)
later= datetime.datetime(2004, 12, 8, 3, 45, 00)
difference = later - now
timeList=str(difference).split(":")
timeinSecs=(int(timeList[0])*3600)+(int(timeList[1])*60)+int(timeList[2])
And that's the easier way to find the difference between two times in 
seconds.

HTH
Liam Clarke
P.S. If you're interested, here's a 20 line alarm clock I wrote
because my one broke this morning.
http://www.rafb.net/paste/results/ctOH1T36.html

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


Re: [Tutor] Re: Could I have used time or datetime modules here?

2004-12-07 Thread Dick Moores
Brian van den Broek wrote at 07:50 12/7/2004:
Dick Moores said unto the world upon 2004-12-07 07:04:
To Liam and Brian,

Here's Brian's script in it's bare bones, without the input error 
checking and his extensive and helpful comments:
===begin code
import datetime
import time
alarm_time = raw_input("Enter alarm time as hh:mm ")
alarm_time_list = alarm_time.split(':')
alarm_hour, alarm_minute = (int(alarm_time_list[0]),
int(alarm_time_list[1]))
now = datetime.datetime.now()
alarm_datetime = datetime.datetime(now.year+4, now.month, now.day,
   alarm_hour, alarm_minute)
print alarm_datetime
alarm_in_seconds = (alarm_datetime - now).seconds
print "I should wake up in %d seconds" % alarm_in_seconds
time.sleep(alarm_in_seconds)
print "I'm awake!"
end code=

Brian, where did you learn about the ".seconds". And the .year, .month, 
.day of
"alarm_datetime = datetime.datetime(now.year + 4, now.month, now.day,
   alarm_hour, alarm_minute)"?
Does this come from a general knowledge of OOP, or is it somewhere in 
the Python docs? The only thing I've seen, and it's not an explanation, 
is in note (1) on http://docs.python.org/lib/datetime-date.html
Oh Sir, you flatter me! My general knowledge of OOP is about the same as 
my general knowledge of the migration patterns of Siberian water-fowl. ;-)

After Anna, Gonçalo, and Liam encouraged me to explore the datetime 
module, I read (OK, skimmed) the docs. For my original purpose, I just 
needed to test two times with '>', but I recalled something about 
timedelta objects being returned by subtracting one datetime from 
another. I hadn't used them before I wrote my script in reply to you. I 
learned about the handy for your purposes .seconds attribute in the 
Library Reference -- 6.10.2 timedelta Objects. (That's the section name 
in the 2.4 installed docs; I'm typing off line so can't [OK, won't] get 
a link.)

It seems I've missed out on something important
BTW I'm not sure you need the +4 of "now.year + 4". I've run this 
without the +4 and it doesn't seem to be needed. And notes (1) and (4) 
on that page seem to say this, as far as I understand them.
I'm not sure I do either :-)
Here's why I did it:
I discovered that in order to get the right "seconds until alarm" value 
from the datetime for now and the alarm datetime by subtracting one 
datetime object from another, I needed the alarm datetime to be in the 
future. But, since you can set an alarm for 09:00 tomorrow at 22:00 
today, I needed the alarm datetime to not use today's date. (If you use 
today's, you end up with seconds *since* 09:00 this morning, not the 
desired seconds *until* 09:00 tomorrow morning.) Since 
timedelta_object.seconds discards all difference save the seconds save 
those from the hours, minutes, and seconds difference in the two 
datetime objects, it doesn't matter what date the alarm datetime is set 
to. (The day information is in timedelta_object.days.)

Or, so I thought. I'd first tried getting the alarm datetime by simply 
taking the date component of datetime.datetime.now() and adding to the 
day value. That works fine, provided you are not on the last day of the 
month. But, when checking boundary cases before posting the code I sent, 
I discovered this sort of thing:

>>> last_day_of_june = datetime.datetime(2004, 6, 30) # long for clarity
>>> ldj = last_day_of_june# short for typing
>>> new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1)
Traceback (most recent call last):
  File "", line 1, in -toplevel-
new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1)
ValueError: day is out of range for month
>>>
So, adding to the day or the month was out, unless I wanted elaborate 
code to determine which to add to under what circumstances. So then I 
thought, "Well, just change from now.day + 1 to now.year + 1, and all 
problems go away". And then I thought "Ah, but what if I try to run the 
script on Feb. 29?

So, that's why I used now.year + 4. It still leaves open the possibility 
of getting bit by the every so often further correction to the calender, 
but, I *believe* the next one is due in 2100, so I think I can live with 
it. ;-)

I'm not saying it isn't hackish, though. Better ways surely exist.
Brian,
I just can't succeed in reproducing the problems with the boundary 
cases  with the +4 removed. I've tried setting my computer's clock to Nov 
30, Feb 29, 2004, and Dec 31, 2004 (without changing the time). It's now 
about 9 am where I am, and setting the alarm time to 0700 (i.e., on the 
n

[Tutor] "TypeError: 'int' object is not callable"??

2004-12-08 Thread Dick Moores
I got this error msg for this line of code:
n = -(2(a**3.0)/27.0 - a*b/3.0 + c)
(where a = 1, b = 2, c = 3)
And was baffled until I realized the line should be
n = -(2*(a**3.0)/27.0 - a*b/3.0 + c)
But I still don't understand what "callable" means. Can someone help?
Thanks,
Dick Moores
[EMAIL PROTECTED]
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "TypeError: 'int' object is not callable"??

2004-12-08 Thread Dick Moores
My thanks to both Max and Kent. So Python tries, and fails, to see 2() as 
a function!

I also got some help from 
Dick  

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


[Tutor] How to get the 2 complex cube roots of 1?

2004-12-09 Thread Dick Moores
My trusty $10 Casio calculator tells me that the 3 cube roots of 1 are:
1, (-.5 +0.866025403j), and (-.5 -0.866025403j), or thereabouts. Is there 
a way to do this in Python?

Checking the Casio results with Python:
>>> 1**3
1
>>> (-.5 + .866025403j)**3
(0.796196859+1.1766579932626087e-009j)
>>> (-.5 - .866025403j)**3
(0.796196859-1.1766579932626087e-009j)
Thanks,
Dick Moores
[EMAIL PROTECTED]
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Complex roots

2004-12-09 Thread Dick Moores
VERY helpful, Matt. Thanks.

One question: This seems to not compute accurately at all when the
imaginary part of number=complex() is other than 0. For example,
number=complex(5,5):

With 
number=complex(5,5)
n=float(4)

the code produces
{0: (1.631, 0.0), 1: (0.0, 1.631), 2: (-1.631, 0.0), 3: (0.0, -1.631)}

And testing:
>>> (0.0 + 1.631j)**4
(7.0764565459210003+0j)

If that's the case, why the line
size=math.sqrt((number.real**2)+(number.imag**2)) ?

Dick


On Thu, 09 Dec 2004 11:52:15 +, Matt Williams
<[EMAIL PROTECTED]> wrote:
> Further to my previous post, please find some code below:
> 
> Hope this helps,
> Matt
> 
> #Complex number Roots
> #Matt Williams 9.12.04
> 
> import math
> 
> number=complex(0.5,0)
> n=float(3)
> 
> size=math.sqrt((number.real**2)+(number.imag**2))
> 
> arg=math.radians(360/n)
> 
> root=1/n
> 
> modulus=size**root
> 
> theta=float(0)
> roots={}
> i=0
> while i y=round(modulus*(math.sin(theta)),3)
> x=round(modulus*(math.cos(theta)),3)
> roots[i]=(x,y)
> theta=theta+arg
> i=i+1
> 
> print roots
>
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Complex roots

2004-12-10 Thread Dick Moores
Aw, that's just amazing.
I put your function in http://www.rcblue.com/Python/croots.py, which gets 
c and n from user and adds a test function.

Here's what one run produces:

Enter either a complex number in form x + yj, or a real number: 3.1 -1j
Enter an integer n, to find the n'th roots: 5
c is (3.1-1j); n is 5
root1 is (1.26393645827-0.0789828505298j)
root1 to the 5 power is (3.1-1j)
root2 is (0.46569588+1.17766796174j)
root2 to the 5 power is (3.1-1j)
root3 is (-0.976121119826+0.806821678349j)
root3 to the 5 power is (3.1-1j)
root4 is (-1.06897102928-0.679024741664j)
root4 to the 5 power is (3.1-1j)
root5 is (0.315460690744-1.2264820479j)
root5 to the 5 power is (3.1-1j)
==
Actually, I'm trying to write a Python script that computes all 3 roots 
of a cubic equation. Do you happen to have one tucked away in your store 
of wisdom and tricks? (One for real coefficients will do).

Anyway, thought it wouldn't hurt to ask..
Dick
Tim Peters wrote at 07:41 12/9/2004:
Try this instead:
def croots(c, n):
"""Return list of the n n'th roots of complex c."""
from math import sin, cos, atan2, pi
arg = abs(c)**(1.0/n)
theta = atan2(c.imag, c.real)
result = []
for i in range(n):
theta2 = (theta + 2*pi*i)/n
x = arg * cos(theta2)
y = arg * sin(theta2)
result.append(complex(x, y))
return result
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Complex roots

2004-12-10 Thread Dick Moores
Oops. Make that croots3.py (<http://www.rcblue.com/Python/croots3.py>).
I forgot a couple of abs's. For example,
"if n.imag < 1e-13:"
is changed to
"if abs(n.imag) < 1e-13:"
Dick
Dick Moores wrote at 07:38 12/10/2004:
I've modified croots.py to croots2.py 
(<http://www.rcblue.com/Python/croots2.py>)

The only changes are in the testCrootsResult function. It will ignore 
very small .imag or .real when printing.

Thus this result:

Enter either a complex number in form x + yj, or a real number: 4
Enter an integer n, to find the n'th roots of that number: 3
c is (4+0j); n is 3
root1 is 1.58740105197, adjusted from (1.58740105197+0j)
root1 to the 3 power is 4.0, adjusted from (4+0j)
root2 is (-0.793700525984+1.374729637j)
root2 to the 3 power is 4.0, adjusted from (4-2.6645352591e-015j)
root3 is (-0.793700525984-1.374729637j)
root3 to the 3 power is 4.0, adjusted from (4-5.55111512313e-015j)

Dick
Dick Moores wrote at 02:15 12/10/2004:
Aw, that's just amazing.
I put your function in http://www.rcblue.com/Python/croots.py, which 
gets c and n from user and adds a test function.

Here's what one run produces:

Enter either a complex number in form x + yj, or a real number: 3.1 -1j
Enter an integer n, to find the n'th roots: 5
c is (3.1-1j); n is 5
root1 is (1.26393645827-0.0789828505298j)
root1 to the 5 power is (3.1-1j)
root2 is (0.46569588+1.17766796174j)
root2 to the 5 power is (3.1-1j)
root3 is (-0.976121119826+0.806821678349j)
root3 to the 5 power is (3.1-1j)
root4 is (-1.06897102928-0.679024741664j)
root4 to the 5 power is (3.1-1j)
root5 is (0.315460690744-1.2264820479j)
root5 to the 5 power is (3.1-1j)
==
Actually, I'm trying to write a Python script that computes all 3 roots 
of a cubic equation. Do you happen to have one tucked away in your 
store of wisdom and tricks? (One for real coefficients will do).

Anyway, thought it wouldn't hurt to ask..
Dick
Tim Peters wrote at 07:41 12/9/2004:
Try this instead:
def croots(c, n):
"""Return list of the n n'th roots of complex c."""
from math import sin, cos, atan2, pi
arg = abs(c)**(1.0/n)
theta = atan2(c.imag, c.real)
result = []
for i in range(n):
theta2 = (theta + 2*pi*i)/n
x = arg * cos(theta2)
y = arg * sin(theta2)
result.append(complex(x, y))
return result

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


Re: [Tutor] Complex roots

2004-12-12 Thread Dick Moores
Tim (was: Bill) Peters wrote at 20:45 12/10/2004:
[Dick Moores]
> Aw, that's just amazing.


> I put your function in http://www.rcblue.com/Python/croots.py,
That's fine by me -- but I'd appreciate it if you stopped claiming
there that my name is Bill .
Are you sure? Well, OK. Tim it is.
> Actually, I'm trying to write a Python script that computes all 3
> roots of a cubic equation. Do you happen to have one tucked
> away in your store of wisdom and tricks? (One for real coefficients
> will do).
I don't, no.  You can code one for cubics from Cardano's formula, e.g.,
http://mathworld.wolfram.com/CubicFormula.html
but it's rarely worth the bother -- it's complicated and doesn't
generalize.
I accept this challenge to write a complicated script of little value.
In practice, roots for polynomials beyond quadratics are
usually obtained by numerical approximation methods that don't care
much about the polynomial's degree.
Are these "numerical approximation methods" pythonically possible?
Dick (AKA George) Moores
[EMAIL PROTECTED]
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] OT?: how to google just the 2.4 tutorial?

2004-12-12 Thread Dick Moores
I know how to limit google search results to a single site, but is it 
possible to google just one section of a site?

I'd like to be able to search just the 2.4 tutorial, 
http://www.python.org/doc/2.4/tut/tut.html
Possible? And if so, how to?

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


Re: [Tutor] OT?: how to google just the 2.4 tutorial?

2004-12-12 Thread Dick Moores
Brian van den Broek wrote at 10:43 12/12/2004:
Dick Moores said unto the world upon 2004-12-12 11:53:
I know how to limit google search results to a single site, but is it 
possible to google just one section of a site?
I'd like to be able to search just the 2.4 tutorial, 
http://www.python.org/doc/2.4/tut/tut.html
Possible? And if so, how to?
Thanks,
Dick Moores
[EMAIL PROTECTED]
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
Hey Dick and all,
that's odd. I tried searching with
  site:www.python.org/doc/
and
  site:www.python.org/doc
but neither gave hits. :-(
From the "Department of there has to be a better way, but . . . ",
try entering something like this into the google search box:
  site:www.python.org inurl:tut string
That will search www.python.org pages with 'tut' in the url that have 
'string' in the page body. That doesn't restrict it to 2.4, or non-dev docs.

My best attempt:
  site:www.python.org inurl:tut -inurl:dev inurl:current string
still pulls up hits like  
which don't have 'current' in the url. And, adding inurl:node to the 
suggested search yields no results, either. I'm not sure why. :-|

So, none of this gets you there, but it does get you closer.
<http://www.google.com/help/operators.html> shows how to use some of the 
more esoteric google operators.

You might also check out (and maybe improve) 
<http://www.python.org/cgi-bin/moinmoin/GoogleTips>.
Thanks, Brian.
I stumbled across http://docs.python.org as a site, so at least searching 
within Python docs (which include the tutorial) is possible.

For example,
site:http://docs.python.org "complex number"
This finds 23 results, compared to the 334 returned by
site:http://www.python.org "complex number"
To find the results for the tutorial, search the results page for
site:http://docs.python.org "complex number" and search the page on 
"/tut/". These will be for the tutorial. There are just 2 for "complex 
number"

A much simpler way to find things in the tutorial (after all) seems to be 
to use the "Python Documentation" help file that comes with 2.4. I 
searched on
"complex number" tutorial  and got 3 hits, the 2 found with the method of 
the paragraph immediately above, plus one more in the index of the tutorial.

Dick



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


Re: [Tutor] Complex roots

2004-12-12 Thread Dick Moores
Thanks for the sobering advice, and for the two sites I knew nothing 
about. So there's a SciPy!

Dick
Tim Peters wrote at 20:37 12/12/2004:
> Are these "numerical approximation methods" pythonically possible?
Of course, but coding general-purpose root finders-- even if "general"
is limited to just polynomials --requires mathematical and numeric
expertise.  If it interests you, there are book-length treatments of
the subject, and there's really no easy reliable approach.  Good
online sources for numeric algorithms include:
http://www.netlib.org/
Just Googling on
polynomial roots Python
will point you to
http://www.scipy.org/
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Complex roots

2004-12-12 Thread Dick Moores
Hmm, sounds like something to sink my teeth into for a while. Thanks for 
just enough of a hint as to how to go about it.

But on second thought, how about another hint. How are imaginary roots 
approximated? For each root, do you try to approximate root.real and 
root.imag simultaneously, or what? Sounds mind-boggling. Maybe I should 
start by approximating real roots, if they exist; and cut my teeth on 
quadratic equations where b**2 - 4*a*c >= 0! Or linear equations.

Thank you.
Dick Moores
Alan Gauld wrote at 09:25 12/12/2004:
> Are these "numerical approximation methods" pythonically possible?
>
Yes and that's how they are normally found - not necessarily with
Python,
but by applying computer simulations of the equations. Generally you
calculate values in ever decreasing increments until you get enough
accuracy. eg you discover a zero crossingh between 3 and 4, then
between 3.3 and 3.4 then between 3.36 and 3.37 and so on...
Caveat:
You also need to look out for double crossings within a single step
change, so don't make the steps too big. And check the number of
roots you expect versus the number you get as an error detection
scheme.
Alan G.

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


Re: [Tutor] OT?: how to google just the 2.4 tutorial?

2004-12-15 Thread Dick Moores
Just got this reply from [EMAIL PROTECTED]   --Dick
Regrettably, we don't currently offer a way to limit your search to a
specific section of a site. We really appreciate your thoughtful feedback,
and we'll keep it in mind as we work to improve Google.
Regards,
The Google Team
Dick Moores wrote at 08:53 12/12/2004:
I know how to limit google search results to a single site, but is it 
possible to google just one section of a site?

I'd like to be able to search just the 2.4 tutorial, 
http://www.python.org/doc/2.4/tut/tut.html
Possible? And if so, how to?

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


Re: [Tutor] Complex roots

2004-12-16 Thread Dick Moores
Thanks. Tim Peters helped me out with his answer of 12/9. 
<http://mail.python.org/pipermail/tutor/2004-December/033967.html>

Dick Moores
Jacob S. wrote at 19:27 12/15/2004:
Finding the all the roots of a complex number shouldn't be too difficult. I
tend to do it on paper sometimes. Maybe I can write a script to do it for me
instead.  I stongly caution you though. The methods that I show below are
unstable and should be verified by a math web site as it has been quite a
few months since I last used the equations. In fact, I'll almost bet they're
wrong. If you want me to check them, I'll gladly google for the right
equations if you want.
where i == sqrt(-1)
[pseudo-code]
p = (a+bi)**n
n = polar(p)  ## polar is a function that converts rectangular coordinates
to polar coordinates.
radius = n[0]
angle = n[1]
1st rootradius**n cis (angle/(180*n))  ## Where cis is short for
(cos(angle) + i*sin(angle))
2nd rootradius**n cis (angle/(360*n))
...
qth rootradius**n cis (angle/(180*q*n))
[/pseudo-code]
So saying, I would set a for i in range loop for n times to run these root
finders through. Note unless you call some sort of polar to rectangular
function on the roots, they will still be in polar.
HTH as always,
Jacob Schmidt
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Complex roots

2004-12-10 Thread Dick Moores
I've modified croots.py to croots2.py 
(<http://www.rcblue.com/Python/croots2.py>)

The only changes are in the testCrootsResult function. It will ignore 
very small .imag or .real when printing.

Thus this result:

Enter either a complex number in form x + yj, or a real number: 4
Enter an integer n, to find the n'th roots of that number: 3
c is (4+0j); n is 3
root1 is 1.58740105197, adjusted from (1.58740105197+0j)
root1 to the 3 power is 4.0, adjusted from (4+0j)
root2 is (-0.793700525984+1.374729637j)
root2 to the 3 power is 4.0, adjusted from (4-2.6645352591e-015j)
root3 is (-0.793700525984-1.374729637j)
root3 to the 3 power is 4.0, adjusted from (4-5.55111512313e-015j)
====
Dick
Dick Moores wrote at 02:15 12/10/2004:
Aw, that's just amazing.
I put your function in http://www.rcblue.com/Python/croots.py, which 
gets c and n from user and adds a test function.

Here's what one run produces:

Enter either a complex number in form x + yj, or a real number: 3.1 -1j
Enter an integer n, to find the n'th roots: 5
c is (3.1-1j); n is 5
root1 is (1.26393645827-0.0789828505298j)
root1 to the 5 power is (3.1-1j)
root2 is (0.46569588+1.17766796174j)
root2 to the 5 power is (3.1-1j)
root3 is (-0.976121119826+0.806821678349j)
root3 to the 5 power is (3.1-1j)
root4 is (-1.06897102928-0.679024741664j)
root4 to the 5 power is (3.1-1j)
root5 is (0.315460690744-1.2264820479j)
root5 to the 5 power is (3.1-1j)
==
Actually, I'm trying to write a Python script that computes all 3 roots 
of a cubic equation. Do you happen to have one tucked away in your store 
of wisdom and tricks? (One for real coefficients will do).

Anyway, thought it wouldn't hurt to ask..
Dick
Tim Peters wrote at 07:41 12/9/2004:
Try this instead:
def croots(c, n):
"""Return list of the n n'th roots of complex c."""
from math import sin, cos, atan2, pi
arg = abs(c)**(1.0/n)
theta = atan2(c.imag, c.real)
result = []
for i in range(n):
theta2 = (theta + 2*pi*i)/n
x = arg * cos(theta2)
y = arg * sin(theta2)
result.append(complex(x, y))
return result

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


Re: [Tutor] Complex roots

2004-12-15 Thread Dick Moores
Alan Gauld wrote at 09:25 12/12/2004:
> Are these "numerical approximation methods" pythonically possible?
>
Yes and that's how they are normally found - not necessarily with
Python,
but by applying computer simulations of the equations. Generally you
calculate values in ever decreasing increments until you get enough
accuracy. eg you discover a zero crossingh between 3 and 4, then
between 3.3 and 3.4 then between 3.36 and 3.37 and so on...
Caveat:
You also need to look out for double crossings within a single step
change, so don't make the steps too big. And check the number of
roots you expect versus the number you get as an error detection
scheme.
I tried to follow your tips, and came up with pinchCubic.py for 
approximating the real roots of cubic equations.
<http://www.rcblue.com/Python/pinchCubic.py>

I'd appreciate any guidance.
Dick Moores
[EMAIL PROTECTED]
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to use Python 2.6 with IDLE?

2009-07-27 Thread Dick Moores
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.

Thanks,

Dick Moores
___
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 Dick Moores
On Mon, Jul 27, 2009 at 04:27, Gregor Lingl wrote:
> 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

Yes! After I did that, now when I call
E:\Python26\Lib\idlelib\idle.pyw the IDLE that opens uses 2.62.

But I also want to use Ulipad, actually my main Python editor. When I
call E:\Programs\Ulipad3.7\UliPad.pyw (by clicking on it in Explorer),
Ulipad no longer opens. Before I made the change you suggested, at
least Ulipad would open using 2.51. What can I do to use both IDLE and
Ulipad with 2.62?

Dick
___
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 Dick Moores
On Mon, Jul 27, 2009 at 09:32, Alan Gauld wrote:
>
> "Dick Moores"  wrote
>
>>> I suggest you have to change the association of *.pyw files to the
>>> program, which is used to 'open' it.
>>>
>> Yes! After I did that, now when I call
>> E:\Python26\Lib\idlelib\idle.pyw the IDLE that opens uses 2.62.
>>
>> But I also want to use Ulipad, actually my main Python editor. When I
>> call E:\Programs\Ulipad3.7\UliPad.pyw (by clicking on it in Explorer),
>> Ulipad no longer opens. Before I made the change you suggested, at
>> least Ulipad would open using 2.51. What can I do to use both IDLE and
>> Ulipad with 2.62?
>
> What I do for these things is create a shortcut which specifies the full
> path to the interpreter and to the pyw file. I also set the working foldeer
> to wherever is most appropriate - usually my project folder. That's fairly
> bulletproof in my experience!

Alan, here's what have now to call Ulipad: the shortcut shown at
<http://www.rcblue.com/Misc/Ulipad_Shortcut.png>. It opens Ulipad, but
a Ulipad that uses 2.51, not 2.62 in its shell, but does use 2.62 to
run scripts (Ulipad asked me which interpreter I wanted to use for
that). So it seems I've almost got Ulipad where I want it. Perhaps the
developer can help me get its shell to use 2.62 as well.

I made a shortcut for IDLE that opens an IDLE that uses
2.62 (it's image is at <http://www.rcblue.com/Misc/IDLE_Shortcut.png>).

Thanks,

Dick
___
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 Dick Moores
On Mon, Jul 27, 2009 at 12:50, ALAN GAULD wrote:
>
>
>> > What I do for these things is create a shortcut which specifies the full
>> > path to the interpreter and to the pyw file. I also set the working foldeer
>> > to wherever is most appropriate - usually my project folder. That's fairly
>> > bulletproof in my experience!
>>
>> Alan, here's what have now to call Ulipad: the shortcut shown in the
>> attached image. It opens Ulipad, but a Ulipad that uses 2.51, not 2.62
>
> So edit the Target field of the shortcut to say:
>
> E:\Python26\pythonw.exe E:\Programs\Ulipad37\ulipad.pyw

No, I'd already tried that. Doesn't work. Nothing happens.

> Or whatever combination of interpreter and editor you want.

That is the correct combination.

> In other words explicitly specify both the interpreter and the file rather 
> than
> relying on Windows file associations.
>
> And if that fails to work, the lasst resort is to write a batch file that 
> calls
> the right file with the rigt interpreter and then create a shortcut to that!

Any chance you could write that batch file for me?

Dick
___
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 Dick Moores
On Mon, Jul 27, 2009 at 14:32, Alan Gauld wrote:
>
> "Dick Moores"  wrote
>
>>> So edit the Target field of the shortcut to say:
>>>
>>> E:\Python26\pythonw.exe E:\Programs\Ulipad37\ulipad.pyw
>>
>> No, I'd already tried that. Doesn't work. Nothing happens.
>
> OK, You could try changing pythonw.exe tyo python.exe to
> bring up a console and watch for errors there

I get a console for a fraction of a second. Can't read anything it says.

> Or just try typing the command into a console session till
> you get one that works!


>>> In other words explicitly specify both the interpreter and the file
>>> rather than
>>> relying on Windows file associations.
>>>
>>> And if that fails to work, the lasst resort is to write a batch file that
>>> calls
>>> the right file with the rigt interpreter and then create a shortcut to
>>> that!
>>
>> Any chance you could write that batch file for me?
>
> Look at the one used for IDLE in standard python - idle.bat.
>
> Just copy and edit it as suggested by someone earlier.

I'm not sure how to edit it. What's required for Ulipad is quite
different, I believe.

This is what I got from Dave Angel:
e:
  cd \Python26\Lib\idlelib\
  ..\..\pythonw.exe idle.pyw %*

And I can't decipher it. What is the "..\..\"?

I would like to learn how to write simple batch files, however, quite
aside from writing one to solve my Ulipad problem.

> Finally, never having used ulipad, is it the interpreter called by the
> editor
> that you are trying to change? Or the interpretor that runs the editor?

The latter, I believe.

> When you say "nothing happens" do you mean the editor doesn't start?

Yes.

> Or just that it still uses the wrong version of Python?
>
> If it's the interpreter used by the editor to run programs that may be
> defined in ulipad's config details somewhere - either an ini file or
> in the registry.  In which case find it and edit it manually.
> Or it could be by ulipad reading it from the environment - in which
> case there won't be much you can do!

I think I'll wait until the developer, who is in China (Beijing, I
believe), wakes up and gets back to his computer. It's 6:19 am there
now. If I understood him correctly, the version of Python Ulipad's
shell uses should be the same as the version of Python it uses to run
scripts inside Ulipad. But in my case, the shell runs 2.51; 2.62 runs
my scripts.

Thanks very much Alan, and everybody! If I get this solved, I'll write back.

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


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

2009-07-28 Thread Dick Moores
On Tue, Jul 28, 2009 at 02:20, Dave Angel wrote:
> Dick Moores wrote:
>>
>> 
>> I'm not sure how to edit it. What's required for Ulipad is quite
>> different, I believe.
>>
>> This is what I got from Dave Angel:
>> e:
>>  cd \Python26\Lib\idlelib\
>>  ..\..\pythonw.exe idle.pyw %*
>>
>> And I can't decipher it. What is the "..\..\"?
>>
>>
>
> Just ask.The double-dots are the standard way of indicating "the
> directory above the previous one."  That's useful knowledge not only within
> batch files but also within shortcuts and within Python programs.
>
> The batch file starts by changing to the E: drive.  Then it changes to the
> explicit directory \Python26\Lib\idlelib, and because of the leading slash,
> that refers to an absolute directory, irrespective of what the current
> directory happened to be earlier. The 3rd line means that we want to run a
> program pythonw.exe, located two directories up from the current one,
> *without changing" the current directory.  It could have been written:
>
>e:\Python26\pythonw.exe idle.pyw %*
>
> but then if you ever changed to a different version, or installed on a
> different drive or directory, you'd have two places in the batch file to
> change.  I like using relative directories where possible.
>
> Finally, the %* at the end means copy whatever other parameters were passed
> to the batch file, as additional parameters to the program.

Thanks, Dave. Very informative.

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


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

2009-07-31 Thread Dick Moores
Finally, success! Thanks to help from the Ulipad list.

Python is built on wxPython. I upgraded wxPython to v2.8. Then found
that even with 2.8 I was getting an error saying that I didn't have
the comtypes module. After downloading and installing comtypes I now
have Ulipad's shell running 2.6.2 and also Ulipad running scripts
within Ulipad written in 2.6.2. See
<http://www.rcblue.com/Misc/Ulipad4.png>, which shows the Ulipad's
shell window on the left, executing correctly a bit of code using a
new 2.6 feature, and also the "Messages" window showing the correct
output of the script 26.py .

I call Ulipad with a Win XP shortcut,
<http://www.rcblue.com/Misc/Ulipad_Shortcut2.png>. The contents of the
"Target:" textbox is
"E:\Python26\pythonw.exe E:\Programs\Ulipad3.7\Ulipad.pyw" (no quotes).

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


[Tutor] How to get user input as regex

2005-04-02 Thread Dick Moores
I'm just beginning to learn regex, and am wondering how to get user input 
that can be used as a regex. Of course my attempt below doesn't work, but 
how should I modify it?

I'm practicing with phone.txt, which is 513 lines, each line having a 
name and phone number, and some other details like an address and times.

Sorry for the dumb question.
import re
s = raw_input("regex: ")
digs = re.compile(r"s")
for line in open("data//phone.txt"):
if digs.search(line):
print line
Thanks,
Dick Moores
[EMAIL PROTECTED]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to get user input as regex

2005-04-02 Thread Dick Moores
Pierre Barbier de Reuille wrote at 07:22 4/2/2005:
You should do something much simpler ^_^ :
import re
s = raw_input("regex : ")
digs = re.compile(s)
[...]
Aha! Thanks!
Dick


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


Re: [Tutor] What is the best book to start? - Many Thanks!

2005-04-07 Thread Dick Moores
Steve George wrote at 01:36 4/6/2005:
The best book I know is Core Python by Wesley Chun.  But it only
covers 1.6 so quite a few things have changed since then.
The first page (p. ixx?) of the Preface to my copy says "At the time of 
publication (2001), Python 2.0 was just released, so you will definitely 
have the latest and greatest."

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


Re: [Tutor] UselessPython 2.0

2005-04-09 Thread Dick Moores
Sean Steeg wrote at 11:22 4/7/2005:
So we're requesting that anyone with
one-offs, snippets, mini-apps, full-fledged apps and the like make a
submission to the new and improved UselessPython.  The code doesn't
have to be pretty, but it does have to work.
I'm a newbie, but would this qualify as a contribution to UselessPython 2.0?

#isPalindrome.py
# revision of http://www.uselesspython.com/glpalindrome.py to handle 
palindromes
#   such as "Radar" and "A man, a plan, a canal, Panama!"

# http://www.palindromelist.com/ has many palindromes
# string.ascii_lowercase is 'abcdefghijklmnopqrstuvwxyz'
import string
def isPalindrome(w):
return w == '' or (w[0]==w[-1]) and isPalindrome(w[1:-1]) # recursive
def makeStringAllLowercaseAlpha(s):
"""
Take any string, convert all uppercase alphabetic characters to 
lower case,
then strip all non-alphabetic characters
"""
s1 = string.lower(userstring)
s2 = ""
for index in range(len(s1)):
if s1[index] in string.ascii_lowercase:
s2 += s1[index]
return s2

userstring = raw_input('Enter a word or sentence to test: ')
userstringRevised = makeStringAllLowercaseAlpha(userstring)
if isPalindrome(userstringRevised):
print userstring, "is a palindrome."
else:
print userstring, "is not a palindrome."

Dick Moores
[EMAIL PROTECTED]


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


[Tutor] Trying to write a string formatting demo

2005-04-10 Thread Dick Moores
I'm trying to write a string formatting demo, just for things like 
%.4f,  %.3e, and %.3g.

Here's what I have, but of course it doesn't work. What should the print 
statement be?


x = raw_input("enter a float: ")
if x == "":
print "x will be the default 1234.56789"
x = 1234.56789
else:
x = float(x)
s = raw_input("enter a float format string such as '.4f' or '.3e': ")
print "%f formatted with '%s' is %s" % (x,s,x)
==
Thanks,
Dick Moores
[EMAIL PROTECTED]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trying to write a string formatting demo

2005-04-10 Thread Dick Moores
Brian van den Broek wrote at 01:09 4/10/2005:
Hi Dick,
why not replace th last line with the following 2:
print_value = ('%' + s ) %x
print "%f formatted with '%s' is %s" %(x, s, print_value)
HTH,
Brian vdB
Sorry, half asleep: I should also have said that I don't think it is 
wise to call your user input string governing the formating of the float 
`s'. Much better to choose a meaningful name, or, failing that, at least 
not a letter that is itself a string formatting code :-)
Thanks very much, Brian. Here's what I have now, and it works.
==
# formatDemo.py
while True:
print "enter a float, 'q' to quit, or nothing to accept default 
float of 1234.56789"
x = raw_input()
if x == "":
print "x will be the default 1234.56789"
x = 1234.56789
elif x in "qQ":
break
else:
x = float(x)

floatFormatString = raw_input("enter a float format string such as 
'.4f' or '.3e': ")

printValue = ('%' + floatFormatString ) %x
print "%f formatted with '%s' is %s" %(x, floatFormatString, printValue)
print
==
Dick
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] UselessPython 2.0

2005-04-12 Thread Dick Moores
Michael Janssen wrote at 10:30 4/11/2005:
On Apr 10, 2005 7:18 AM, Dick Moores <[EMAIL PROTECTED]> wrote:
> I'm a newbie, but would this qualify as a contribution to 
UselessPython 2.0?

Hello Dick,
don't be shy, or do you suspect it might be too usefull? ;-) I found
it funny, so it must be good enough.
here my remarks:
> def makeStringAllLowercaseAlpha(s):
> """
> Take any string, convert all uppercase alphabetic characters to
> lower case,
> then strip all non-alphabetic characters
[what's bad about non-alphabetic characters?]
> """
> s1 = string.lower(userstring)
oops: this function gets an argument s, here you're using the global
variable userstring. I know, it works, but there will be functions
were mistakes like this weren't just ugly but buggy.
> s2 = ""
> for index in range(len(s1)):
> if s1[index] in string.ascii_lowercase:
> s2 += s1[index]
or easier (much more readable, helps understanding the programm):
for char in s1:
 if char in string.ascii_lowercase:
   s2 += char
regards
Michael
Thanks very much, Michael. Here's the revision.
=
# isPalindrome.py
# revision of http://www.uselesspython.com/glpalindrome.py to handle 
palindromes
#   such as "Radar" and "A man, a plan, a canal, Panama!"

# http://www.palindromelist.com/ has many palindromes
# string.ascii_lowercase is 'abcdefghijklmnopqrstuvwxyz'
import string
def isPalindrome(w):
return w == '' or (w[0]==w[-1]) and isPalindrome(w[1:-1]) # recursive
def makeStringAllLowercaseAlpha(s):
"""
Take any string, convert all uppercase alphabetic characters to 
lower case,
then strip all non-alphabetic characters
"""
s1 = string.lower(s)
s2 = ""
for char in s1:
if char in string.ascii_lowercase:
s2 += char
return s2

userstring = raw_input('Enter a word or sentence to test: ')
userstringRevised = makeStringAllLowercaseAlpha(userstring)

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


Re: [Tutor] How to calculate pi with another formula?

2005-04-12 Thread Dick Moores
Gregor Lingl wrote at 11:27 10/29/2004:
Hi Dick!
Accidentally I just was tinkering around with the new
decimal module of Python2.4. (By the way: it also works
with Python 2.3 - just copy it into /Python23/Lib)
The attached program uses a very elementary (and inefficient)
formula to calculate pi, namely as the area of a 6*2**n-sided
polygon (starting with n=0), inscribed into a circle of radius 1.
(Going back to Archimedes, if I'm right ...)
Nevertheless it calculates pi with a precision of (nearly)
100 digits, and the precision can be  arbitrarily enlarged.
In the output of this program only the last digit is not correct.
import decimal
decimal.getcontext().prec = 100
def calcpi():
   s = decimal.Decimal(1)
   h = decimal.Decimal(3).sqrt()/2
   n = 6
   for i in range(170):
   A = n*h*s/2  # A ... area of polygon
   print i,":",A
   s2 = ((1-h)**2+s**2/4)
   s = s2.sqrt()
   h = (1-s2/4).sqrt()
   n = 2*n
calcpi()
Just for fun ...
Gregor
This works great, and if I change the precision to, say, 2000, and the 
range to 2000, I get pi accurate to the 1,205th digit (this took 66 
minutes, with psyco employed), when I compare with the pi pages on the web.

Now to my new question. I have an artist friend who knows an artist who 
needs pi expressed in base 12. I don't know how many digits he needs, but 
I think he'll take what he can get. Is there a way to use math.log(x, 
base) with the decimal module to accomplish this? Or is there another 
way? Or is there no way?

Thanks,
Dick Moores
[EMAIL PROTECTED]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] terminology question

2005-08-01 Thread Dick Moores
Why are list comprehensions called that?

Thanks,

Dick Moores
[EMAIL PROTECTED]

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


Re: [Tutor] terminology question

2005-08-01 Thread Dick Moores
[EMAIL PROTECTED] wrote at 21:52 8/1/2005:
>Quoting Dick Moores <[EMAIL PROTECTED]>:
>
> > Why are list comprehensions called that?
>
>Because that's what they're called in Haskell, I guess..

This Haskell, I suppose?
<http://en.wikipedia.org/wiki/Haskell_programming_language>

>It's historical, based on the term "set comprehension" from mathematics, 
>also
>known as "set builder notation": 
>http://en.wikipedia.org/wiki/Set_comprehension

And I was a math major..

Thanks!

Dick

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


Re: [Tutor] can python run under windows 95?

2007-05-07 Thread Dick Moores


At 12:49 PM 5/7/2007, Andreas Kostyrka wrote:
I'm almost sure that Python as
such runs on Win95. Some modules might
not. But I'm also almost sure that the installer is not Win95
compatible.
But there's this from
<
http://www.python.org/download/releases/2.5/>, which seems to
imply that if he first downloads and installs the Microsoft Installer,
the .msi would be installable. No?
"Starting with the Python 2.4 releases the Windows Python
installer is being distributed as a Microsoft Installer (.msi) file. To
use this, the Windows system must support Microsoft Installer 2.0. Just
save the installer file,

Python-2.5.msi, to your local machine, then double-click
python-2.5.msi to find out if your machine supports MSI. If it doesn't,
you'll need to install Microsoft Installer first. Many other packages
(such as Word and Office) also include MSI, so you may already have it on
your system. If not, you can download it freely from Microsoft for

Windows 95, 98 and Me and for

Windows NT 4.0 and 2000. Windows XP and later already have MSI; many
older machines will already have MSI installed."
Dick Moores



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


Re: [Tutor] wxPython GUI builders?

2007-06-13 Thread Dick Moores
At 01:08 PM 6/13/2007, Alan Gauld wrote:
>What's available and in what state of readiness?

I don't have the details you want, but you might look at SPE. 
<http://pythonide.blogspot.com/>

Dick Moores


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


Re: [Tutor] Integer to binary

2007-07-10 Thread Dick Moores
At 07:27 AM 7/10/2007, Mihai Iacob wrote:
>Hello,
>
>Is there a function that converts from integer to
>binary (or a module that handles this)?
>
>The only thing close to it that i found in the manual
>is the binascii module but i can't get it to work.

Here's one:

def base10ToBaseN(n, base=2):
 """converts base 10 integer n to base 2-9 integer as string"""
 if n == 0: return '0'
 sign = '-' if n<0 else ''

 num = abs(n)
 seq = []
 while (num != 0):
 (num, bit) = divmod(num, base)
 seq.append(str(bit))
 seq.append(sign)
 return ''.join(reversed(seq))

Dick Moores


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


[Tutor] Importing question

2007-07-13 Thread Dick Moores


At

http://wiki.python.org/moin/SimplePrograms I found this
code:

import itertools
def iter_primes():
 # an iterator of all numbers between 2 and
+infinity
 numbers = itertools.count(2)
 # generate primes forever
 while True:
 # get the first number
from the iterator (always a prime)
 prime =
numbers.next()
 yield prime
 # this code iteratively
builds up a chain of
 # filters...slightly
tricky, but ponder it a bit
 numbers =
itertools.ifilter(prime.__rmod__, numbers)
for p in iter_primes():
    if p > 1000:
    break
    print p

It works for me in Win XP, Python 2.5.
However, in trying to dig into the code to understand it, I'm not able to
find itertools.py, even though itertools is found in the docs at
<
http://www.python.org/doc/2.4/lib/module-itertools.html>. 
A search of my Python25 directory doesn't turn up an itertools.py.

So my question is, how does the first line of the code work? Where
is itertools?
Thanks,
Dick Moores


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


Re: [Tutor] Importing question

2007-07-13 Thread Dick Moores
At 07:55 AM 7/13/2007, Eric Brunson wrote:
>Dick Moores wrote:
>>At http://wiki.python.org/moin/SimplePrograms I found this code:
>>
>>
>>import itertools
>>
>>def iter_primes():
>>  # an iterator of all numbers between 2 and +infinity
>>  numbers = itertools.count(2)
>>
>>  # generate primes forever
>>  while True:
>>  # get the first number from the iterator (always a prime)
>>  prime = numbers.next()
>>  yield prime
>>
>>  # this code iteratively builds up a chain of
>>  # filters...slightly tricky, but ponder it a bit
>>  numbers = itertools.ifilter(prime.__rmod__, numbers)
>>
>>for p in iter_primes():
>> if p > 1000:
>> break
>> print p
>>
>>
>>It works for me in Win XP, Python 2.5.
>>
>>However, in trying to dig into the code to understand it, I'm not 
>>able to find itertools.py, even though itertools is found in the 
>>docs at < http://www.python.org/doc/2.4/lib/module-itertools.html>.
>>A search of my Python25 directory doesn't turn up an itertools.py.
>>
>>So my question is, how does the first line of the code work? /Where 
>>/is itertools?
>
>On my Fedora 7 system it is in 
>/usr/lib/python2.5/lib-dynload/itertoolsmodule.so.

Hm. I have no lib-dyload, nor an itertoolsmodule.

Dick


>Note the difference in naming for built in binary modules.

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


[Tutor] class question

2007-07-13 Thread Dick Moores


on

http://wiki.python.org/moin/SimplePrograms I found this
code:
===
class BankAccount(object):
    def __init__(self, initial_balance=0):
    self.balance =
initial_balance
    def deposit(self, amount):
    self.balance += amount
    def withdraw(self, amount):
    self.balance -= amount
    def overdrawn(self):
    return self.balance <
0
my_account = BankAccount(15)
my_account.withdraw(5)
print my_account.balance
=
This prints the expected "10". 
My question is, of what use can "overdrawn" be put? If I change
the withdrawal amount to 25, it prints the expected "-10",
whether the class contains the "overdrawn" function or
not.
Thanks,
Dick Moores


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


Re: [Tutor] class question

2007-07-13 Thread Dick Moores
At 05:35 AM 7/13/2007, Tiger12506 wrote:
> > ===
> > class BankAccount(object):
> >def __init__(self, initial_balance=0):
> >self.balance = initial_balance
> >def deposit(self, amount):
> >self.balance += amount
> >def withdraw(self, amount):
> >self.balance -= amount
> >def overdrawn(self):
> >return self.balance < 0
> > my_account = BankAccount(15)
> > my_account.withdraw(5)
> > print my_account.balance
> > =
> >
> > This prints the expected "10".
> >
> > My question is, of what use can "overdrawn" be put? If I change the
> > withdrawal amount to 25, it prints the expected "-10", whether the class
> > contains the "overdrawn" function or not.
> >
> > Thanks,
> >
> > Dick Moores
>
>A very good question. Now I have one for you. What does your bank do when
>you try to withdraw money? First, it checks to see if you have the money in
>your account. If you do, it subtracts that out of your balance. Whoever
>wrote that code failed to do the check within the withdraw function.
>
>===
>class BankAccount(object):
>def __init__(self, initial_balance=0):
>self.balance = initial_balance
>def deposit(self, amount):
>self.balance += amount
>def withdraw(self, amount):
>if self.overdrawn():
>   raise "Insufficient Funds Error"
>self.balance -= amount
>def overdrawn(self):
>return self.balance < 0
>my_account = BankAccount(15)
>my_account.withdraw(5)
>print my_account.balance
>=

But when I run that with a withdrawal of 25, it still prints only 
"-10". How have you involved the "overdrawn" function?

Dick


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


Re: [Tutor] class question

2007-07-13 Thread Dick Moores


At 12:35 PM 7/13/2007, [EMAIL PROTECTED] wrote:
However if you try to withdraw
any money after you took out the $25 it would raise the error. 
The overdrawn function checks if you are in the negatives. 
Since the balance is checked before the money is taken out, there is no
error when you take out the $25. 
If you wan the error to be raised whenever you go negative simply switch
the withdrawal and the function call in withdraw 
 def withdraw(self, amount): 
    self.balance -=
amount
   if self.overdrawn():
  raise
"Insufficient Funds Error"

and if you don't want the money taken out if there is insufficient
funds, 
just add the withdrawn amount back: 
 def withdraw(self, amount): 
    self.balance -=
amount
   if self.overdrawn(): 
    self.balance +=
amount
  raise
"Insufficient Funds Error, no money withdrawn" 

Thanks. You've clarified it for me completely. 
Your second way seems to make more sense. And instead of raising the
error, why not just print it:
class BankAccount(object):
   def __init__(self, initial_balance=0):
   self.balance = initial_balance
   def deposit(self, amount):
   self.balance += amount
   def withdraw(self, amount): 
   self.balance -= amount
   if self.overdrawn(): 
   self.balance
+= amount
   print
"Insufficient Funds, no money withdrawn"   

   def overdrawn(self):
   return self.balance < 0
my_account = BankAccount(15)
my_account.withdraw(25)
print "Account balance is", my_account.balance
Dick



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


Re: [Tutor] class question

2007-07-13 Thread Dick Moores
At 03:12 PM 7/13/2007, Alan Gauld wrote:

>"Dick Moores" <[EMAIL PROTECTED]> wrote
>
> > Thanks. You've clarified it for me completely.
> >
> > Your second way seems to make more sense.
> > And instead of raising the error, why not just print it:
>
>Because that would make the class much less reusable.
>It would be limited to applications using stdout. A GUI
>banking program would be unable to use the BankAccount
>class. But by raising an exception the user gets to decide
>what to do, either pop up a dialog, print a message or send
>an email to the banks client.
>
>Its a primary design goal for reuse to de-couple business
>logic - like the bank account - from the user interface.
>
>There is a bit more discussion around this in my
>Case Study topic where I convert it from command
>line to GUI and again in my InterProcess Comms topic
>where I turn the AddressBook into a client-server app.

Thanks, Alan. I'll check it out.

Dick


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


Re: [Tutor] Importing question

2007-07-13 Thread Dick Moores
At 02:50 PM 7/13/2007, Alan Gauld wrote:

>"Dick Moores" <[EMAIL PROTECTED]> wrote in
>
>
> > import itertools
> >
> > def iter_primes():
> > # an iterator of all numbers between 2 and +infinity
> > numbers = itertools.count(2)
> > ...
>
> > It works for me in Win XP, Python 2.5.
> >
> > However, in trying to dig into the code to understand it,
> > I'm not able to find itertools.py,
>
>Thats because its a compiled C module not implemented
>in Python. You probably won't find a sys.py either.
>
>If you do
>
> >>> print itertools
>
>
>You'll see its actually built-in.
>
>So you need to look at the C source to see how it is written!

Ah. and

 >>> import math
 >>> print math


Thanks, Alan!

Dick

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


Re: [Tutor] Good writeup on Python assignment semantics

2007-07-17 Thread Dick Moores


At 04:57 AM 7/17/2007, you wrote:
A recent comp.lang.python thread
has a good explanation of Python's 
assignment semantics:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/56e7d62bf66a435c/

Kent,
Yes, interesting. But could you explain what you mean by "assignment
semantics"?  Semantics:
<
http://dictionary.reference.com/search?q=semantics>
I have trouble relating semantics to programming. Also, "object
passing semantics" as in the sentence in that thread, "You need
to learn about Python's scoping now, not its object passing semantics.

I did some Googling, and came up with this, which seems relevant, but
clearer about syntax than semantics: 
"Semantics
In linguistics, the study of meanings. In computer science, the term
is frequently used to differentiate the meaning of an instruction from
its format. The format, which covers the spelling of language components
and the rules controlling how components are combined, is called the
language's syntax. For example, if you misspell a command, it is a syntax
error. If, on the other hand, you enter a legal command that does not
make any sense in the current context, it is a semantic error.
"
<
http://www.angelfire.com/anime3/internet/programming.htm>
Thanks,
Dick Moores



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


Re: [Tutor] Good writeup on Python assignment semantics

2007-07-17 Thread Dick Moores
At 07:38 AM 7/17/2007, Kent Johnson wrote:
>Dick Moores wrote:
>>At 04:57 AM 7/17/2007, you wrote:
>>>A recent comp.lang.python thread has a good explanation of Python's
>>>assignment semantics:
>>>http://groups.google.com/group/comp.lang.python/browse_thread/thread/56e7d62bf66a435c/
>>> 
>>>
>>
>>Kent,
>>Yes, interesting. But could you explain what you mean by 
>>"assignment semantics"?  Semantics: < 
>>http://dictionary.reference.com/search?q=semantics>
>>I have trouble relating semantics to programming.
>
>Semantics: The study or science of meaning in language.
>
>In other words, what does it mean to say
>   a = b
>in Python?
>
>Syntax is like spelling and grammar rules - if you understand 
>syntax, you can write a program that will compile and run. But 
>without understanding what the various programming constructs 
>actually mean, you will have trouble writing a program that does 
>something useful.
>
>I think to write correct programs in any language, you must have a 
>correct mental model of what the program is doing, where by 
>'correct' I mean a model that is consistent with the actual 
>behaviour of the program.
>
>Programmers coming from a background in C and C++ have a mental 
>model of variables as containers for values. This model works in 
>those languages, where variables correspond to memory locations and 
>assignment copies a value from one location to another. It doesn't 
>work in Python, where variables are names for values and assignment 
>creates another name for the same value without copying. To write 
>correct Python programs you have to have a different model for what 
>variables are and how they behave. We regularly see questions on 
>this list from people who are confused by assignment because they 
>are using a faulty model.
>
>So "what does it mean?" might be interpreted as "what is a useful 
>model of this operation that allows me to understand and predict its 
>behaviour?", and "assignment semantics" is a shortcut for saying "a 
>useful model of assignment that allows me to understand and predict 
>its behaviour."
>
>Kent

Thanks very much for your trouble, Kent. A big help.

Dick 

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


Re: [Tutor] What exactly is [::-1]?

2007-07-26 Thread Dick Moores
At 12:37 PM 7/26/2007, Chris Calloway wrote:
>The *other* form of extended slicing, the one with two colons (and no
>commas) is supported by typeseq objects, though.

What are typeseq objects. Searching the python site on "typeseq" draws a blank.

Dick Moores 

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


Re: [Tutor] What exactly is [::-1]?

2007-07-26 Thread Dick Moores
At 12:17 AM 7/26/2007, Alan Gauld wrote:

>"Dick Moores" <[EMAIL PROTECTED]> wrote
>
> >>I could send you a link but I'd just google 'python list slicing' to
> >>find it, so I'll leave that as an exercise for the reader.
> >
> > I don't find Google of help with this. Could someone supply a link?
>
>Not sure why it didn't help you Dick, but it led me to:
>
>http://docs.python.org/lib/typesseq.html
>
>Which is admittedly sparing in its explanation but does at
>least describe the three values involved and their defaults.
>
>The tutorial also threw up this:
>
>http://docs.python.org/tut/node5.html
>
>Which describes basic slicing (using only 2 indices) of strings
>and also has a link to the previous reference page.
>
>Finally I tried googling for 'python slicing' and got this as my first
>hit:
>
>http://docs.python.org/ref/slicings.html
>
>Which is the language lawyers version!

Alan, I don't see an explanation of [::-1] anywhere in those 3 links. 
There needs to be a clear description and better examples somewhere 
in the docs, IMO.

My thanks to Luke and Wesley.

Dick


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


Re: [Tutor] What exactly is [::-1]?

2007-07-25 Thread Dick Moores
At 08:38 PM 7/25/2007, Luke Paireepinart wrote:
> > I would like to know what exactly the index notation of [::-1] is, where
> > it comes from and if there are other variants.
> >
>This is called list slicing.  Look into it to figure out what all this
>stuff means.
>I could send you a link but I'd just google 'python list slicing' to
>find it, so I'll leave that as an exercise for the reader.

I don't find Google of help with this. Could someone supply a link?

Dick Moores


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


Re: [Tutor] Code like a Pythonista

2007-07-27 Thread Dick Moores
At 05:13 AM 7/26/2007, Kent Johnson wrote:
>For anyone who has wondered, how do I learn to write Python like an
>expert? What do I read after I finish the tutorial? Check out David
>Goodger's "Code Like a Pythonista"
>http://python.net/~goodger/projects/pycon/2007/idiomatic/

Kent,

The handout is excellent! Thanks!

But the slideshow at 
<http://python.net/~goodger/projects/pycon/2007/idiomatic/presentation.html>, 
isn't.

Dick Moores


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


Re: [Tutor] Code like a Pythonista

2007-07-27 Thread Dick Moores
At 12:02 PM 7/27/2007, Terry Carroll wrote:
>On Fri, 27 Jul 2007, Dick Moores wrote:
>
> > The handout is excellent! Thanks!
> >
> > But the slideshow at
> > 
> <http://python.net/~goodger/projects/pycon/2007/idiomatic/presentation.html>,
> > isn't.
>
>You have to use the page-up and -down keys; or the spacebar (at least on
>Windows under Firefox).  Took me a while to figure that out.

Ah. Thanks.

Dick


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


Re: [Tutor] ideas for college app.

2007-07-28 Thread Dick Moores
At 03:02 AM 7/28/2007, Shriphani Palakodety wrote:
>Hello all,
>I am looking for a few ideas for my college app. Can someone give me a
>few ideas i could work on? I would like to use these to learn more of
>python and to become a true expert at it.

Are there any set requirements for your "college app"? What does 
"college app" mean?

Dick Moores


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


[Tutor] Ingenious script (IMO)

2007-08-06 Thread Dick Moores
Google Answers folded, but Google has kept the archive accessible. I 
found this Python script at 
<http://answers.google.com/answers/threadview?id=756160>

and modified it for U.S. money denominations:

http://www.rcblue.com/Python/changeMaker_revised_for_US_denominations.py

I'm still working at Python--been at it a while--and thought the 
script was ingenious. Do the Tutors agree? Or is it just 
run-of-the-mill programming? Could it have been more simply written?

Thanks,

Dick Moores

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


Re: [Tutor] Ingenious script (IMO)

2007-08-06 Thread Dick Moores
At 06:49 AM 8/6/2007, Kent Johnson wrote:
>Dick Moores wrote:
>>http://www.rcblue.com/Python/changeMaker_revised_for_US_denominations.py
>>I'm still working at Python--been at it a while--and thought the 
>>script was ingenious. Do the Tutors agree? Or is it just 
>>run-of-the-mill programming? Could it have been more simply written?
>
>I don't find it either ingenious or well-written. The algorithm is 
>the same one you would use to count out an amount by hand so it 
>doesn't seem so unusual. IMO the code relies too much on indices. If 
>you rewrite it using a dict (or, even better, defaultdict(int)) for 
>coinCount, there is no need for indices at all. Even with coinCount 
>as a list, it could be better written.
>
>coinCount = []
>for d in denominations:
> coinCount.append(0)
>
>=>
>
>coinCount = [0] * ndenominations
>
>
>The main loop could be
>for deno in range(ndenominations):
>   if not remaining:
> break
>
>or
>for i, deno in enumerate(denominations):
># i is now the index, deno is the actual denomination
>
>
>but I would write it this way and avoid the use of the index completely:
>
>from collections import defaultdict
>coinCount = defaultdict(int)
>remaining = change
>
>#   Loop until either we have given all the change or we have
>#   run out of coin denominations to check.
>for deno in denominations:
> if not remaining:
> break
>
> #   For one denomination, count out coins of that denomination
> #   as long as the remaining amount is greater than the denomination
> #   amount.
>
> while remaining >= deno:
> coinCount[deno] += 1
> print "remaining =", remaining
> remaining -= deno
>
>#   Report the results.
>print "Your change is $%.02f"% (float(change) / CPD)
>for deno in denominations:
> if coinCount[deno] > 0:
> if deno >= 100:
> print "$%d bills:\t" % (deno / CPD), coinCount[deno]
> else:
> print "%d-cent coins:\t" % (deno), coinCount[deno]
>
>
>Kent

Thanks Kent!

Here's what I have after incorporating your suggestions:

=
#!/usr/bin/env python
#coding=utf-8
from collections import defaultdict

CPD = 100
cost = int(CPD * float(raw_input("Enter the cost: ")))
tend = int(CPD * float(raw_input("Enter the tendered amount: ")))

#   Calculate the change.
change = tend - cost

coinCount = defaultdict(int)
print coinCount
remaining = change
denominations = (2000, 1000, 500, 100, 50, 25, 10, 5, 1)

#   Loop until either we have given all the change or we have
#   run out of coin denominations to check.
for deno in denominations:
 if not remaining:
 break


 #   For one denomination, count out coins of that denomination
 #   as long as the remaining amount is greater than the denomination
 #   amount.


 while remaining >= deno:
 coinCount[deno] += 1
 remaining -= deno


#   Report the results.
print "Your change is $%.02f"% (float(change) / CPD)
for deno in denominations:
 if coinCount[deno] > 0:
 if deno >= 100:
 print "$%d bills:\t" % (deno / CPD), coinCount[deno]
 else:
 print "%d-cent coins:\t" % (deno), coinCount[deno]


Gotta say though, I still don't understand how the defaultdict works here.

Dick



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


Re: [Tutor] Ingenious script (IMO)

2007-08-06 Thread Dick Moores
At 07:44 AM 8/6/2007, Kent Johnson wrote:
>Dick Moores wrote:
>>Gotta say though, I still don't understand how the defaultdict works here.
>
>Did you try the docs?
>http://docs.python.org/lib/defaultdict-objects.html

Yes, but it left me still in the dark.


>If coinCount were an ordinary dict, the line
>   coinCount[deno] += 1
>
>would have to be written as
>   coinCount[deno] = coinCount.get(deno, 0) + 1
>
>Using defaultdict(int) makes the use of 0 as the default value 
>automatic. (Actually the default value is obtained by calling int(), 
>whose value is 0.)

OK, thanks for spelling it out, Kent.

Dick

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


Re: [Tutor] Ingenious script (IMO)

2007-08-06 Thread Dick Moores
On 8/6/07, Eric Brunson <[EMAIL PROTECTED]> wrote:
>
> Try something like:
>
> def makechange( amount, denominations ):
>
> coins = {}
> for d in denominations:
> coins[d] = int( amount/d )
> amount = amount%d
>
> return coins
>
> Sorry, but could you spell out your point?

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


Re: [Tutor] Ingenious script (IMO)

2007-08-06 Thread Dick Moores
At 10:16 AM 8/6/2007, Eric Brunson wrote:

Your point about efficiency is well-taken.

>def makechange( amount, denominations ):
>
> coins = {}
> for d in denominations:
> coins[d] = int( amount/d )
> amount = amount%d
>
> return coins

OK, I used this this way:


def makechange( amount, denominations ):

coins = {}
for d in denominations:
coins[d] = int( amount/d )
amount = amount%d

return coins

denominations = (2000, 1000, 500, 100, 50, 25, 10, 5, 1)
amount = 2218
print makechange(2218, denominations)
==

And get:
{1: 3, 100: 2, 5: 1, 1000: 0, 10: 1, 2000: 1, 50: 0, 500: 0, 25: 0}

That's the correct change: 3 pennies, 2 $1 bills, 1 nickel, no $10 
bills, 1 dime, 1 $20 bill, no half-dollars, no $5 bills, no quarters.

For amount = 3288:
{1: 3, 100: 2, 5: 0, 1000: 1, 10: 1, 2000: 1, 50: 1, 500: 0, 25: 1}

Why those weird orders?

Dick



==
   Bagdad Weather
 

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


Re: [Tutor] Ingenious script (IMO)

2007-08-06 Thread Dick Moores
At 02:17 PM 8/6/2007, you wrote:
>Nice idea. Written style is average. Other tutors have discussed issues with
>performance, style, etc. I thought I would mention that whenever I am asked
>to give my opinion on a script, I compare it to something I have
>written/would write. In this case, I have already written. In my version, it
>not only tells how many of each denomination, but also how one would count
>back the change. It would be an interesting challenge to implement that, no?
>;-)

First remind me how Americans do that. I lived in Japan a long time, 
and it's done quite differently there.

For the U.S., say the output so far is:

Enter the cost: 5.77
Enter the tendered amount: 10
Your change is $4.23
$1 bills:   4
10-cent coins:  2
1-cent coins:   3

What would be the U.S. way of counting back the change? I think we 
start with the $5.77, but then what?

Dick

==
   Bagdad Weather
 

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


Re: [Tutor] Ingenious script (IMO)

2007-08-06 Thread Dick Moores
At 08:38 PM 8/6/2007, Tiger12506 wrote:
> > The modern way seems to be to look at the change amount given by the
> > cash register and count that out starting with dollars...
>So true... tsk tsk.
>
>That's because the teenagers that give you the change do not know how to
>count it back. What a great idea to write a program that can show them how!
>Or perhaps the excuse is more the truth - it's faster to throw the change at
>you. I know that many old-timers would be very impressed to have their
>change counted back to them. (It's required sometimes-my father told stories
>of a blind man that knew how much money he had and where in his wallet it
>was by how the cashier counted it back).
>
>I imagine that however exactly it is phrased when you count back change is
>dialectual. Some people do it some way, some do it other ways. In my part of
>the US, the "proper" way is:
>
>$10.00
>Say "5.77"
>"3 makes 80"
>"20 makes 6"
>"and four makes 10 dollars"
>"Have a nice day"
>
>While handing out the described amount at each line break. Sometimes,
>especially in important applications, like in a bank, they will count and
>hand the bills out to you individually - i.e. "and one, two, three, four
>makes 10 dollars"
>Of course, the "have a nice day" is optional, but it makes a nice touch ;-)
>Among the elders, it is considered very courteous to count back the change,
>but so often this is not the case that it is no longer considered rude to
>skip the counting...
>
>Anyway, the python part of this discussion is to point out that the method
>varies, so it would be even more of a challenge to provide options for how
>the change should be counted.

OK, I'll give it a try. Thanks for the challenges.

Dick

==
   Bagdad Weather
 

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


Re: [Tutor] Python Editors .. which do you reccomend for a amateur?

2007-08-09 Thread Dick Moores
At 04:23 PM 8/4/2007, johnf wrote:
>I got to put my pitch in for wing.  The latest is very good indeed.  Yea it
>cost money but I feel well worth the money.

John,

Could you tell us what it is about Wing that you like so much? I 
assume you mean Wing IDE Professional? Have you tried the new version 
3 beta? <http://wingware.com/>

Thanks,

Dick Moores

==
   Bagdad Weather
<http://weather.yahoo.com/forecast/IZXX0008_f.html> 

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


Re: [Tutor] Bookpool sale on Addison Wesley

2007-08-09 Thread Dick Moores
I always first check BestBookDeal.com. <http://www.bestbookdeal.com/>

Dick Moores

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


[Tutor] WinPdb?

2007-08-09 Thread Dick Moores


(I posted this to the python-list 24 hours ago, and didn't get a single
response. How about you guys?)
The only debugging I've done so far is to put in print statements where I
want to see what's happening. But it's often "through a glass
darkly".
However, I just discovered that my excellent (IMO) Python editor, Ulipad,
comes with WinPdb, and I'm thinking it's about time I learned how to use
a debugger. 
But first, could I get some reviews here of WinPdb before I invest a lot
of time in learning it? I've found a couple links to tutorials on the
WinPdb website
(<
http://www.digitalpeers.com/pythondebugger/>, where you'll also
notice that version 1.2.0 came out August 6 (the latest svn revision of
Ulipad already has it: 
(Ulipad's developer Limodou (who's in Beijing), is very
responsive). 
Thanks,
Dick Moores



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


Re: [Tutor] WinPdb?

2007-08-09 Thread Dick Moores
At 03:00 PM 8/9/2007, you wrote:
> > Dick Moores wrote:
> >> (I posted this to the python-list 24 hours ago, and didn't get a
> >> single response. How about you guys?)
> > You mean this list?  Cause if you mean this list, then you didn't post
> > it correctly.
>
>I don't believe he did. There are seperate python-lists, comp.lang.python,
>one actually called python-list I believe, and besides, since he
>specifically said "How about you guys?" as in let's try someone else - I
>think he didn't mean this list.

Right. I meant the python list named "python-list" with the address 
[EMAIL PROTECTED] ;) However, it should also have gone, as a 
matter of course, to the comp.lang.python newsgroup. I just checked 
and it's not there, even though more recent posts of mine in other 
threads ARE there.

Dick


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


[Tutor] Opinions about this new Python book?

2007-08-11 Thread Dick Moores


Title: Python Power!: The Comprehensive Guide 
Author: 

Matt Telles 
Publisher:  Course Technology 
Pub. Date:  Jul 27, 2007 
Edition:  1st edition 
Binding:  Paperback 
Pages:  508 
ISBN:  1598631586 
List Price:  34.99 USD
<
http://www.bestbookdeal.com/book/compare/1598631586>
Thanks,
Dick Moores


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


Re: [Tutor] WinPdb?

2007-08-11 Thread Dick Moores
At 04:31 PM 8/9/2007, Alan Gauld wrote:
>"Dick Moores" <[EMAIL PROTECTED]> wrote
>
> > The only debugging I've done so far is to put in print statements
> > where I want to see what's happening.
>
>Thats OK for basic stuff but for complex things you can wind up
>with an awful lot of printing going on!
>
> > However, I just discovered that my excellent (IMO) Python editor,
> > Ulipad, comes with WinPdb, and I'm thinking it's about time
> > I learned how to use a debugger.
>
>Everyone should, they are wonderful tools provided you stay
>in control.
>
> > But first, could I get some reviews here of WinPdb
>
>Its very good, I think the one in eclipse/PyDev is slightly better
>but its close. Its certainly better than either IDLE or Pythonwin.
>
>The main thing in using debuggers is to avoid the temptation to
>just start the program and step all the way through. Learn to use
>a combination of break points - to target a suspect function or
>control structure and watches - the equivalent of your print
>statements. If the debugger supports conditional watches so
>much the better, then you only get output when the value
>goes to a particular condition.
>
>Once you've broken the flow at a suspect function and shown
>a known error via a watch set another break point at the next
>level up then rerun to there (conditional break points are great
>too but I don't think pdb does those...) only then do you need
>to start stepping line by line until you see the bug occur.
>
>At that point give up on the debugger and engage your brain!
>
>BTW If you can get a copy of my book (the paper one - a
>library mebbe?) there is a chapter in there about debugging
>which includes the use of raw pdb...

Thanks for all the advice and tips, Alan.

Unfortunately, I can't find your book around here. Are there any 
other books/webpages on debugging you or others can recommend?

Dick


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


Re: [Tutor] Ingenious script (IMO)

2007-08-11 Thread Dick Moores
At 07:31 AM 8/6/2007, Dick Moores wrote:
>At 06:49 AM 8/6/2007, Kent Johnson wrote:
> >Dick Moores wrote:
> >>http://www.rcblue.com/Python/changeMaker_revised_for_US_denominations.py
> >>I'm still working at Python--been at it a while--and thought the
> >>script was ingenious. Do the Tutors agree? Or is it just
> >>run-of-the-mill programming? Could it have been more simply written?
> >
> >I don't find it either ingenious or well-written. The algorithm is
> >the same one you would use to count out an amount by hand so it
> >doesn't seem so unusual. IMO the code relies too much on indices. If
> >you rewrite it using a dict (or, even better, defaultdict(int)) for
> >coinCount, there is no need for indices at all. Even with coinCount
> >as a list, it could be better written.
> >
> >coinCount = []
> >for d in denominations:
> > coinCount.append(0)
> >
> >=>
> >
> >coinCount = [0] * ndenominations
> >
> >
> >The main loop could be
> >for deno in range(ndenominations):
> >   if not remaining:
> > break
> >
> >or
> >for i, deno in enumerate(denominations):
> ># i is now the index, deno is the actual denomination
> >
> >
> >but I would write it this way and avoid the use of the index completely:
> >
> >from collections import defaultdict
> >coinCount = defaultdict(int)
> >remaining = change
> >
> >#   Loop until either we have given all the change or we have
> >#   run out of coin denominations to check.
> >for deno in denominations:
> > if not remaining:
> > break
> >
> > #   For one denomination, count out coins of that denomination
> > #   as long as the remaining amount is greater than the denomination
> > #   amount.
> >
> > while remaining >= deno:
> > coinCount[deno] += 1
> > print "remaining =", remaining
> > remaining -= deno
> >
> >#   Report the results.
> >print "Your change is $%.02f"% (float(change) / CPD)
> >for deno in denominations:
> > if coinCount[deno] > 0:
> > if deno >= 100:
> > print "$%d bills:\t" % (deno / CPD), coinCount[deno]
> > else:
> > print "%d-cent coins:\t" % (deno), coinCount[deno]
> >
> >
> >Kent
>
>Thanks Kent!
>
>Here's what I have after incorporating your suggestions:
>
>=
>#!/usr/bin/env python
>#coding=utf-8
>from collections import defaultdict
>
>CPD = 100
>cost = int(CPD * float(raw_input("Enter the cost: ")))
>tend = int(CPD * float(raw_input("Enter the tendered amount: ")))
>
>#   Calculate the change.
>change = tend - cost
>
>coinCount = defaultdict(int)
>print coinCount
>remaining = change
>denominations = (2000, 1000, 500, 100, 50, 25, 10, 5, 1)
>
>#   Loop until either we have given all the change or we have
>#   run out of coin denominations to check.
>for deno in denominations:
>  if not remaining:
>  break
>
>
>  #   For one denomination, count out coins of that denomination
>  #   as long as the remaining amount is greater than the denomination
>  #   amount.
>
>
>  while remaining >= deno:
>  coinCount[deno] += 1
>  remaining -= deno
>
>
>#   Report the results.
>print "Your change is $%.02f"% (float(change) / CPD)
>for deno in denominations:
>  if coinCount[deno] > 0:
>  if deno >= 100:
>  print "$%d bills:\t" % (deno / CPD), coinCount[deno]
>  else:
>  print "%d-cent coins:\t" % (deno), coinCount[deno]
>
>
>Gotta say though, I still don't understand how the defaultdict works here.
>
>Dick

I was just about finished with a script that would tell the clerk how 
to give the change to the customer, when I discovered that the above 
script computes the wrong amount of change in certain situations. It 
works fine if the customer tenders only bills and no change, but 
that's not realistic. For example, if the cost is $1.78 the customer 
may well tender $2.03 so he can get a quarter back rather than 2 
dimes and 2 pennies. But the script in that case will compute change 
of 24 cents!  Try it out. I've put the same script on the web, but 
deleted the line that I'd left in by mistake, "print coinCount".

So, does this mean I should use the decimal module? Or is there 
another way to fix the problem?

Thanks,

Dick


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


Re: [Tutor] Ingenious script (IMO)

2007-08-11 Thread Dick Moores
At 04:11 AM 8/11/2007, Dick Moores wrote:

>I was just about finished with a script that would tell the clerk 
>how to give the change to the customer, when I discovered that the 
>above script computes the wrong amount of change in certain 
>situations. It works fine if the customer tenders only bills and no 
>change, but that's not realistic. For example, if the cost is $1.78 
>the customer may well tender $2.03 so he can get a quarter back 
>rather than 2 dimes and 2 pennies. But the script in that case will 
>compute change of 24 cents!  Try it out. I've put the same script on 
>the web, but deleted the line that I'd left in by mistake, "print coinCount".

Sorry. Forgot to include the link. 
<http://www.rcblue.com/Misc/changeMakerKent0-a.py>


>So, does this mean I should use the decimal module? Or is there 
>another way to fix the problem?
>
>Thanks,
>
>Dick

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


Re: [Tutor] Ingenious script (IMO)

2007-08-11 Thread Dick Moores
At 06:05 AM 8/11/2007, Kent Johnson wrote:
>Dick Moores wrote:
> > I was just about finished with a script that would tell the clerk how
> > to give the change to the customer, when I discovered that the above
> > script computes the wrong amount of change in certain situations. It
> > works fine if the customer tenders only bills and no change, but
> > that's not realistic. For example, if the cost is $1.78 the customer
> > may well tender $2.03 so he can get a quarter back rather than 2
> > dimes and 2 pennies. But the script in that case will compute change
> > of 24 cents!  Try it out. I've put the same script on the web, but
> > deleted the line that I'd left in by mistake, "print coinCount".
>
>The problem is that
>int(100 * float("2.03"))
>is 202, not 203, because the float representation of 2.03 is actually
>2.0298.
>
>The same problem occurs if you enter 2.03 as the cost and 3.00 as the
>amount tendered; it computes change of $0.98.
>
>Use int(round(100 * float("2.03"))) to get the correct amount.

That did it. Thanks, Kent.

Here's the script that hands over change in the traditional way. 
<http://www.rcblue.com/Misc/changeMakerKent_Traditional.py>

Is there a better way to handle the singulars and plurals?

Dick


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


Re: [Tutor] Ingenious script (IMO)

2007-08-11 Thread Dick Moores
At 07:13 AM 8/11/2007, bob gailer wrote:
>Dick Moores wrote:
>>Here's the script that hands over change in the traditional way. 
>><http://www.rcblue.com/Misc/changeMakerKent_Traditional.py>
>>
>>Is there a better way to handle the singulars and plurals?
>>
>What do you mean by "better"?
>More efficient?
>More readable/maintainable?
>Less code?

Phythonic.

Dick


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


Re: [Tutor] Ingenious script (IMO)

2007-08-11 Thread Dick Moores
At 07:21 AM 8/11/2007, bob gailer wrote:
>Dick Moores wrote:
>>At 07:13 AM 8/11/2007, bob gailer wrote:
>>>Dick Moores wrote:
>>>>Here's the script that hands over change in the traditional way. 
>>>><http://www.rcblue.com/Misc/changeMakerKent_Traditional.py>
>>>>
>>>>Is there a better way to handle the singulars and plurals?
>>>What do you mean by "better"?
>>>More efficient?
>>>More readable/maintainable?
>>>Less code?
>>
>>Phythonic.
>What about the current code is not "Pythonic"?

Hey, that's MY question. :-)

I'd just appreciate some constructive criticism.

Dick

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


Re: [Tutor] Decoding

2007-08-12 Thread Dick Moores


At 01:15 PM 8/12/2007, Khamid Nurdiev wrote:
Hello All,
 I am currently learning python with the book "Python
programming: An introduction to CS" by John M. Zelle and have come
the section where he speaks of encoding messages. Currently the basic
snippet looks like this:



def dec():

    import string

    message=raw_input("Enter the message to
decode: ") 

    result=''

    for x in string.split(message):

   
result=result+chr(eval(x))

    return result

print dec()



it works fine as expected
I dunno, if I enter "How are you?" at the prompt, I get
"NameError: name 'How' is not defined".
Dick Moores



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


Re: [Tutor] Decoding

2007-08-12 Thread Dick Moores


At 02:12 PM 8/12/2007, Dick Moores wrote:
At 01:15 PM 8/12/2007, Khamid
Nurdiev wrote:
Hello All,
 I am currently learning python with the book "Python
programming: An introduction to CS" by John M. Zelle and have come
the section where he speaks of encoding messages. Currently the basic
snippet looks like this:


def dec():
    import string
    message=raw_input("Enter the message to
decode: ") 
    result=''
    for x in string.split(message):
   
result=result+chr(eval(x))
    return result

print dec()


it works fine as expected
I dunno, if I enter "How are you?" at the prompt, I get
"NameError: name 'How' is not defined".
Oops! I missed the meaning of "decode". Sorry.
Dick



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


Re: [Tutor] Python Book Recommendations [Was:[Re: Security]]

2007-08-13 Thread Dick Moores
At 01:17 PM 8/13/2007, bhaaluu wrote:
>Finally, if you do find a computer programming book that you
>think is the Philosopher's Stone, and you can't live without it,
>check all the used-book stores that sell online at:
>
>http://used.addall.com

Better, IMO, is BestBookDeal.com <http://www.bestbookdeal.com/>

Dick Moores


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


[Tutor] Graphing the random.gauss distribution

2007-08-14 Thread Dick Moores
Kent Johnson posted this to Tutor list Aug 8, 2007 
(<http://mail.python.org/pipermail/tutor/2007-August/056194.html>):


 > Python provides you with a pseudo random number generator whose output
 > values are uniformly distributed between the input parameters.  What you
 > are dealing with in fish weights or test scores or other natural
 > phenomena is most likely a normal distribution. Check out Wikipedia's
 > normal distribution entry.  The math is really juicy. You may end up
 > with a recipe for the Python Cookbook.

No need for all that, use random.gauss()

Kent


I hadn't noticed gauss was there in the Random module. I got to 
wondering if I could graph the distribution. This code produces a 
nice bell-curve-seeming curve (on its side). Takes about 80 secs to 
run on my computer. To fit your situation, the length of the bars can 
be shortened or lengthened by decreasing or increasing, respectively, 
the divisor of gaussCalls in line 5, "barLengthAdjuster = gaussCalls//2600".

Dick Moores

==
from random import gauss
mean = 100
std = 10
gaussCalls = 1000
barLengthAdjuster = gaussCalls//2600

d = []
for k in range(200):
 d.append([k, 0])

for k in xrange(gaussCalls):
 n = int(gauss(mean, std))
 d[n][1] += 1

for c in d:
 barLength = c[1]//barLengthAdjuster
 print barLength, "=", c[0], c[1]


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


Re: [Tutor] Graphing the random.gauss distribution

2007-08-14 Thread Dick Moores
At 06:47 AM 8/14/2007, Kent Johnson wrote:
>Dick Moores wrote:
> > Kent Johnson posted this to Tutor list Aug 8, 2007
> > (<http://mail.python.org/pipermail/tutor/2007-August/056194.html>):
> >
> > 
> >  > Python provides you with a pseudo random number generator whose output
> >  > values are uniformly distributed between the input parameters.  What you
> >  > are dealing with in fish weights or test scores or other natural
> >  > phenomena is most likely a normal distribution. Check out Wikipedia's
> >  > normal distribution entry.  The math is really juicy. You may end up
> >  > with a recipe for the Python Cookbook.
> >
> > No need for all that, use random.gauss()
> >
> > Kent
> > 
> >
> > I hadn't noticed gauss was there in the Random module. I got to
> > wondering if I could graph the distribution. This code produces a
> > nice bell-curve-seeming curve (on its side). Takes about 80 secs to
> > run on my computer. To fit your situation, the length of the bars can
> > be shortened or lengthened by decreasing or increasing, respectively,
> > the divisor of gaussCalls in line 5, "barLengthAdjuster = 
> gaussCalls//2600".
> >
> > Dick Moores
> >
> > ==
> > from random import gauss
> > mean = 100
> > std = 10
> > gaussCalls = 1000
> > barLengthAdjuster = gaussCalls//2600
> >
> > d = []
> > for k in range(200):
> >  d.append([k, 0])
>
>This could be a list comprehension:
>d = [ [k, 0] for k in range(200) ]

So you recommend using list comprehensions wherever possible? (I sure 
wouldn't have thought of that one..)

>but there is no need to keep the array index in the array so this is
>simpler:
>
>d = [0] * 200
>
> > for k in xrange(gaussCalls):
> >  n = int(gauss(mean, std))
> >  d[n][1] += 1
>
>This becomes just
>   d[n] += 1
>
> >
> > for c in d:
> >  barLength = c[1]//barLengthAdjuster
> >  print barLength, "=", c[0], c[1]

By the time my code got into my post, I had changed "print barLength 
* "=", c[0], c[1]"  to  "print barLength, "=", c[0], c[1]", thinking 
upon reading it over that the "*" was a mistake. :-(   The code I 
didn't send DID make bars out of "="s.

>Use enumerate() to get the indices as well as the list contents. This
>version prints an actual bar as well:
>for i, count in enumerate(d):
>   barLength = count//barLengthAdjuster
>   print i, '*' * barLength, count

Ah, enumerate() is nice! I'd forgotten about it. And "*" IS better 
for bars than "=".

I prefer the index (or integer) to come after the bar ends, and 
before the count. One reason is that if the index is at the base of 
the bar, at 100 and above, the bars get pushed out one character 
longer than they should be relative to the 99 or less bars. I suppose 
there's a way to handle this, but I couldn't think of it then (but see below).

So this is my code now:


from random import gauss
mean = 100
std = 10
gaussCalls =100
barLengthAdjuster = gaussCalls//2600

d = [0] * 200

for k in xrange(gaussCalls):
 n = int(gauss(mean, std))
 d[n] += 1

for i, count in enumerate(d):
 barLength = count//barLengthAdjuster
 print '*' * barLength, i, count
=

This would solve the problem I mentioned above caused by putting the 
indices at the bases of the bars:

for i, count in enumerate(d):
 barLength = count//barLengthAdjuster
 if i < 100:
 print "%d  %s %d" % (i, '*' * barLength, count) # there are 
2 spaces between %d and %s
 else:
 print "%d %s %d" % (i, '*' * barLength, count)

Thanks very much, Kent, for taking the time to advise me on my code.

Dick 

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


[Tutor] Question re Tutor List Etiquette

2007-08-14 Thread Dick Moores
When sending a reply to a post, to the list, should we also address 
the reply to the author of the post to which we are replying? 
(There's gotta be an easier way to say that..) If we do so, then the 
author gets a duplicate of our reply.

I've run some statistics (but no more bar graphs ;-) ). My Eudora 
mailbox for Tutor contains 12,114 emails (I've deleted the duplicates 
I've received). Of these, 9,424 are replies. Of these replies, 4,338 
(46%) were addressed ONLY to the list. So 54% WERE also sent to the 
author being replied to.

Is there a rule about this? Or should one be made? Or does it matter?

Replying only to the list takes a bit of trouble. The default 
behavior seems to be that the "Reply" button addresses the author 
only and not the list; "Reply to all" addresses both the list, the 
author, and any others included in the To: or Cc: headers of the post 
being replied to. Or at least that's how Eudora and Gmail work.

Ten years ago or so I managed a Majordomo list, and I recall that it 
was possible for the list manager to configure the list to include a 
"Reply-To" header. If this would be possible for the admins to do 
with Tutor -- to include a "Reply-To: tutor@python.org" header in the 
posts sent out by the list, it would enable us to address a reply 
only to the list by hitting the "Reply" button.

Dick Moores

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


Re: [Tutor] Graphing the random.gauss distribution

2007-08-14 Thread Dick Moores
At 10:28 AM 8/14/2007, you wrote:
>Dick Moores wrote:
> > At 06:47 AM 8/14/2007, Kent Johnson wrote:
> >> This could be a list comprehension:
> >> d = [ [k, 0] for k in range(200) ]
> >
> > So you recommend using list comprehensions wherever possible? (I sure
> > wouldn't have thought of that one..)
>
>Not "whenever possible", no, but I find simple list comps (I count this
>one as simple) to be far more readable than the equivalent loop. Not
>only are they shorter but they read the way I think.
>
>If the list comp can't be easily written on one line, or has a complex
>condition, or has two for clauses, I find it less appealing and may
>write it as a for loop. I never use a list comp just for the
>side-effects; only when I actually want the list.

Got it.

> > I prefer the index (or integer) to come after the bar ends, and before
> > the count. One reason is that if the index is at the base of the bar, at
> > 100 and above, the bars get pushed out one character longer than they
> > should be relative to the 99 or less bars. I suppose there's a way to
> > handle this, but I couldn't think of it then (but see below).
>
>Use string formatting or str.rjust():
>In [1]: '%3d' % 10
>Out[1]: ' 10'
>In [2]: '%3d' % 100
>Out[2]: '100'
>In [4]: str(10).rjust(3)
>Out[4]: ' 10'

So:

for i, count in enumerate(d):
 barLength = count//barLengthAdjuster
 print "%3d %s %d" % (i, '*' * barLength, count)

Or:

for i, count in enumerate(d):
 barLength = count//barLengthAdjuster
 print str(i).rjust(3), '*' * barLength, count

Right? (Anyway, they work!)
Terrific! Two ways!


> > This would solve the problem I mentioned above caused by putting the
> > indices at the bases of the bars:
> >
> > for i, count in enumerate(d):
> > barLength = count//barLengthAdjuster
> > if i < 100:
> > print "%d  %s %d" % (i, '*' * barLength, count) # there are 2
> > spaces between %d and %s
> > else:
> > print "%d %s %d" % (i, '*' * barLength, count)
>
>Ouch. See above.

Ouch? No like? (I know, your 2 ways are both easier.)

Thanks much again, Kent.

Dick


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


Re: [Tutor] Question re Tutor List Etiquette

2007-08-14 Thread Dick Moores
At 11:56 AM 8/14/2007, Kent Johnson wrote:
>Dick Moores wrote:
> > When sending a reply to a post, to the list, should we also address
> > the reply to the author of the post to which we are replying?
> > (There's gotta be an easier way to say that..) If we do so, then the
> > author gets a duplicate of our reply.
>
>This is configurable for each subscriber. Go to the tutor web page at
>http://mail.python.org/mailman/listinfo/tutor
>
>Enter your subscription email at the bottom where it says, "To
>unsubscribe from Tutor, get a password reminder, or change your
>subscription options enter your subscription email address:"
>
>Set "Avoid duplicate copies of messages?" to Yes.

Great!

> > Ten years ago or so I managed a Majordomo list, and I recall that it
> > was possible for the list manager to configure the list to include a
> > "Reply-To" header. If this would be possible for the admins to do
> > with Tutor -- to include a "Reply-To: tutor@python.org" header in the
> > posts sent out by the list, it would enable us to address a reply
> > only to the list by hitting the "Reply" button.
>
>Surely you have been reading the list long enough to know that this
>comes up every three months as a topic!

No, you can't assume that because I'm a long-term subscriber that I 
have always faithfully read the list. If I had, I'd be much better at 
Python than I am!

>  It's not going to change. I'm
>not going to discuss it (and I hope no one else will either). Search the
>archives if you want to see previous discussions.

Well, I don't see that it's all that bad that I brought it up again. 
The newcomers undoubtedly will benefit from your advice, as I did. Or 
does the new welcome message mention how to avoid duplicate copies of 
messages? If not, it should.

Dick

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


Re: [Tutor] Python Book Recommendations

2007-08-15 Thread Dick Moores


At 04:38 PM 8/14/2007, Fiyawerx wrote:
My company has a subscription
with the books24x7.com site, and I'm
sure they offer individual accounts, but so far I'm ashamed that I've
paid close to 200$ worth of computer books that I could have been
accessing online for free. Including 'dummies' books, Teach yourself
whatever, and just a multitude of other books. Just did a quick search
for titles with 'python' and returned about 20. 
My public library system in the Seattle area
(<
http://www.kcls.org/>) has access to Books 24x7 for cardholders.
It seems there may be different classes of access, because I just
searched on 'python' in titles and got only 15 hits. The latest published
book is Python for Dummies (2006). And that's the ONLY Python book for
2006. 
Dick Moores




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


[Tutor] Need to convert 1,987,087,234,456 to an int

2007-08-15 Thread Dick Moores
If a line in a script has
n = "1,987,087,234,456"
It's simple to convert the string, "1,987,087,234,456" to an int, but 
I can't figure out how to do it for
n = 1,987,087,234,456  # no quotes
(I want to be able to type in big ints using commas--much easier to 
see that I've typed correctly)

Python sees 1,987,077,234,456 as a tuple:
 >>>type(1,987,077,234,456)


But:
 >>>type(1,987,087,234,456)
  File "", line 1
type(1,987,087,234,456)
^
SyntaxError: invalid token

(My wild guess is that 087 is octal.)

Anyway,

I need to convert things such as 1,987,077,234,456 to ints. This will do it:
(m can also be an int such as 1987077234456)
if type(m) == tuple:
 mAsStr = ""
 for part in m:
 part = str(part)
 mAsStr += part
 m = int(mAsStr)

So this is fine as long as none of the parts of the tuple is of the 
form 08X (where X is from 0-9). What to do?

Thanks,

Dick Moores



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


Re: [Tutor] Need to convert 1,987,087,234,456 to an int

2007-08-15 Thread Dick Moores
At 06:58 PM 8/15/2007, John Fouhy wrote:
>On 16/08/07, Dick Moores <[EMAIL PROTECTED]> wrote:
> > Python sees 1,987,077,234,456 as a tuple:
> >  >>>type(1,987,077,234,456)
> > 
>
>Hmm, not for me:
>
> >>> type(1,987,077,234,456)
>Traceback (most recent call last):
>   File "", line 1, in 
>TypeError: type() takes 1 or 3 arguments

Tried again just now, and I got what you got. However:

 >>>m = 1,987,077,234,456
 >>>type(m) == tuple
True


>What python are you using? (2.5.1 for me)

XP, Python 2.5, editor is Ulipad


> > I need to convert things such as 1,987,077,234,456 to ints.
>
>You could do this:
>
> >>> def decomma(*t):
>...  return int(''.join(str(i) for i in t))
>...
>
>Thus:
>
> >>> decomma(1,234,567)
>1234567

That's cool! However, it doesn't solve the problem in my original post.

 >>> t = 1,987,087,234,456
   File "", line 1
 t = 1,987,087,234,456
 ^
SyntaxError: invalid token

 >>> def decomma(*t):
   return int(''.join(str(i) for i in t))

 >>> decomma(1,987,087,234,456)
   File "", line 1
 decomma(1,987,087,234,456)
 ^
SyntaxError: invalid token

Dick


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


Re: [Tutor] Need to convert 1,987,087,234,456 to an int

2007-08-15 Thread Dick Moores
At 06:58 PM 8/15/2007, John Fouhy wrote:
>You could do this:
>
> >>> def decomma(*t):
>...  return int(''.join(str(i) for i in t))

What's that asterisk doing in decomma(*t)? Where do I go in the docs 
to look it up?

Thanks,

Dick


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


Re: [Tutor] Need to convert 1,987,087,234,456 to an int

2007-08-15 Thread Dick Moores
At 06:58 PM 8/15/2007, John Fouhy wrote:
>What python are you using? (2.5.1 for me)

2.5. If I install 2.51 will it install itself "over" my 2.5? Or will 
it set itself up in a separate Python 251 folder/directory?

Dick


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


Re: [Tutor] Need to convert 1,987,087,234,456 to an int

2007-08-15 Thread Dick Moores
To Eric Walker, John Fouhy, and  Eric Brunson:

Thanks very much. I think I'm beginning to get it. At least I was 
able to write a couple of functions that do what I wanted:

=
def f(n,m,*args):
 x = n*m
 for arg in args:
 product = arg*x
 x = product
 print product

numbers = 10, 6, 7

f(3,4,*numbers)

# --

def g(*args):
 n = 0
 for arg in args:
 sum = n + arg
 n = sum
 print sum

numbers = 10, 6, 7, 5, 100

g(*numbers)


They give me 5040 and 128, respectively.

Dick

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


Re: [Tutor] Python Book Recommendations [Was:[Re: Security]]

2007-08-15 Thread Dick Moores
At 05:48 PM 8/14/2007, Kent Johnson wrote:
>I also have a shortcut set up so if I type
>py modulename
>in the Firefox address bar it takes me directly to the docs for that
>module. To do this, create a bookmark with this URL:
>file://localhost/Users/kent/Library/Documentation/Python-Docs-2.5/lib/module-%s.html
>
>and give it the keyword 'py'.

Great tips, Kent! I especially appreciate this one.

Dick


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


Re: [Tutor] Need to convert 1,987,087,234,456 to an int

2007-08-16 Thread Dick Moores
At 02:41 AM 8/16/2007, Alan Gauld wrote:
>But Python 3000 is a semi mythical fancy that doesn't exist and may 
>never exist.
>It is where all the ills of Python will be cured. Saying it is in Python 3000
>is usually a synonym for it won't be "fixed" anytime soon!

But have you seen what Guido says?

"We're closing in on the first Python 3000 alpha release (promised 
for the end of August)."


Semi-mythical fancy?

Dick


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


Re: [Tutor] Python Book Recommendations [Was:[Re: Security]]

2007-08-17 Thread Dick Moores
At 08:19 AM 8/17/2007, Chris Calloway wrote:
>bhaaluu wrote:
> > Perhaps these concerns should be directed to either the
> > maintainers of Python.Org ( http://python.org/ ), or to
> > the author of the Software Carpentry Course?
>
>I sent a pointer both to the lead maintainer (Dr. Greg Wilson at Univ.
>Toronto) and to Titus Brown who, along with Chris Lasher, is having a
>Software Carpentry sprint at SciPy'07 at Caltech tomorrow. So this is a
>timely observation. :) Titus wrote back that it "sure does sound wrong,"
>so I would bet on it getting fixed tomorrow.
>
>SWC has been around since 1998. It started as an 800KUSD Dept. of Energy
>project at Los Alamos for a design competition with cash prizes. It
>resulted in several tools including Roundup and SCons. It received
>27KUSD in funding from the PSF in 2006. It is taught to scientists at
>Univ of Toronto, Indiana Univ, and Caltech. Dr. Wilson wrote about it in
>the magazine of Sigma Xi:
>
>http://www.americanscientist.org/template/AssetDetail/assetid/48548
>
>It has moved around a lot. It's current official home is on scipy.org:
>
>http://www.swc.scipy.org/
>
>There are several links to older SWC URLs on python.org. None of them
>are in the wiki where they could be easily fixed, however.

Chris, THANK YOU, especially for the link, <http://www.swc.scipy.org/>.

My thanks also to Alan, Wesley, and bhaaluu. What a great list Tutor is!

An appreciative noob,

Dick Moores

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


[Tutor] What is a "symbolic debugger"

2007-08-17 Thread Dick Moores
In the "Python Book Recommendations [Was:[Re: Security]]" thread, 
Chris Calloway included a link to the American Scientist article, 
"Where's the Real Bottleneck in Scientific Computing?". In that 
article I saw a term, "symbolic debugger", I  had been wondering 
about for a while. Google was of little help (to me, at least), and 
searching Wikipedia on "symbolic debugger" gets me the Debugger 
article "Redirected from Symbolic debugger". I'm beginning to think 
that the debugger I want to learn, WinPdb, is also a symbolic 
debugger, but what's "symbolic" about it?

Thanks,

Dick Moores


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


[Tutor] The Python 2.5 Quick Reference

2007-08-18 Thread Dick Moores
I was wondering if the Python 2.5 Quick Reference, by Richard Gruet, 
wouldn't make a suitable addition to a list of useful Python 
references. It seems to be very well-done to me. It comes in various 
forms. See http://rgruet.free.fr/. I find I prefer 
<http://rgruet.free.fr/PQR25/PQR2.5.html>. Using Firefox, I 
"captured"  this to my "ScrapBook" and open it with a shortcut key set to:
file:///C:/Documents%20and%20Settings/Riley/Application%20Data/Mozilla/Firefox/Profiles/7nl3fxen.default/ScrapBook/data/20070818011939/index.html

BTW Python.org references only a very early antecedent of this PQR, 
from 1995: <http://www.python.org/doc/QuickRef.html>. At least that's 
the only one I could find..

 From the "Front Matter" section of Python 2.5 Quick Reference:

Last modified on June 23, 2007
14 Dec 2006,
upgraded by Richard Gruet for Python 2.5
17 Feb 2005,
upgraded by Richard Gruet for Python 2.4
03 Oct 2003,
upgraded by Richard Gruet for Python 2.3
11 May 2003, rev 4
upgraded by Richard Gruet for Python 2.2 (restyled by Andrei)
7 Aug 2001
upgraded by Simon Brunning for Python 2.1
16 May 2001
upgraded by Richard Gruet and Simon Brunning for Python 2.0
18 Jun 2000
upgraded by Richard Gruet for Python 1.5.2
30 Oct 1995
created by Chris Hoffmann for Python 1.3

Dick Moores

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


Re: [Tutor] What is a "symbolic debugger"

2007-08-18 Thread Dick Moores
At 01:13 AM 8/18/2007, Alan Gauld wrote:

>"Dick Moores" <[EMAIL PROTECTED]> wrote
>
> > article I saw a term, "symbolic debugger", I  had been wondering
> > about for a while. Google was of little help (to me, at least), and
>
>Its a debugger that undestand symbols, in other words it can read
>the symbol table produced by a compiler/interpreter.

Ah. And that sent me to <http://en.wikipedia.org/wiki/Symbol_table>/


>Most debuggers nowadays are symbolic, but in the early days
>they weren't and you had to debug all code at the assembler/memory
>address level.
>
>If you want to have fun with that try loading a simple program into
>the DOS DEBUG command and stepping through it examining
>the memory image as you go., It is decidedly non symbolic!

Is that something I should be able to do on Win XP? Would I use debug 
 at the command line?

>Or on Linux/Unix you may be able to use adb. adb is often using
>for debugging core dumps from programs that haven't been
>compiled with the -g debug flag or have had the symbol table
>'strip'ed.
>
> > that the debugger I want to learn, WinPdb, is also a symbolic
> > debugger, but what's "symbolic" about it?
>
>Yes Python debuggers are all symbolic.
>They can understand your variable names etc so you can say
>
>break foo
>
>instead of
>
>break [0x25698567]

I'll take "break foo" any day.

Thanks very much, Alan!

Dick Moores
XP, Python 2.5, editor is Ulipad





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


Re: [Tutor] The Python 2.5 Quick Reference

2007-08-18 Thread Dick Moores
At 04:42 AM 8/18/2007, Kent Johnson wrote:
>Dick Moores wrote:
>>I was wondering if the Python 2.5 Quick Reference, by Richard 
>>Gruet, wouldn't make a suitable addition to a list of useful Python 
>>references.
>
>It has a link on the top-level documentation page at python.org:
>http://www.python.org/doc/

Ah, I see it now. Good.

BTW do you think the PQR is an accurate and useful reference, Kent?

Dick


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


Re: [Tutor] A fun puzzle

2007-08-23 Thread Dick Moores
At 07:34 PM 8/22/2007, Kent Johnson wrote:
>FWIW here is my fastest solution:
>
>01 from itertools import chain
>02 def compute():
>03  str_=str; int_=int; slice_=slice(None, None, -1)
>04 for x in chain(xrange(1, 101, 10), xrange(2, 101, 10),
>05 xrange(3, 101, 10), xrange(4, 101, 10), xrange(5, 101, 10),
>06 xrange(6, 101, 10), xrange(7, 101, 10), xrange(8, 101, 10),
>07 xrange(9, 101, 10)):
>08  rev = int_(str_(x)[slice_])
>09  if rev>=x: continue
>10 if not x % rev:
>11  print x,
>12 compute()

Kent, thanks for showing us itertools.chain(). By using it you keep x 
from being assigned an integer divisible by 10 (thereby faster), 
which of course means no need for

if n % 10 == 0:
 continue

Again faster.
And at first I thought your use of str_, int_, and slice_ were pretty 
weird; instead of your line 08, why not just use the straightforward

rev = int(str(x)[::-1])

but on upon testing I see they all make their respective 
contributions to speed.

But I don't understand why. Why is your line 08 faster than "rev = 
int(str(x)[::-1])"?

BTW I also thought that

for x in chain(xrange(1, 101, 10), xrange(2, 101, 10),
xrange(3, 101, 10), xrange(4, 101, 10), xrange(5, 101, 10),
xrange(6, 101, 10), xrange(7, 101, 10), xrange(8, 101, 10),
xrange(9, 101, 10)):
 pass

MUST take longer than

for x in xrange(100):
 pass

because there appears to be so much more going on, but their timings 
are essentially identical.

Dick Moores
XP, Python 2.5, editor is Ulipad

==
   Bagdad Weather
<http://weather.yahoo.com/forecast/IZXX0008_f.html> 

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


Re: [Tutor] A fun puzzle

2007-08-23 Thread Dick Moores
At 08:20 AM 8/23/2007, Kent Johnson wrote:
>Dick Moores wrote:
>>At 07:34 PM 8/22/2007, Kent Johnson wrote:
>>>FWIW here is my fastest solution:
>>>
>>>01 from itertools import chain
>>>02 def compute():
>>>03  str_=str; int_=int; slice_=slice(None, None, -1)
>>>04 for x in chain(xrange(1, 101, 10), xrange(2, 101, 10),
>>>05 xrange(3, 101, 10), xrange(4, 101, 10), xrange(5, 101, 10),
>>>06 xrange(6, 101, 10), xrange(7, 101, 10), xrange(8, 101, 10),
>>>07 xrange(9, 101, 10)):
>>>08  rev = int_(str_(x)[slice_])
>>>09  if rev>=x: continue
>>>10 if not x % rev:
>>>11  print x,
>>>12 compute()
>
>>And at first I thought your use of str_, int_, and slice_ were 
>>pretty weird; instead of your line 08, why not just use the straightforward
>>rev = int(str(x)[::-1])
>>but on upon testing I see they all make their respective 
>>contributions to speed.
>>But I don't understand why. Why is your line 08 faster than "rev = 
>>int(str(x)[::-1])"?
>
>Two reasons. First, looking up a name that is local to a function is 
>faster than looking up a global name. To find the value of 'str', 
>the interpreter has to look at the module namespace, then the 
>built-in namespace. These are each dictionary lookups. Local values 
>are stored in an array and accessed by offset so it is much faster.

Wow, what DON'T you understand?

Please explain "accessed by offset".

>Second, the slice notation [::-1] actually creates a slice object 
>and passes that to the __getitem__() method of the object being 
>sliced. The slice is created each time through the loop. My code 
>explicitly creates and caches the slice object so it can be reused each time.
>>BTW I also thought that
>>for x in chain(xrange(1, 101, 10), xrange(2, 101, 10),
>>xrange(3, 101, 10), xrange(4, 101, 10), xrange(5, 101, 10),
>>xrange(6, 101, 10), xrange(7, 101, 10), xrange(8, 101, 10),
>>xrange(9, 101, 10)):
>>  pass
>>MUST take longer than
>>for x in xrange(100):
>>  pass
>>because there appears to be so much more going on, but their 
>>timings are essentially identical.
>
>Well for one thing it is looping 9/10 of the number of iterations.

This time I added "xrange(10, end, 10)" and did the timing using the 
template in the timeit module:

template = """
def inner(_it, _timer):
 _t0 = _timer()
 from itertools import chain
 end = 100
 for _i in _it:
 for x in chain(xrange(1, end, 10), xrange(2, end, 10),
 xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10),
 xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10),
 xrange(9, end, 10), xrange(10, end, 10)):
 pass
 _t1 = _timer()
 return _t1 - _t0
"""
This gets always close to 71 msec per loop.


template = """
def inner(_it, _timer):
 _t0 = _timer()
 end = 100
 for _i in _it:
 for x in xrange(end):
 pass
 _t1 = _timer()
 return _t1 - _t0
"""
This gets always close to 84 msec per loop.

So they're not the same! And yours is the faster one! Because 
itertools.chain() is written in C, I suppose.

>  Also, chain() doesn't have to do much, it just forwards the values 
> returned by the underlying iterators to the caller, and all the 
> itertools methods are written in C to be fast. If you read 
> comp.lang.python you will often see creative uses of itertools in 
> optimizations.

I just did a search on "itertools" in the comp.lang.python group at 
Google Groups, and got 1,940 hits. <http://tinyurl.com/3a2abz>. That 
should keep me busy!

Dick



==
   Bagdad Weather
<http://weather.yahoo.com/forecast/IZXX0008_f.html>  

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


Re: [Tutor] A fun puzzle

2007-08-24 Thread Dick Moores
At 11:49 AM 8/23/2007, Kent Johnson wrote:
>Dick Moores wrote:
>>>Two reasons. First, looking up a name that is local to a function 
>>>is faster than looking up a global name. To find the value of 
>>>'str', the interpreter has to look at the module namespace, then 
>>>the built-in namespace. These are each dictionary lookups. Local 
>>>values are stored in an array and accessed by offset so it is much faster.
>>Wow, what DON'T you understand?
>
>Lots, actually :-) There is a whole 'nother tier or two of Python 
>expert above me that I can't touch. I just parrot back what I hear 
>them saying. :-)
>
>>Please explain "accessed by offset".
>
>IIUC an array is allocated on the call stack to hold references to 
>the local variables. (Anticipating you next question: 
>http://en.wikipedia.org/wiki/Stack_frame) To get the value of the 
>local variable the runtime just has to look up the correct entry in 
>the array. The bytecode has the offset into the array. This is very 
>quick - an indexed lookup.
>
>Normal attribute access such as a module or builtin has to read the 
>value out of a dict which is much more expensive, even with Python's 
>optimized dicts.

Thank you. Nice parroting. :-)


>>This time I added "xrange(10, end, 10)" and did the timing using 
>>the template in the timeit module:
>>template = """
>>def inner(_it, _timer):
>>  _t0 = _timer()
>>  from itertools import chain
>>  end = 100
>>  for _i in _it:
>>  for x in chain(xrange(1, end, 10), xrange(2, end, 10),
>>  xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10),
>>  xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10),
>>  xrange(9, end, 10), xrange(10, end, 10)):
>>  pass
>>  _t1 = _timer()
>>  return _t1 - _t0
>>"""
>>This gets always close to 71 msec per loop.
>>
>>template = """
>>def inner(_it, _timer):
>>  _t0 = _timer()
>>  end = 100
>>  for _i in _it:
>>  for x in xrange(end):
>>  pass
>>  _t1 = _timer()
>>  return _t1 - _t0
>>"""
>>This gets always close to 84 msec per loop.
>>So they're not the same! And yours is the faster one! Because 
>>itertools.chain() is written in C, I suppose.
>
>That is very strange. I did a simple timer with time.time() and 
>found that my original (1-9) version was consistently a little 
>slower than the simple xrange(). And xrange is written in C too, and 
>the chain version adds a layer over xrange. You should check your 
>code carefully, that is a very surprising result.

Yes, surprising. But the templates pasted above are exactly what I 
used in 2 copies of timeit.py. I don't know what to check. Can you 
see what's wrong?  I just ran both of those again, with very similar results.

Following your lead I've now done some timing using time.time():

==
from __future__ import division
from itertools import chain
import time

end = 100
timeTotal = 0
for c in range(100):
 timeStart = time.time()
 for x in chain(xrange(1, end, 10), xrange(2, end, 10),
 xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10),
 xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10),
 xrange(9, end, 10), xrange(10, end, 10)):
 pass

 timeEnd = time.time()
 timeElapsed = timeEnd - timeStart
 timeTotal += timeElapsed
avgTime = timeTotal/c
print "with chain avgTime was %.4g seconds" % avgTime

"""
results of 5 runs:
with chain avgTime was 0.2072 seconds
with chain avgTime was 0.1916 seconds
with chain avgTime was 0.1913 seconds
with chain avgTime was 0.1921 seconds
with chain avgTime was 0.1915 seconds
(avg is 0.1947 seconds)
"""
=

=
from __future__ import division
import time
end = 100
timeTotal = 0
for c in range(100):
 timeStart = time.time()
 for x in xrange(end):
 pass
 timeEnd = time.time()
 timeElapsed = timeEnd - timeStart
 timeTotal += timeElapsed
avgTime = timeTotal/c
print "no chain avgTime was %.4g seconds" % avgTime

"""
results of 5 runs:
no chain avgTime was 0.2104 seconds
no chain avgTime was 0.2109 seconds
no chain avgTime was 0.1946 seconds
no chain avgTime was 0.1948 seconds
no chain avgTime was 0.1946 seconds
(avg is 0.2011 seconds)
"""
=
When I ran the above 2 scripts, I alternated between them. Don't 
really see that one is decisively faster than the other.

Dick



==
   Bagdad Weather
<http://weather.yahoo.com/forecast/IZXX0008_f.html> 

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


  1   2   3   4   5   6   >