[Tutor] Running program from Python

2007-07-20 Thread Chris Smith
Howdy,

I am working on some research. I'm trying to optimize the performance of 
an antenna. For the simulation of the antenna it would be easiest to use 
an antenna software package that I have in my lab. I know that Matlab 
can call the antenna software through a command called system. Matlab 
also uses system to pass a VB script file to the antenna software that 
tells the software what to do. However, I don't have access to Matlab in 
my lab.

I use Python for a lot of program prototyping, and was looking through a 
Python reference book to see if there was something in there I could 
use. I ran across two functions that I thought might work. They are in 
the os module and are the different exec functions and also the spawnv 
function.

The python program would run something like this:
1) optimization program comes up with initial variables to try
2) a VB script is generated
3) antenna program called and given the VB script
4) antenna program evaluates the antenna
5) results are sent back to optimization program
6) optimization program evaluates results and generates new variables
7) process from 2 on is repeated

Would either of these two functions be what I need?

Thanks for your help.

Chris S.

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


[Tutor] Running another program from Python

2007-07-20 Thread Chris Smith
Howdy,

I am working on some research. I'm trying to optimize the performance of 
an antenna. For the simulation of the antenna it would be easiest to use 
an antenna software package that I have in my lab. I know that Matlab 
can call the antenna software through a command called system. Matlab 
also uses system to pass a VB script file to the antenna software that 
tells the software what to do. However, I don't have access to Matlab in 
my lab.

I use Python for a lot of program prototyping, and was looking through a 
Python reference book to see if there was something in there I could 
use. I ran across two functions that I thought might work. They are in 
the os module and are the different exec functions and also the spawnv 
function.

The python program would run something like this:
1) optimization program comes up with initial variables to try
2) a VB script is generated
3) antenna program called and given the VB script
4) antenna program evaluates the antenna
5) results are sent back to optimization program
6) optimization program evaluates results and generates new variables
7) process from 2 on is repeated

Would either of these two functions be what I need?

Thanks for your help.

Chris S.

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


Re: [Tutor] Pmw BLT help

2007-03-25 Thread Chris Smith
Alan Gauld wrote:
 Chris Smith [EMAIL PROTECTED] wrote
 
 
I'm trying to learn how to use Pmw.BLT
 
 
line 16, in __init__
self.vector_x = Pmw.Blt.Vector()
  File C:\Python24\lib\site-packages\Pmw\Pmw_1_2\lib\PmwBlt.py, 
line
99, in __init__
self.tk.call(_vectorCommand, 'create', self._name)
TclError: invalid command name ::blt::vector

I've read over the installation instructions and even reinstalled 
the
software and that didn't help any. Could anyone help me out?
 
 
 I don't use PMW but its saying there is no such command as Vector.
 Are you sure PMW is installed OK? Have you got any of the
 other commands to work? Is the case OK?
 
 Just some ideas,
 
 Alan G.
