Re: [Tutor] Am I storeing up problems ?

2005-01-02 Thread Brian van den Broek
Max Noel said unto the world upon 2005-01-02 19:43:
On Jan 2, 2005, at 23:00, Danny Yoo wrote:
(Aside: one nonobvious example where copying can be avoided is in 
Conway's
Game of Life:  when we calculate what cells live and die in the next
generation, we can actually use the 'Command' design pattern to avoid
making a temporary copy of the world.  We can talk about this in more
detail if anyone is interested.)

I am.
-- Max
Seconded. (Thanks for offering, Danny.)
Best to all,
Brian vdB
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Sorting/filtering data, dictionary question & Re:OT

2005-01-02 Thread Bill Burns
Hi,

I have a couple of questions about a program I've been working on. Here's a
overview of what the program does.

Calculates the following data about HVAC/Plumbing pipe:
A). Total volume of water inside the pipe (US gallons).
B). The weight of the water inside the pipe.
C). The actual weight of the pipe, itself.
There's a total of six different types of pipe to choose from and within that
group of six, there's a total of 100 different sizes. Sizes range from 1/2" to
48". The user enters pipe lengths into a GUI and then clicks on a pushButton
to write the data out to a csv file. A dialog then pops up and gives the user
the option to open the csv file (with OpenOffice Calc).

Using suggestions I received from the Tutor List, I created a dictionary for
the program that holds various data about the pipes. The dict holds pipe
sizes, inside diameters, names of the lineEdits on the GUI, weight of the pipe
per foot, etc. 

So, the user enters various pipe lengths, and using the dictionary the program
calculates the totals, the totals go into a list, the list gets sorted and
then the sorted list is written to csv file.

One problem I ran into was sorting my lists. The dictionary I initially came
up with contained a pipe size designation in this format: 1/2", 3/4", 1", etc.
This format is the standard way to write pipe sizes (at least in the US
anyway). When I sorted the data (using this format), I found that the inches
didn't sort the way I wanted them to.
   For example:
   >>>sizes = ['1/2"', '3/4"', '1"', '1-1/4"', '1-1/2"']
   >>>sizes.sort()
   >>>sizes
   ['1"', '1-1/2"', '1-1/4"', '1/2"', '3/4"']
   >>>
Although Python is sorting exactly as it is supposed to, I needed the inches
to be in sequential order. Not knowing what to do, I added another size to the
dictionary before each of the "inch sizes". This new "size" has this type of
format: .5, .75, 1, 1.25, 1.5, etc. And when the data is sorted, it works
perfectly. But now I was left with both a "size" and an "inch size" and I only
wanted the "inch size" in the pipe reports (the csv file).

Below is a small section of the dictionary the program uses (pipeDict). I'm
also providing two functions to give you a general idea of how I'm:
1). Creating and sorting the pipe data and
2). How I'm filtering the "size" out of the list.


pipeDict = \
{('lineEdit1','Steel(Std)',.5,'1/2"',.85): .622, 
('lineEdit2','Steel(Std)',.75,'3/4"',1.13): .824,
('lineEdit3','Steel(Std)',1,'1"',1.678): 1.049,
('lineEdit4','Steel(Std)',1.25,'1-1/4"',2.272): 1.38,
('lineEdit5','Steel(Std)',1.5,'1-1/2"',2.717): 1.61, 
('lineEdit6','Steel(Std)',2,'2"',3.652): 2.067, 
('lineEdit7','Steel(Std)',2.5,'2-1/2"',5.79): 2.469, 
('lineEdit8','Steel(Std)',3,'3"',7.57): 3.068, 
('lineEdit9','Steel(Std)',3.5,'3-1/2"',9.11): 3.548, 
('lineEdit10','Steel(Std)',4,'4"',10.79): 4.026, 
('lineEdit11','Steel(Std)',5,'5"',14.62): 5.047, 
('lineEdit12','Steel(Std)',6,'6"',18.97): 6.065, 
('lineEdit13','Steel(Std)',8,'8"',28.55): 7.981, 
('lineEdit14','Steel(Std)',10,'10"',40.48): 10.02}
  
def somePipeReport():
report = []
for name, typ, size, inchSize, weight in pipeDict:
report.append((typ,size,inchSize,weight))
report.sort()
newReport = filterPipeData(report)
print newReport