I know I've installed Pmw ok since all I do for installation is unpack 
it and put in into the site-packages folder in the python installation. 
I think the problem is when Pmw is trying to reference BLT which is 
supposed to be installed with Tcl (it's an extension of some kind), but 
I can't find any BLT troubleshooting help.

C. Smith

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


[Tutor] Pmw BLT help

2007-03-24 Thread Chris Smith
I'm trying to learn how to use Pmw.BLT to have plotting in some GUIs I 
would like to create. I have a book with some examples but when I run 
the code I get this error message which seems to be related to the 
packages I installed and not my code:

Traceback (most recent call last):
   File C:\Documents and Settings\Chris  Esther\My 
Documents\Python\Booksrelatedcode\Python4ComputationalScience\src\py\gui\plotdemo_blt.py,
 
line 105, in ?
 blt = BltDemo1(root)
   File C:\Documents and Settings\Chris  Esther\My 
Documents\Python\Booksrelatedcode\Python4ComputationalScience\src\py\gui\plotdemo_blt.py,
 
line 16, in __init__
 self.vector_x = Pmw.Blt.Vector()
   File C:\Python24\lib\site-packages\Pmw\Pmw_1_2\lib\PmwBlt.py, line 
99, in __init__
 self.tk.call(_vectorCommand, 'create', self._name)
TclError: invalid command name ::blt::vector

I've read over the installation instructions and even reinstalled the 
software and that didn't help any. Could anyone help me out?

C. Smith

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


[Tutor] numpy help

2006-11-03 Thread Chris Smith

Howdy,

I'm a college student and for one of we are writing programs to 
numerically compute the parameters of antenna arrays. I decided to use 
Python to code up my programs. Up to now I haven't had a problem, 
however we have a problem set where we are creating a large matrix and 
finding it's inverse to solve the problem. To invert the matrix I've 
tried using numpy.numarray.linear_algebra.inverse and 
numpy.oldnumeric.linear_algebra.inverse which both give me the same 
error ( I was hoping they called different routines but I think they 
call the same one ).



This is the error message I receive:

Traceback (most recent call last):
  File C:\Documents and Settings\Chris  
Esther\Desktop\636_hw5_2\elen636_hw5_2.py, line 60, in module
matrix_inverse = 
numpy.numarray.linear_algebra.generalized_inverse(matrix)
  File 
C:\Python25\lib\site-packages\numpy\oldnumeric\linear_algebra.py, line 
59, in generalized_inverse

return linalg.pinv(a, rcond)
  File C:\Python25\lib\site-packages\numpy\linalg\linalg.py, line 
557, in pinv

u, s, vt = svd(a, 0)
  File C:\Python25\lib\site-packages\numpy\linalg\linalg.py, line 
485, in svd

a = _fastCopyAndTranspose(t, a)
  File C:\Python25\lib\site-packages\numpy\linalg\linalg.py, line 
107, in _fastCopyAndTranspose

cast_arrays = cast_arrays + (_fastCT(a.astype(type)),)
TypeError: can't convert complex to float; use abs(z)



I've tried inverting small complex matrices and it worked fine. Does 
anyone know why it won't work for this larger matrix? Any ideas how I 
can work around this problem and get the correct inverse matrix?


Chris

P.S. elen636_math.py is my personal library of functions I've create to 
solve the problem while elen636_hw5_2.py is the program that I'm 
actually running
# Purpose:
# This is a library of functions for ELEN 636 that
# so far has the ability to calculate the Sine and
# Cosine integrals as well as the mutual impedance
# between two parallel antennas.
#
# Author: Christopher Smith
# E-mail: [EMAIL PROTECTED]
# Date:   10/30/2006

###
### NOTE: The functions below for the sine and cosine integrals are similar
###   to the functions I turned in for homework assignment 4 problem 6
###   except that I added the ability to check for convergence.
###   I also added the factor into the mutual impedance formula so that the
###   answer is given in terms of the terminal input impedance instead of
###   the loop impedance as it was formerly giving.
###

# depends on the math library
from math import *
import numpy.numarray, numpy

def factorial(n):

This function calculates the factorial of a number.

sum = 1.0
for m in range(1, int(n)+1):
sum = float(m)*sum
return sum

def Si(x):

This function computes the sine integral. It uses a power series
expansion that can be found in Abramowitz and Stegun's math
functions reference book.

start = 0.0
stop = 10.0
sine_int = 0.0
convergence = 1.0*10**(-6)   # want to have the difference between
 # the last run and this run below
 # this value
while 1:
for n in range(int(start), int(stop)):
n = float(n)
sine_int += ((-1)**n)*x**(2*n +1)/((2*n+1)*factorial(2*n+1))
sine_int_new = sine_int + ((-1.)**stop)*x**(2.*stop 
+1.)/((2.*stop+1.)*factorial(2.*stop+1.))
converge_check = sine_int_new - sine_int
if abs(converge_check)  convergence:
break
else:
start = stop
stop += 5.0
return sine_int_new

def Ci(x):

This function computes the cosine integral. It uses a power series
expansion that can be found in Abramowitz and Stegun's math
functions reference book.

start = 1.0
stop = 10.0
convergence = 1.0*10.**(-6)   # want to have the difference between
 # the last run and this run below
 # this value
# The first number in the sum is Euler's constant to 10 digits
cosine_int = 0.5772156649 + log(x)
while 1:
for n in range(int(start), int(stop)):
m = float(n)
cosine_int = cosine_int +((-1)**m)*x**(2*m)/((2*m)*factorial(2*m))
cosine_int_new = cosine_int + 
((-1)**stop)*x**(2*stop)/((2*stop)*factorial(2*stop))
converge_check = cosine_int_new - cosine_int
if abs(converge_check)  convergence:
break
else:
start = stop
stop += 5.0
#print stop
return cosine_int_new


def mutual_impedance(length1_tot, length2_tot, stagger, d):

This function computes the mutual impedance between two antennas
for the Parallel in Echelon Configuration. The formulas are taken
from a paper by Howard King, Mutual Impedance of Unequal Length
Antennas in Echelon

NOTE: all 

Re: [Tutor] error help

2006-10-07 Thread Chris Smith
Thanks for the help. That was the problem. I guess I'd been looking at 
it so long I missed that. The error message wasn't helping me either.

Chris Smith

Geoframer wrote:
 The main problem from what i can tell is that the number of '(' and ')' 
 you use in declarations (and maybe even functions) are not correct.
 
 Take for instance :
 
 u0prime  = beta*(sqrt(d**2 +(h +length1)**2) - h +length1))
 
 You open 3 '(' and close 4 ')' .
 
 The problem is not the little test code at the end (as you illustrated 
 yourself by moving it up and getting a different error).
 The Token Error: EOF in multi-line statement usually means you made an 
 error using too many or too little ()'s.
 
 I suggest carefully re-examining your code and check if everything is 
 entered correctly using the right amount of ()'s ;-)
 
 Hope this helps some.
 
 Ciao - Geofram
 
 On 10/7/06, *Chris Smith* [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] 
 wrote:
 
 I'm writing a numerical program for an assignment at school. So the code
 of my program isn't too long I've coded the formulas, which are rather
 long, as funcions. However when I try to run my program I keep getting
 one of two errors. The first happens when I do a test run of my code
 with the test portion of the code at the bottom. It keeps popping up an
 error message that says that my import statement is spaced incorrectly.
 It's not supposed to be indented at all and I can't figure out why it's
 popping up at all. If I try moving the test portion of the code up to
 the top it gives me Token Error: EOF in multi-line statement. I don't
 understand this one because I try to have the last line be the one with
 the return statement of my last function and when the error happens it
 adds a line to my code and the error pops up.
 
 Can anyone tell me why I'm having these error or what I can do to get
 around them?
 
 Chris Smith
 
 
 #Functions for Numerical Program
 #--
 ### The sine and cosine integrals are taken from Abramowitz and Stegun.
 ### Only use the first 6 terms of the summation in the sine and cosine
 ### integrals.
 
 
 def Si(x):
 sine_integral = x - x**3/18. + x**5/600. - x**7/35280. \
 + x**9/3265920. + x**11/439084800.
 return sine_integral
 
 def Ci(x):
 # Euler's constant
 Euler_const = 0.5772156649
 
 cosine_integral = Euler_const + log(x) - x**2/4. + x**4/96. \
   - x**6/4320. + x**8/322560. + x**10/36288000
 return cosine_integral
 
 
 def Mutual_impedance(length1, length2, stagger, d):
 
 Mutual impedance formulas for Parallel in Echelon Configuration
 The formulas are taken from a paper by Howard King, Mutual
 Impedance
 of Unequal Length Antennas in Echelon
 
 NOTE: all measurements should be entered in wavelengths
 
 
 # stagger (this is the vertical separation between antenna centers)
 # d (this is the horizontal separation between the antennas)
 # length1 and length2 (this is the half length of the antennas)
 
 # vertical separation between center of antenna 1 and bottom of
 antenna 2
 h = stagger - length2
 
 # wave propagation constant and eta
 beta = 2*pi
 
 # formulas to put into mutual impedance equation
 u0   = beta*(sqrt(d**2 +(h -length1)**2) +(h -length1))
 v0   = beta*(sqrt(d**2 +(h -length1)**2) -(h -length1))
 u0prime  = beta*(sqrt(d**2 +(h +length1)**2) - h +length1))
 v0prime  = beta*(sqrt(d**2 +(h +length1)**2) +(h +length1))
 u1   = beta*(sqrt(d**2 +(h -length1 +length2)**2) +(h
 -length1 +length2))
 v1   = beta*(sqrt(d**2 +(h -length1 +length2)**2) - h
 -length1 +length2))
 u2   = beta*(sqrt(d**2 +(h +length1 +length2)**2) -(h
 +length1 +length2))
 v2   = beta*(sqrt(d**2 +(h +length1 +length2)**2) +(h
 +length1 +length2))
 u3   = beta*(sqrt(d**2 +(h -length1 +2*length2)**2) +(h
 -length1 +2*length2))
 v3   = beta*(sqrt(d**2 +(h -length1 +2*length2)**2) -(h
 -length1 +2*length2))
 u4   = beta*(sqrt(d**2 +(h +length1 +2*length2)**2) -(h
 +length1 +2*length2))
 v4   = beta*(sqrt(d**2 +(h +length1 +2*length2)**2) +(h
 +length1 +2*length2))
 w1   = beta*(sqrt(d**2 +h**2) -h)
 y1   = beta*(sqrt(d**2 +h**2) +h)
 w2   = beta*(sqrt(d**2 +(h +length2)**2) -(h +length2))
 y2   = beta*(sqrt(d**2 +(h +length2)**2) +(h +length2))
 w3   = beta*(sqrt(d**2 +(h +2*length2)**2) -(h +2*length2))
 y3   = beta*(sqrt(d**2 +(h +2*length2)**2) +(h +2*length2))
 
 R12 = 15*(cos(beta*(length1 - h))*(Ci(u0) +Ci(v0) -Ci(u1)
 -Ci(v1)) \
   +sin(beta*(length1 - h))*(-Si(u0

Re: [Tutor] Removing lines in string-table

2005-05-17 Thread Chris Smith

On Tuesday, May 17, 2005, at 08:35 America/Chicago, 
[EMAIL PROTECTED] wrote:

 I have a string table (don't recall the right word used in Python
 right now) and would like to remove every 'cell' that contains a
 string '_thumb.jpg'. There are 1- digits before the string if that
 matters. I made a for-loop that does what I want to:

 for line in fileNames:
 if line[-10:] == '_thumb.jpg':
 fileNames.remove(line)

 But I really doubt that it's not the best way to do this. So, any
 comments are really appreciated.


The above will not work if two successive lines contain the target 
text. When you remove the one, its neighbor slides over to take the 
place of the one removed and then when you proceed to the next line 
you are actually skipping the one that slid over.  This could be 
remedied with using indices to access the list, but perhaps a better 
approach is to use filter or a list comprehension to remove the target 
lines:

###
def myfilter(x):
return not x.endswith('_thumb.jpg')
fileNames =filter(myfilter, fileNames)

# OR

fileNames =[x for x in fileNames if not x.endswith('_thumb.jpg')]
###

/c

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


Re: [Tutor] help

2005-05-11 Thread Chris Smith

On Wednesday, May 11, 2005, at 08:09 America/Chicago, 
[EMAIL PROTECTED] wrote:

 hi
 i'm trying to extend a list program by adding a test, problem is after
 getting the menu of taking the test i can't seem to get the test 
 running
 i.e viewing of questions and answers. here's what i tried to do
 menu_item = 0
 list = []
 while menu_item !=9:
print -
  print 1. print the questions
print 2. take the test
print 3. quit
menu_item = input(pick an item from the menu: )


Hi Feziwe,

If you are trying to modify someone else's code, then the work that you 
would have done to write it now has to go into trying to understand 
what they have already done. Not to lecture too much, but if you didn't 
write it then work through it piece by piece to see how it works.  What 
you will notice that relates to your problem is that there is a 'while' 
loop that requires a menu_item to be not equal to 9.  Since your menu 
never asks the user to enter a 9, you will never get out of that loop.  
Also, check to see what *does* happen when a 2 is pressed: if there is 
not an instruction to call a function, then the instructions in that 
part of the 'if...elif...else' section will be done and the 'while' 
loop will resume (since menu_item was not 9.

Does this get you started toward understanding the problem?

/c

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


Re: [Tutor] character format

2005-05-11 Thread Chris Smith

On Wednesday, May 11, 2005, at 20:43 America/Chicago,  
[EMAIL PROTECTED] wrote:

 I believe Max's guess was that the file is compressed with bzip (the  
 first
 two characters will be BZ, as you found).  Try doing:

 import bz2
 print bz2.decompress(data)

 Where data is a string containing the characters you have.  (Although  
 you
 say that compression is unlikely, the BZ characters would be a big
 co-incidence).


That interactive mode is *very* helpful.  If you import a module and  
then do a directory on it to see what it has for tools and then start  
playing with them, you can learn some interesting things without a lot  
of overhead:

###
  import bz2
  dir(bz2)
['BZ2Compressor', 'BZ2Decompressor', 'BZ2File', '__author__',  
'__doc__', '__file__', '__name__', 'compress', 'decompress']
  bz2.compress('foo')
BZh91AYSYI\xfe\xc4\xa5\x00\x00\x00\x01\x00\x01\x00\xa0\x00!\x00\x82,]\ 
xc9\x14\xe1BA'\xfb\x12\x94
  bz2.decompress(_) #underscore to reference last thing
'foo'
###

Hmmm...

/c

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


Re: [Tutor] Tutor Digest, Vol 15, Issue 21 (python.org: trusted sender for your account)

2005-05-09 Thread Chris Smith

On Monday, May 9, 2005, at 15:45 America/Chicago, 
[EMAIL PROTECTED] wrote:

 Actually, perhaps this is something you guys would know about! In your
 own learning python (or as you watched others learn, if you're one of
 the resident experts), have you come across some good challenges for
 python learners?



The ACM Programming problems are archived at

http://www.acm.inf.ethz.ch/ProblemSetArchive.html

These are tasks on which one's python tool may be sharpened.

/c

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


Re: [Tutor] Python Challenge - Riddle 2

2005-05-09 Thread Chris Smith

 Am I looking for something like this -

 XXXjXXX? or something like XjXX or XXjX?

The former: 3 on each side. Exactly 3.

BTW wink, you can check your understanding by saving the image you 
get from riddle 6, compressing it with zlib, filtering out all but 
string.letters and looking for the same pattern as in riddle 2. You 
should come up with scdehtinjgu...but that's a 404 for a web page.

/c

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


Re: [Tutor] elegant way to turn list into string

2005-05-07 Thread Chris Smith
 while x  26:
 new_alph = alph[1:] + alph[:1]
 print new_alph
 print \n
 x += 1

 But this has the drawback of not progressing with my
 newly create alphabet, it just returns:
 abcdefghijklmnopqrstuvwxyz

The reason that new_alph never changes is that you are calculating it 
from the same (unchanging) thing every time.  The value of alph never 
changes in your loop, so the value of new_alph is always the same.

Others have given suggestions as to what else you might do, but a fix 
for the above loop is to replace the word new_alph with alph.

/c

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


Re: [Tutor] Python challenges

2005-05-06 Thread Chris Smith

On Thursday, May 5, 2005, at 19:33 America/Chicago, 
[EMAIL PROTECTED] wrote:

 Anyone have a gentle hint, or pointer to another 'beginner' tutorial
 to regular expressions?

 Thanks! I dont want to get stuck here in the riddles!


How about counting how many times each character is used and look for 
the ones that are used infrequently (like only once). Dictionaries can 
do this.

/c

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


Re: [Tutor] Python challenges

2005-05-06 Thread Chris Smith

 Anyone have a gentle hint, or pointer to another 'beginner' tutorial
 to regular expressions?

 Thanks! I dont want to get stuck here in the riddles!


 How about counting how many times each character is used and look for 
 the ones that are used infrequently (like only once). Dictionaries can 
 do this.


Oops! Please disregard this irrelevant advice.

wishin-for-an-unsend,
/c

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


Re: [Tutor] No Need to press Enter

2005-05-04 Thread Chris Smith
 From: Joseph Quigley

 What is the secret to have the user press the Q key, and the program
 exits without pressing the Enter key?
 Or the Control and Q keys to exit?
 For the Macintosh, would the same command/s for Control Q keys be the
 same as the Apple Q key?


I see that Diane has suggested (what I believe to be) a pyGame 
solution.  I had asked this question before and Danny Yoo wrote up a 
script that is posted at

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892

With the modifications that I added (just before sending this) the code 
there has the ability to get the getch() behavior (not having to press 
enter) on the Mac (whether you are running under the pythonIDE or the 
Terminal), Windows, or Unix.

An example of usage (assuming that the code is stored in a file named 
getch.py) might be,

###
import getch
inkey = getch._Getch()
print 'Press any key to end'
while inkey()=='':
pass
print 'ok'
###

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


Re: [Tutor] tokenize row numbering

2005-05-03 Thread Chris Smith

 From: Andrei project5 at redrival dot net

 ###
 # line 1 according to tokenize tuple
 # line 2
 a=b #line 3
 ###

 Does anyone have an idea of *why* the rows/physical lines of code
 beginning their count at 1 instead of 0? In order to process the code 
 I

 The snippet above shows that numbering begins at 0, with the fourth 
 line having
 number 3. So either I misunderstand the question, or the snippet is 
 confusing.


Sorry, don't count the ### which are snippet delimiters.  Here's 
another example I ran before sending this: for the single line program,

print hello, world

This is what comes back from the tokenizer:

NAME 'print' (1, 0) (1, 5)
STRING 'hello, world' (1, 6) (1, 20)
ENDMARKER '' (2, 0) (2, 0)

It shows that 'print' starts at position 1,0 whereas if I were to 
number the rows like I numbered the columns, it would be at position 
0,0.

I was just wondering if someone knew a good reason for this, otherwise 
I would submit it as a feature change at source forge. But I'm not sure 
how long this behavior has been around and if people actually use this 
information.  I did, but what I ended up doing was adding 1 to every 
row position returned by the tokenizer.

/c

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


[Tutor] Re: input() : part two

2005-04-30 Thread Chris Smith
I found a work around for the terminal it appears that the message in
the input(message)  was being assigned to the next variable making
Matrix=error=alpha
It's good to see that you got this working.  Just a couple notes:
1) Regarding your comment above, it just *looks* like it was doing an  
assignment because of the = that you had for the Matrix and error  
prompt strings. If you had used the prompt ? instead, the first line  
of the file would have been ???.  One way you could also get around  
this is being interpreted in your program is to print a # before  
doing any input:

###
print #, # note the comma which keeps the output on the same line.
Matrix = input(Matrix=)
error = input(error=)
alpha = input(alpha=)
###
This would produce # Matrix=error=alpha= in your redirected output.
2) Also, it is possible to do a redirect from the IDE by just opening  
a file and then redirecting output to this file:

#--- 
--
# normal output
fav_number = input(What is your favorite number?)

# output redirected to file
import sys
file_name = 'myCode.py'
file = open(file_name, 'w') #careful; this overwrites an already  
existing file
old_stdout = sys.stdout #let's remember where we *were* sending  
output
sys.stdout = file   #now everything that gets printed will  
go the the file

print print 'my favorite number is',,fav_number
file.close()#close the file
sys.stdout = old_stdout #restore the output
# normal output again
print Now open and run,file_name
#--- 
--
'''--the output--
What is your favorite number?42
Now open and run myCode.py
   --end output--'''

In the file that was created there is a single line that, for this  
case, says

###
print 'my favorite number is', 42
###
If it starts to get tricky keeping track of what is being printed to  
the program, you might want to check out the string interpolation  
module that allows you to substitute in variables from your main script  
just by putting a $ before the variable name in a string (e.g.
this:
	printpl(print 'The favorite number is $fav_number')
will make (with the input from above):
	print 'The favorite number is 42'

The module and demos are at http://lfw.org/python/Itpl.py
Best regards,
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: input()

2005-04-29 Thread Chris Smith
On Friday, Apr 29, 2005, at 09:48 America/Chicago, 
[EMAIL PROTECTED] wrote:

Hello and  thanks in advance.
I am trying to prompt the user for some input. I need three values
from the user so,I used input() like so;
Matrix = input(Matrix=)
error=input(error=)
alpha= input(alpha=)
  using  Macpython it works fine but when I use a terminal all I get is
a blank line. When I try to enter at the command line I get this
Matrix=error=alpha=
Also I need to redirect any output from the program into another file,
which is why I used the terminal in the first place. So, I guess I have
two problems
1. How do I redirect output using Macpython?
2. How do I use input() while using a terminal?
It seems to work fine here for me, but I'm not sure what you are trying 
to do.  I'm using Python 2.4 under OS 10.2.8.  Perhaps you could paste 
a copy of the terminal prompts as they appear?  Here is what my session 
looked like when I entered 12 and 4 for two inputs:

###
csmith% cat go.py
a=input('a=')
b=input('b=')
print a,b
csmith% python go.py
a=12
b=4
12 4
###
If I make a file and feed it to the program rather than entering the 
text by hand I get:

###
csmith% cat  dat
12
4
^C
csmith% python go.py  dat
a=b=12 4
###
If I try to redirect this to a file I get:
###
csmith% python go.py  dat  out
csmith% cat out
a=b=12 4
###
One thing you might try is to change your prompt from something like 
a= to a=\n

Which of the above scenarios are you trying to work with and what do 
you want the result to be? It looks like the input to input() is not 
echoed so you should do that yourself if you want the values the user 
entered to be displayed in the file/output. e.g.

###
csmith% cat go2.py
def echoInput(prompt=):
  ret = input(prompt)
  print ret
  return ret
a=echoInput('a=')
b=echoInput('b=')
print a,b
csmith% python go2.py  dat  out
csmith% cat out
a=12
b=4
12 4
###
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] tokenize row numbering