def filterPipeData(data):
filteredData = []
for typ, size, inchSize, weight in data:
filteredData.append((typ,inchSize,weight))  
return filteredData   


The two functions above are not *exactly*  what I'm using, but it's close
enough to give you an idea of how I'm removing the "size" data. The reason I
created a separate function to filter the "size" out is because I currently
have two reports within the program. I figured it would be better to create
one function that each report could call to filter data. I also thought that
if I create any additional reports in the future, those reports could utilize
the same function as well. 

Question #1:
Am I going about this sorting and filtering thing correctly or have I just
gone insane? My gut feeling is, there's probably an easier/smarter way to do
this.

Question #2:
As I mentioned above, this program calculates the water volume inside of the
pipe. I do that using this function:

def volCalc(ID, length):
from math import pi
gal = ((ID*.5)**2)*pi*(12*length)/(230.9429931) 
return gal

The ID (inside diameter) is pulled from pipeDict (it's the value in the
dictionary) and the length comes from user input. What I'm wondering is,
would it be a better idea to store in the dictionary a "gallon per foot value"
for each pipe? For example, looking at 10" Steel(Std) pipe in the above
dictionary we find that this type & size of pipe has an ID of 10.02 (inches).
When we plug this ID and a length of 1 foot into the volCalc() function it
returns a total of 4.10 gallons (rounded). Would it 

Re: [Tutor] dumping .pck files

2005-01-02 Thread Patric Michael
> I want to explore some mailman config files, e.g.
> config.pck.  Some quick searches informed me that these
> contain pickled configuration info.
> 
> My first naive attempt to dump what was in them failed:
> 
> >>> import pickle
> >>> pickle.load(open("config.pck"))
> traceback
> ImportError: No module named Mailman.Bouncer
> 
> It seems that to do a good job of dumping the data, I need to tell it
> what this class looks like.
> 
> Are there alternatives?  Does the pickle format really not provide a
> way to inspect the data without the class definitions?  E.g. if I
> didn't have the source code or didn't want to dig around in it?
> 
> Is there a simple way to dump everything it does understand, and
> just print stubs for the parts it doesn't?
> 
> Or is there some nice software to do this all for me?
> 
> Or perhaps does mailman itself have handy command-line tools to aid in
> comparing configurations across mailing lists?

In the bin directory, find the script called "config_list".  From the help file 
(./config_list --help):

 --outputfile filename