2005-04-29 Thread Chris Smith
I got over my intimidation with tokenize and learned to use it to strip 
comments from code files.  In the process, I learned that the tuples 
that it returns for the position in the code of various tokens is 
1-based in the row rather than 0-based, so the tuple pair (3,1),(3,2) 
would be the start and stop position of the = OP in the following 
code:

###
# line 1 according to tokenize tuple
# line 2
a=b #line 3
###
Does anyone have an idea of *why* the rows/physical lines of code 
beginning their count at 1 instead of 0? In order to process the code I 
either have to subtract 1 from all the first elements of tuple 
positions or else insert a blank line at the beginning of the list that 
I make out of my code when I want to process it.

Is this a candidate for a feature change request?
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] enumerate offset?

2005-04-29 Thread Chris Smith
Does anybody else ever run into the case of using enumerate on a slice 
but then wish that the original list indices were being returned 
instead of the ones starting at zero?

I would like to see an offset argument that could be used with 
enumerate:

###
l=range(5)
for i,li in enumerate(l[3:]):
print i, li
def myenumerate(l,offset=0):
for i,li in enumerate(l):
yield i+offset, li
print
for i,li in myenumerate(l[3:],3):
print i,li
###
'''--the output--
0 3
1 4
3 3
4 4
   --end output--'''
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] CLS?

2005-04-25 Thread Chris Smith
I have this in my misc library.  It was my last attempt at unifying the 
cls function snippets that I got when I asked about this question some 
time ago (check the ASPN tutor archives for 'cls').  After adding 
darwin to the test for the system (instead of just 'mac') I got it to 
work from a script written and executed in pythonIDE for 2.3.3.  Does 
it work for you in your context?  (Note: it ends with the white paper 
method if all else fails.)

###
#--
def isInteractive():
Returns 1 if we're running in an interpreter window, and false
otherwise.This is a variation of what
pydoc.help() tries. If it doesn't work it might be because the
None, 1, ? is occuring on a different line.  One might consider
the following approach instead:
for li in inspect.stack():
if li[1:4] == (None, 1, ?):
return 1

#return inspect.stack()[2][1:4] == (None, 1, ?)
# the line above will enable the math if called on the 1st line of 
a script

#return inspect.stack()[3][1].find(PyInteractive)0
# but if this encounters a None at that position it will not be able
# to use the find function. SO...let's just look through the 
whole stack
import inspect
return str([x[1] for x in inspect.stack()]).find(PyInteractive)-1

#--
def cls():
A function to clear the output window.
import sys,os
if sys.platform in ['mac', 'darwin']:
if isInteractive():
import PyConsole
PyConsole.console.clearbuffer()
print
else:
print #in case the window is not open yet
sys.stdout.clearbuffer()
else:
try:
os.system('cls')
except:
try:
os.system('clear')
except:
try:
print
sys.stdout.write(os.popen(clear).read())
except:
print '\n'*80
###
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: [Pythonmac-SIG] Weird import problem with PythonIDE on Mac (was 'import problem')