-o filename
Instead of configuring the list, print out a list's configuration
variables in a format suitable for input using this script.  In this
way, you can easily capture the configuration settings for a
particular list and imprint those settings on another list.  filename
is the file to output the settings to.  If filename is `-', standard
out is used.

Dont forget to supply the list name in the command line.  
For example:

config_list -o outfile.txt mylist 

Patric




> 
> Are there other serialization options that would make this easier?
> 
> Many thanks,
> 
> Neal McBurnett http://bcn.boulder.co.us/~neal/
> Signed and/or sealed mail encouraged.  GPG/PGP Keyid: 2C9EBA60
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


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


[Tutor] dumping .pck files

2005-01-02 Thread Neal McBurnett
I want to explore some mailman config files, e.g.
config.pck.  Some quick searches informed me that these
contain pickled configuration info.

My first naive attempt to dump what was in them failed:

>>> import pickle
>>> pickle.load(open("config.pck"))
traceback
ImportError: No module named Mailman.Bouncer

It seems that to do a good job of dumping the data, I need to tell it
what this class looks like.

Are there alternatives?  Does the pickle format really not provide a
way to inspect the data without the class definitions?  E.g. if I
didn't have the source code or didn't want to dig around in it?

Is there a simple way to dump everything it does understand, and
just print stubs for the parts it doesn't?

Or is there some nice software to do this all for me?

Or perhaps does mailman itself have handy command-line tools to aid in
comparing configurations across mailing lists?

Are there other serialization options that would make this easier?

Many thanks,

Neal McBurnett http://bcn.boulder.co.us/~neal/
Signed and/or sealed mail encouraged.  GPG/PGP Keyid: 2C9EBA60
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Basic question -> How to use a class from a file?

2005-01-02 Thread Rich Krauter
Bernard Lebel wrote:
Okay here comes the next question.
In that class, I have 3 functions. Actually, one of them calls the two 
others.

However when I call these functions (wich are placed before the caller 
in the file), I get an error saying that the global name x (the function 
name) is not defined.

What am I doing wrong?


Hi Bernard,
This is just a guess since you didn't post your code, but did you call 
the 'bare' methods in your class definition, rather than calling the 
methods through an instance (which is usually called 'self' inside class 
definitions)?

I think the following may be similar to what you wanted to do:
class A(object):
def __init__(self,data=None):
self.data = data
def methodA(self):
self.methodB()
self.methodC()
def methodB(self):
print "in methodB"
print self.data
def methodC(self):
print "in methodC"
print self.data
if __name__ == '__main__':
a1 = A(5)
a1.methodA()
a2 = A([1,2,3])
a2.methodA()
Hope this helps.
Rich
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Basic question -> How to use a class from a file?

2005-01-02 Thread Bernard Lebel
Okay here comes the next question.
In that class, I have 3 functions. Actually, one of them calls the two 
others.

However when I call these functions (wich are placed before the caller 
in the file), I get an error saying that the global name x (the function 
name) is not defined.

What am I doing wrong?
Thanks
Bernard
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] My 2nd ever .py script [XML, makedirs, copytree]

2005-01-02 Thread Rafal Kaniewski
This is my second script (if you don't include the last time I
programmed (20 years ago...) 

it's a nasty hack but it works...

---

   
-  
- http://www.filemaker.com/fmpdsoresult";>
  0 
  Workflow01.fp7 
   
- 
  yourSoLuckyJob 
  c:\BaldricsWorkFolder 
  FRENCH 
  
- 
  yourSoLuckyJob 
  c:\BaldricsWorkFolder 
  MT 
  
- 
  yourSoLuckyJob 
  c:\BaldricsWorkFolder 
  SPANISH 
  
  

---

from xml.sax import make_parser 
from xml.sax.handler import ContentHandler 
import os
import shutil

class FolderHandler(ContentHandler): 

 def __init__ (self, searchTerm): 
   self.searchTerm= searchTerm;
   self.isA_5Element, self.ishomePathElement, self.isA_1Element,
self.isProjectElement, self.isA_4Element, self.isA_0Element = 0, 0, 0,
0, 0, 0; 

 def startElement(self, name, attrs): 

   if name == 'ROW':  
 self.MODID = attrs.get('MODID',"")
 self.RECORDID = attrs.get('RECORDID',"")
   elif name == 'pce.project.g': 
 self.isProjectElement= 1; 
 self.PROJECT = "";
   elif name == 'pce.homePath.g':
 self.ishomePathElement= 1; 
 self.homePath = "";
   elif name == 'pea.elementA_0': 
 self.isA_0Element = 1;
 self.A_0 = "";
   
 def characters (self, ch): 
   if self.isProjectElement == 1: 
 self.PROJECT += ch
   if self.ishomePathElement== 1: 
 self.homePath += ch 
   if self.isA_0Element == 1: 
 self.A_0 += ch
 
 class DirectoryException(Exception): pass

 FilmScansFolders = self.homePath + '\\' + self.PROJECT + '\\' +
'FILM' + '\\' + 'SCANS' + '\\' + self.A_0 
 FilmTemplFolders = self.homePath + '\\' + self.PROJECT + '\\' +
'TEMPLATES'
  
 dirpath = os.path.join(FilmScansFolders)
 try:
 os.makedirs(dirpath)
 except OSError, e:
 if e.errno == 17:
 if not os.path.isdir(dirpath):
 raise DirectoryException, "'%s' can neither be created
nor is it an existing directory" % dirpath
 else:
 raise # cannot handle it here 
 
 try:
 shutil.copytree('C:\Program Files\Python\TEMPLATES',
FilmTemplFolders) 
 print ''
 except os.error, why:
 print ''
  
 def endElement(self, name): 
   if name == 'pce.project.g': 
 self.isProjectElement= 0
   if name == 'pce.homePath.g': 
 self.ishomePathElement= 0 
   if name == 'pea.elementA_0': 
 self.isA_0Element = 0 

searchTerm= '*'
parser = make_parser()
curHandler = FolderHandler(searchTerm) 
parser.setContentHandler(curHandler) 
parser.parse(open('FM_folders.xml'))

---

The aim (create folders on a network from a database with xml & Python):
1) extract data from xml file (generated by Filemaker database)
2) create complex folder structure (each row of the xml is set
of folders, all rows reside in the same home 'project folder'
3) copy a folder into the 'project folder'
4)the python file is called/executed by Filemaker (multi-user)

I am hoping people can feedback on areas that this script that clearly
needs tidying up.

Thanks all,

-
Rafal Kaniewski
EU:UK

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


Re: [Tutor] Am I storeing up problems ?

2005-01-02 Thread Alan Gauld
> I needed to copy this matrix to 'self.old_data', so I have been
using
> .deepcopy(), which works OK but is SLOW  (12+ secs)

Are you sure you need to copy it./ A simple reassignment should work
and then reconstruct the structure using fresh lists/dictionary etc.
That should work faster.

Alan G.

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


Re: [Tutor] simple list query

2005-01-02 Thread Alan Gauld

> You might want to try:
> 
> x in list

Blush, I forgot about 'in'. And being in C it should be faster 
than the sort/loop combination. Silly me... :-(

Alan G.

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


Re: [Tutor] simple list query

2005-01-02 Thread Alan Gauld
> I have a list consisting of about 250 items, I need to know if a
> particular item is in the list. I know this is better suited to  a
> dictionary but thats not the way it ended up ;-)
>
> I could do a for loop to scan the list & compare each one, but I
have a
> suspission that there is a better way ?

In principle you are right but due to the way Python works you
might be faster doing a sort on the list first, then you only
need to search until you pass the place where the entry should
be... This will be faster if you have to search for several
items, and might be faster even for one since the sort is
written in C but the for loop will be in Python...

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

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


Re: [Tutor] Am I storeing up problems ?

2005-01-02 Thread Max Noel
On Jan 2, 2005, at 23:00, Danny Yoo wrote:
(Aside: one nonobvious example where copying can be avoided is in 
Conway's
Game of Life:  when we calculate what cells live and die in the next
generation, we can actually use the 'Command' design pattern to avoid
making a temporary copy of the world.  We can talk about this in more
detail if anyone is interested.)
I am.
-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?"

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


[Tutor] A not-so-basic question...

2005-01-02 Thread Patric Michael
Hi folks...

I was thinking about this the other day while prepping to write up 
another CGI thing.
It occurred to me to wonder how other folks prepare an app, script, 
whatever.
So the question is, and I am not looking for a "right answer" here.  (I 
doubt ther eis one, to be honest.)

How do you go about setting up a new application?

For example, suppose I need a script that will collect order information 
for a set of items ona  page.  Its output will go to a mail program so the 
artist can be notified.
I know that the script needs to be somewhat customizable since more 
than one person will use it, and I want to look to the future where such a 
script might get superceded for something like credit card orders, or 
possible integration with a larger order processing scheme.

I'd start out by commenting goals in a new file, like so:

--
# Initialize variables

# Gather form data

# Output results
--
Then I'd go back through each comment and either call modules I've 
prewritten, or write new defs.  
Then I'd add import statements to cover the modules and the defs:

--
from datetime import now
import cgi
from mailman import send

# Initialize variables
form = cgi.FieldStorage()

# Gather form data
for each in form:
  blah 
  blah

# Output results
result = {}
send(result)



And so on.  

So the question is, how do you do it?

Is there a method you prefer?  Something tried and true, or maybe 
foolproof?

Just curious...  And maybe a bit hopeful someone has a better way than 
mine.  Seems like I do an awful lot of testing... :)

Patric

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


Re: [Tutor] Basic question -> How to use a class from a file?

2005-01-02 Thread Bernard Lebel
All righty, thanks a lot!
Bernard
tanja pislar wrote:
hi Bernard,
you have to specify the module as well:
let's say your module is called rtModule.py,
then in your case you'd do:
import rtModule
testClass = rtModule.rt()
testClass.walk()
or:
from rtModule import rt
testClass = rt()
testClass.walk()
regards,
tanja
On Sun, 02 Jan 2005 17:43:07 -0500, Bernard Lebel
<[EMAIL PROTECTED]> wrote:
Hello,
An easy one to start the year.
Trying to write my first class, already running into problems after 3
lines! :-(
So have this little class:
class rt:
   def walk(self):
   print 'yeah'
So if I write this in the Python shell, instantiate rt and call walk(),
I get the proper result. yeah gets printed.
Now let say I put this into a file. I want to import that class and use
its methods, but this is were I get lost.
import rt
rt.walk()
Returns:
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'module' object has no attribute 'walk'
When I try to instantiate the class, I get an non-callable module object
error.
So how to use a class from a file?
Thanks
Bernard
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Basic question -> How to use a class from a file?

2005-01-02 Thread tanja pislar
hi Bernard,

you have to specify the module as well:

let's say your module is called rtModule.py,
then in your case you'd do:

import rtModule

testClass = rtModule.rt()
testClass.walk()

or:
from rtModule import rt

testClass = rt()
testClass.walk()

regards,
tanja


On Sun, 02 Jan 2005 17:43:07 -0500, Bernard Lebel
<[EMAIL PROTECTED]> wrote:
> Hello,
> 
> An easy one to start the year.
> 
> Trying to write my first class, already running into problems after 3
> lines! :-(
> 
> So have this little class:
> 
> class rt:
> def walk(self):
> print 'yeah'
> 
> So if I write this in the Python shell, instantiate rt and call walk(),
> I get the proper result. yeah gets printed.
> 
> Now let say I put this into a file. I want to import that class and use
> its methods, but this is were I get lost.
> 
> import rt
> rt.walk()
> 
> Returns:
> Traceback (most recent call last):
>File "", line 1, in ?
> AttributeError: 'module' object has no attribute 'walk'
> 
> When I try to instantiate the class, I get an non-callable module object
> error.
> 
> So how to use a class from a file?
> 
> Thanks
> Bernard
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


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


[Tutor] Basic question -> How to use a class from a file?

2005-01-02 Thread Bernard Lebel
Hello,
An easy one to start the year.
Trying to write my first class, already running into problems after 3 
lines! :-(

So have this little class:
class rt:
def walk(self):
print 'yeah'
So if I write this in the Python shell, instantiate rt and call walk(), 
I get the proper result. yeah gets printed.

Now let say I put this into a file. I want to import that class and use 
its methods, but this is were I get lost.

import rt
rt.walk()
Returns:
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'module' object has no attribute 'walk'
When I try to instantiate the class, I get an non-callable module object 
error.

So how to use a class from a file?
Thanks
Bernard
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Am I storeing up problems ?

2005-01-02 Thread Danny Yoo


On Sun, 2 Jan 2005, Dave S wrote:

> My matrix 'self.data' consists of a list of 110 items, each item is a
> dictionary of 250 keys, each key holds two lists, one of four items, one
> of 12 items.

Hi Dave,

Hmmm... what kind of data is being copied here?  Python's data structures
are desigined for flexibility, but sometimes that flexibility comes at the
cost of some space.  If we knew more about the data that's being stored,
maybe we can think of a more compact representation.


> I needed to copy this matrix to 'self.old_data', so I have been using
> .deepcopy(), which works OK but is SLOW  (12+ secs)

Perhaps we can avoid making a separate copy of the data?  Copying data
structures can often be avoided.  Why does your program try to copy the
data structure?

(Aside: one nonobvious example where copying can be avoided is in Conway's
Game of Life:  when we calculate what cells live and die in the next
generation, we can actually use the 'Command' design pattern to avoid
making a temporary copy of the world.  We can talk about this in more
detail if anyone is interested.)



> Once the matrix is copied, 'self.data' is re-constructed as the
> programme gathers data.
>
> To speed things up I changed my code to
>
> # This is the speeded up deepcopy()
> self.old_data = self.data
> self.data = []
> for i in range(110):
> self.data.append({})
>
>  Query: Is all this OK, it works and quick as well, but I am concerned I
> may be leaving garbage in the Python PVM since I am shrugging off old
> 'self.old_data's which may be mounting up ?


Whenever we reassign to self.old_data:

self.old_data = self.data

then whatever self.old_data was pointing at, before the assignment, should
get garbage collected, if there are no other references to the old data.

The code there isn't really doing any copying at all, but is rather just
constructing a whole new empty data structure into 'self.data'.  If so,
then it does seem that you can avoid copying.

I'd love to know a little bit more about the data that the program is
collecting; if you have time, please feel free to tell us more details.
Good luck to you!

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


[Tutor] Am I storeing up problems ?

2005-01-02 Thread Dave S
Hi there again,
My matrix 'self.data' consists of a list of 110 items, each item is a 
dictionary of 250 keys, each key holds two lists, one of four items, one 
of 12 items.

I needed to copy this matrix to 'self.old_data', so I have been using 
.deepcopy(), which works OK but is SLOW  (12+ secs)

Once the matrix is copied, 'self.data' is re-constructed as the 
programme gathers data.

To speed things up I changed my code to
# This is the speeded up deepcopy()
self.old_data = self.data
self.data = []
for i in range(110):
   self.data.append({})
Query: Is all this OK, it works and quick as well, but I am concerned I 
may be leaving garbage in the Python PVM since I am shrugging off old 
'self.old_data's which may be mounting up ?

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


Re: [Tutor] simple list query

2005-01-02 Thread Dave S
Patrick Hall wrote:
Hi Dave,
 

I have a list consisting of about 250 items, I need to know if a
particular item is in the list. I know this is better suited to  a
dictionary but thats not the way it ended up ;-)
   

 

I could do a for loop to scan the list & compare each one, but I have a
suspission that there is a better way ?
   

Indeed there is: just use the built-in "in":
 

li = ['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c']
'a' in li
   

True
 

'z' in li
   

False
That's a small example, but it will work equally well with a long
list. For instance, we can check to see if the words "Ahab", "whale",
and "pizza" are in the text of "Moby Dick" (I have the text in a file
called "moby.txt".)
 

moby = open('moby.txt').read() # Moby Dick, the whole thing!
mobywords = moby.split() # now mobywords has all the words in the text
'Ahab' in mobywords
   

True
 

'whale' in mobywords
   

True
 

'pizza' in mobywords
   

False
These results are unsurprising. 8^)
A list of 250 words is no problem -- "Moby Dick" has a couple hundred thousand:
 

len(mobywords)
   

214112
I'm not sure I understand why you think a dictionary would be better
in this case, a list seems fine to me.
Best,
Pat
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
 

Thanks guys, something was rattling round by brain that there was a way, 
but I just could not work it out :-)

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


Re: [Tutor] simple list query

2005-01-02 Thread Patrick Hall
Hi Dave,

> I have a list consisting of about 250 items, I need to know if a
> particular item is in the list. I know this is better suited to  a
> dictionary but thats not the way it ended up ;-)

> I could do a for loop to scan the list & compare each one, but I have a
> suspission that there is a better way ?

Indeed there is: just use the built-in "in":

>>> li = ['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c']
>>> 'a' in li
True
>>> 'z' in li
False

That's a small example, but it will work equally well with a long
list. For instance, we can check to see if the words "Ahab", "whale",
and "pizza" are in the text of "Moby Dick" (I have the text in a file
called "moby.txt".)

>>> moby = open('moby.txt').read() # Moby Dick, the whole thing!
>>> mobywords = moby.split() # now mobywords has all the words in the text
>>> 'Ahab' in mobywords
True
>>> 'whale' in mobywords
True
>>> 'pizza' in mobywords
False

These results are unsurprising. 8^)

A list of 250 words is no problem -- "Moby Dick" has a couple hundred thousand:

>>> len(mobywords)
214112

I'm not sure I understand why you think a dictionary would be better
in this case, a list seems fine to me.

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


Re: [Tutor] simple list query

2005-01-02 Thread Bill Kranec
You might want to try:
x in list
this will return true if, for example,  list = [x,y,z,w], false if list 
= [y,y,y,y]

Bill
Dave S wrote:
OK simple query,
I have a list consisting of about 250 items, I need to know if a 
particular item is in the list. I know this is better suited to  a 
dictionary but thats not the way it ended up ;-)

I could do a for loop to scan the list & compare each one, but I have 
a suspission that there is a better way ?

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


[Tutor] simple list query

2005-01-02 Thread Dave S
OK simple query,
I have a list consisting of about 250 items, I need to know if a 
particular item is in the list. I know this is better suited to  a 
dictionary but thats not the way it ended up ;-)

I could do a for loop to scan the list & compare each one, but I have a 
suspission that there is a better way ?

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


Re: [Tutor] doctest

2005-01-02 Thread Kent Johnson
Alan Gauld wrote:
Also, anything I can do... Presently, since I'm running windows xp,
I would
have to hunt for the command prompt and type in the command

Start->Run
Type cmd,
Hit OK
:-)
Or drag the icon from accessories into the start menu or to
the desktop.
Or drag the icon to the left side of the task bar
Or, my favorite, add a 'Command Prompt' item to the right-click menu so you can right-click a 
directory and open a command prompt at that directory. The recipe is here:
http://www.petri.co.il/add_command_prompt_here_shortcut_to_windows_explorer.htm

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


Re: [Tutor] doctest

2005-01-02 Thread Kent Johnson
Jacob S. wrote:
Even so, doctest doesn't seem to recognize the module level docstring.
It will run the test inside the functions, but it says there isn't a test on
the module level.
I put the docstring just like in the example at the link you provided...
Please post the code for the module you are testing.
Also, anything I can do... Presently, since I'm running windows xp, I would
have to hunt for the command prompt and type in the command
'"C:\python24\python.exe" "C:\documents and settings\jacob\desktop\working
python programs\testmodules.py" -v'
You should put C:\python24 in your PATH environment variable. Not sure how to do that on XP; on Win2K I
- right-click My Computer and select Properties
- click the Advanced tab
- click Environment Variables
- find the System variable Path and edit it
- append ";C:\python24" to Path (no quotes; the semicolon is needed, it is a separator for the Path 
variable)
- click OK a few times
- restart your DOS shell so it gets the new variable

Now you should be able to open a command line in the directory containing your 
program and type
 > python testmodules.py -v
Oh, the light goes on...you want to be able to just double-click testmodules.py. See below for the 
fix for -v

...or make a batch file to do it for me...
How can I make testmodules.py (shown below) append the -v to itself? Is
there a self.results or something in testmod?
From the docs at http://docs.python.org/lib/doctest-basic-api.html:
"Optional argument verbose prints lots of stuff if true"
So try
  doctest.testmod(eval(modtotest), verbose=True)
## testmodules.py ###
import doctest
modtotest = 'FractionReducer2'
exec "import %s" % modtotest
doctest.testmod(eval(modtotest))
raw_input()
#
Since you will be editing this to change the module under test, I don't think there is any benefit 
to putting the module name in a string. I would write it like this:

import doctest
import FractionReducer2 as test_module
doctest.testmod(test_module, verbose=True)
raw_input()
This preserves the single point of change when you want to test a different module, but it is IMO 
much more readable.

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


Re: [Tutor] doctest

2005-01-02 Thread Alan Gauld
> Also, anything I can do... Presently, since I'm running windows xp,
I would
> have to hunt for the command prompt and type in the command

Start->Run
Type cmd,
Hit OK

:-)

Or drag the icon from accessories into the start menu or to
the desktop.

> '"C:\python24\python.exe" "C:\documents and
settings\jacob\desktop\working
> python programs\testmodules.py" -v'

Why not create a shortcut and add that to your right click menu?

Or to your desktop if you want - but I hate cluttered desktops!

> ...or make a batch file to do it for me...

A shortcut will suffice, a batch job is overkill for a one liner

Alan G.

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


Re: [Tutor] How to substitute an element of a list asapattern forre.compile()

2005-01-02 Thread Alan Gauld
> >   >>> for x in ['string', 10, True, [1,2,3] ]:
> >   ...   print '%s' %x
> >   ...
> > string
> > 10
> > True
> > [1, 2, 3]
> 
> That's cool! I didn't know that. I guess I'm crazy... : )
> (We already knew that here.)

The difference is in how the formatting details work.
For numbers the formatting digits indicate precision 
and for strings length.

>>> print "%5.3f" % 123.456
123.4560
>>> print "%5.3s" % 123.456
 123.

produce very different results.

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