2005-04-22 Thread Chris Smith
On Friday, Apr 22, 2005, at 03:52 America/Chicago, Just van Rossum - 
[EMAIL PROTECTED] wrote:

Importing __main__ is a very silly thing to do anyway, if you ask me.
All comments from you, Bob, and Jack have been *very* helpful.  I think 
I understand better what is going on.  What's got me scratching my head 
is that I thought it worked several at one time, but I must have been 
misunderstanding what script was actually being run. (?)

Anyway, as to importing from main, I was trying to learn to use the 
timeit module and wanted to be able to pass functions to it (rather 
than literal strings of code).  The init of timeit takes the strings 
you pass and creates a function that is exec'ed.

Do you have a suggestion as to what can I give a module so it has 
enough information to execute a function that resides in __main__? Here 
is a visual of what is going on:

--__main__
def y1():
  pass
import foo
foo.run(string_from_main) #what should I pass?
--external module, foo
def run(string_from_main):
#
exec(string_from_main) #y1 is run as if it were in __main__
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Weird import problem with PythonIDE on Mac (was 'import problem')

2005-04-21 Thread Chris Smith
###
def y1():
pass
def foo():
from __main__ import y1
pass
foo()
###
Here is a version of the code, stripped of the timeit code.  The above 
segment exhibits the same symptoms as the previously submitted one.

Even though I am running this as __main__ it behaves as though it is 
not __main__. i.e. if I run this with pyOxide without the 'run as 
__main__' option, it generates the same ImportError ('Can't import y1') 
as it does when run in the PythonIDE.

In the pythonIDE it generates the error whether the 'run as __main__' 
option is on or off. As a test of that option, I verified that the 
following code only runs when the __main__ option is on and it worked 
as expected:

###
if __name__=='__main__':
print 'running as main'
###
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Weird import problem with PythonIDE on Mac (was 'import problem')

2005-04-20 Thread Chris Smith
On Tuesday, Apr 19, 2005, Lee Cullens wrote:
I assume you mean PythonIDE for Python 2.3 (I usually use 2.4 and 
WingIDE).  Here it is (indents screwed up with var font):

HTH,
Lee C
import timeit
def y1():
print y1 executed
def y2():
print y2 executed
for f in [y1,y2]:
name = f.__name__
print name; f()
t=timeit.Timer(%s() % name, from __main__ import %s % name)
print t.timeit(1)
I wrote this yesterday
--
Well, how bizarre! Now I run the code again (after having restarted the 
PythonIDE) and now I can't get it to NOT work.  And it previously had 
not run for many tries.

I don't suppose this is some sort of quantum effect ;-)
Oh well, I'll keep my eyes open to see if this happens again.
--
And now today, the problem is back again :-(  What's going on? Here is 
a smaller code:

###
def y1():
print 'y1 executed'
for f in [y1]:
name = f.__name__
f()
s1 = '%s()' % name
s2 = 'from __main__ import %s' % name
t=timeit.Timer(s1, s2)
print t.timeit(1)
###
Here is the full report from the traceback window {it's great to be 
able to cut and paste from that window, thanks Just}

'''
ImportError: cannot import name y1
Traceback (innermost last)
File Untitled Script 1, line 10, in ?
File timeit.py, line 158, in timeit
  return self.inner(it, self.timer)
File timeit-src, line 3, in inner
'''
** If I click on the edit button it says that timeit-src cannot be 
found. Is this an error to pay attention to or is that an unrelated 
problem of trying to browse a (perhaps compiled) source file?

Here is what I've tried to reproduce the problem:
1) I have restarted the system (10.2.8) and run nothing but this script 
and still get the error.
2) removed my PythonStartup and sitecustomize.py codes after quitting; 
problem still persists
3) re-installed MacPython 2.3.3 after moving the old version's 
macPython 2.3.3 folder to the desktop
4) I have tried running the script in the add with and without the run 
as __main__ option.

I DO NOT have the error show up when I run the script through the 
Terminal (i.e. %python timeitproblem.py).

I also DO NOT have the problem if I run the script with PyOXIDE.
As noted yesterday, there are some unknown steps that make the problem 
go away, though I do not know what these are yet.

Does anyone else have any insights?
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] snippets helps

2005-04-19 Thread Chris Smith
In a recent post, I believe it was D Hawksworth that noted,
So I imported it, asked the shell window for 'help' (egad, technical
jargon!) and did a search on python, same result.  None of my
beginners' tutorials have anything about pickle, unfortunately (very
frustrating!)
Does anyone know if there are some *beginner*-user-friendly tutorials
out there for pickle? Or can give a sample of how you would implement
it into a VERY SIMPLE program?
I have often wished for some small examples to break into the sometimes 
dense technical notation. Has the python community ever considered 
writing the annotated documentation resource? It would be nice if the 
documentation had more examples that were VERY SIMPLE to demonstrate 
the use of some function or its arguments.

Would something like a documentation wiki (if that's the right word) be 
useful wherein each page(?) of the documentation would have a 
reader-modifiable section in which links back to tutor discussions or 
sample code could be put.  Since such annotations might grow long, 
perhaps a link to another page would be better. Would a rating system 
allow the snippets that people find most useful to rise to the top of 
the examples?

I'm not sure what goes into these wiki and whether something like this 
would get used or not.  Perhaps the personal feedback of the tutor list 
is more effective.

Any thoughts?
/c
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] import problem

2005-04-19 Thread Chris Smith
I sent the following to the mac-sig without reply (except for an 
autoresponder telling me that a person was out of the office :-)).  Is 
there anyone with a mac that could test this code in the IDE to see if 
you have the same problems? (I don't have problems running it through 
the 2.4 version of python in the terminal.)

=
I was recently trying to use the timeit module and although I was able 
to do so without problem on a Windows machine, I get a cannot import 
y1 ImportError from the following script.

###
import timeit
def y1():
print 'y1 executed'
def y2():
print 'y2 executed'
for f in [y1,y2]:
name = f.__name__
print name; f()
t=timeit.Timer('%s()' % name, 'from __main__ import %s' % name)
print t.timeit(1)
###
--the output--
y1
y1 executed
** ImportError
I am using the IDE for 2.3.3 under OS X (10.2.8).
I am able to successfully run timeit in other ways, but I like the 
above way to loop through the codes that I want to test.

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


Re: [Tutor] high score lists

2005-04-15 Thread Chris Smith
On Friday, Apr 15, 2005, at 14:31 America/Chicago, 
[EMAIL PROTECTED] wrote:

So I'm sure that's probably way too much information for most of you!!
But my remaining questions are these:
1. what is/where can i get the pickle module for storing/saving
changes to the high score list?
2. tabs/aligning the score in a column when i display it
The Python Cookbook is a good place to look to see if someone has 
already provided a recipe:
	http://aspn.activestate.com/ASPN/Cookbook/Python/

There are 2 table indenters at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662
In my previous post there is a suggestion on using the longest number 
to print all teh numbers in a space that big.  (There was also an error 
in my understanding of your program where you checked the user's score 
against the *lowest* score in the list, not the highest--sorry about 
that!)

3. displaying the score/scorelist stuff on the graphics window instead
of the python window
4. key=lambda x: x[1] ?
You can think of the key option like this: when sort comes to compare 
elements x and y it gives you the option of telling *what* you want to 
compare about x and y.  You might, for example, want to sort a list of 
strings based on their *length* not on their alphabetical position. To 
do so, write a 1-argument function that returns the length of a string:

###
Python 2.4 (#1, Apr  4 2005, 13:57:19)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1493)] on darwin
Type help, copyright, credits or license for more information.
 l=['sea', 'd', 'bee']
 l.sort()  #the normal sort
 l
['bee', 'd', 'sea']
 def strlen(x):# the 1-argument function
... return len(x)
...
 l.sort(key=strlen)
 l
['d', 'sea', 'bee']  #the length sort; it's stable so sea is still 
before bee
 def length_alph(x):  #'key' function if you want length first and 
then alphabetical
... return (len(x),x)
...
 l.sort(key=length_alph); l
['d', 'bee', 'sea']
###

Thank you so much for all of your suggestions!  I can't wait until I
learn enough python to be able to give some help back :)
This list is a great place for learning.  It's one of the things that 
has made working with Python so enjoyable and productive. (Thanks to 
all!)

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


Re: [Tutor] high score lists

2005-04-15 Thread Chris Smith
On Friday, Apr 15, 2005, at 20:40 America/Chicago, Jacob S. - 
[EMAIL PROTECTED] wrote:

Great.  len is a function though. Why use a second layer of function 
when len is a function in itself?

l = ['d','sea','bee']
l.sort(key=len)
l
['d', 'bee', 'sea']


LOL :-) Oooh, that's nice! OK, instead of wasting a post in admiration, 
how about something else that is a possibility since sort() is stable:

###
 l = ['d','sea','bee']
 l.sort() #get them in lexical order
 l
['bee', 'd', 'sea']
 l.sort(key=len) #now get similar lengths together
 l
['d', 'bee', 'sea']

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


Re: [Tutor] high score lists

2005-04-15 Thread Chris Smith
On Friday, Apr 15, 2005, at 18:46 America/Chicago, 
[EMAIL PROTECTED] wrote:

I did look at your example about using the longest number, but I
couldnt really understand all of the code, and ended up deciding to
arrange it so that the two columns were left-aligned: it looked like
it would align them down the center in your example? Let me know if I
am misunderstanding something.
Those that are fluent in using the string formatting will groan, but I 
usually don't need fancy formatting and can get by with pretty simple 
commands. I just printed the first column right formatted and printed 
the name right next to it (so it appeared to be left formatted). The 
comma in the print statement added the space.

Here is my simple-minded way of thinking about the two column problem:

1) get the data into fixed width strings
2) add those two strings together and print them
Now, as you are seeing, the alignment options for a string will fill in 
the padding spaces that you need.  Figuring out how long each column 
should *minimally* be (based on the actual data) is an extra layer of 
difficulty, but to keep it simple you could just pick widths that you 
think are reasonable and then do something like this:

###
high = [(1000,Denise), (945,Denise), (883,Denise),
 (823,Grant), (779,Aaron), (702,Pete),
 (555,Tom), (443,Tom), (442,Robin), (404,Pete)]
for score, who in high:
col1 = str(score).rjust(10)
col2 = who.rjust(20).replace(' ', '.') #replace spaces with dots
print col1 + col2
###
--the output--
  1000..Denise
   945..Denise
   883..Denise
   823...Grant
   779...Aaron
   702Pete
   555.Tom
   443.Tom
   442...Robin
   404Pete
--end output--
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] high score lists

2005-04-14 Thread Chris Smith
On Thursday, Apr 14, 2005, D. Hartley wrote:
and  a question about sorting (either way):
 I am trying it out with a list of tuples right now. The first problem
 I ran into is that when i sort it (scorelist.sort(reverse=True)), it
 sorts by the person's name (the first entry), and not by the score.
You aren't trying to do any fancy comparison; you just want to compare 
the 2nd values in a tuple rather than the tuple itself (in the case 
where the name comes first). So you supply a 2 argument function that 
returns the comparison of the 2nd values of two tuples:

###
def mycmp(a, b):
return cmp(a[1], b[1])
###
And now do your sort like this:
###
high_scorelist.sort(cmp=mycmp, reverse=True)
###
On the other hand, if you put the numbers first then the task of 
printing is the problem..but that's easily overcome in your loop that 
prints the values: just print the number first!

###
for score, who in highscores:
print score, who
###
which gives,
200 Nina
20 Ben
2 Raj
If you want to get the numbers looking pretty, try finding the longest 
number and then justify all numbers in a space that big:

###
highscores = [(200, 'Nina') , (20, 'Ben') , (2, 'Raj')]
longest_num = max( [ len(str(score)) for score,who in highscores] )
for score, who in highscores:
print str(score).rjust(longest_num), who
###
which gives
200 Nina
 20 Ben
  2 Raj
 plus I'm not quite sure yet how I'd get the user's name or score
 *into* the list - without manually adding it as a tuple? Since I can't
 do something like ... (John, 100)  username = John, userscore
 = 100, if userscore  lowestuserscore etc.
Your code was this:
#-
def add_score(userscore):   #1
   if userscore[0]  high_scorelist[len(high_scorelist)-1][0]:  #2
   print You made the high score list!#3
   high_scorelist.append(userscore) #4
   high_scorelist.sort(reverse=True)#5
   del high_scorelist[len(high_scorelist)-1]#6
   return high_scorelist#7
   else:#8
   print high_scorelist #9
#-
Lines 2-7 handle the case when the user beats the high score but if 
they don't you go to line 9 and just print the high score without 
inserting them in the list to see if they make it. How about modifying 
this so the else part...
	appends the user to the list;
	sorts the list;
	keeps only the first 10 items;
	prints the list

List slices are a nice way to get the first 10 (or whatever) items of a 
list:

###
 def first10(l):
...  return l[:10]
...
 print first10(range(20))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 print first10(range(3))
[0, 1, 2]
###
One final note, in lines 2 and 6 you use len(high_scorelist)-1 to get 
the last item of the list. A nice way to get the last item in the list 
is to use the index -1 which refers to the last one in a list.  
(You can use negative indices, too.)

BTW, the HOWTO on sorting  
http://www.amk.ca/python/howto/sorting/sorting.html  is helpful and 
the site starship site  
http://starship.python.net/crew/theller/pyhelp.cgi  is a nice place to 
do a search of KEYWORDS (like sort) in python documentation.

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


Re: [Tutor] high score lists

2005-04-14 Thread Chris Smith
On Thursday, Apr 14, 2005, I wrote:
which gives
200 Nina
  20 Ben
   2 Raj
oops, copy and paste error...should be:
200 Nina
 20 Ben
  2 Raj
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor