[Tutor] Matrix

2005-10-24 Thread Shi Mu
I can not understand the use of "cell in row" for two times in the code:

# convert the matrix to a 1D list
matrix = [[13,2,3,4,5],[0,10,6,0,0],[7,0,0,0,9]]
items = [cell for row in matrix for cell in row]
print items
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] manipulating list of lists

2005-10-24 Thread Brian van den Broek
John Fouhy said unto the world upon 2005-10-24 22:18:
> On 25/10/05, Brian van den Broek <[EMAIL PROTECTED]> wrote:
> 
>>To sort by the second item, try
>>
>> >>> def sort_by_second(sequence):
>>decorated = [(x[1], x) for x in sequence]
>>decorated.sort()
>>return [x[1] for x in decorated]
> 
> 
> With python2.4, you can use the key= argument to sort.
> 
> eg:
> 
arr = [('a', 5), ('b', 3), ('c', 7), ('d', 1), ('e', 2)]
arr.sort(key=lambda x: x[1])
arr
> 
> [('d', 1), ('e', 2), ('b', 3), ('a', 5), ('c', 7)]


And that would be the better suggestion I predicted :-)

I also should have pointed out that I wrote

 >>> noneless = [[x, y] for [x, y] in orig_list if not (x is None or y 
is None)]

to be fully explicit. Better in real code (I think) would be

 >>> noneless = [x for x in orig_list if not None in x]
 >>> noneless
[['c', 'b'], ['a', 'g'], ['e', 'f']]
 >>>


Best,

Brian vdB

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


Re: [Tutor] manipulating list of lists

2005-10-24 Thread John Fouhy
On 25/10/05, Brian van den Broek <[EMAIL PROTECTED]> wrote:
> To sort by the second item, try
>
>  >>> def sort_by_second(sequence):
> decorated = [(x[1], x) for x in sequence]
> decorated.sort()
> return [x[1] for x in decorated]

With python2.4, you can use the key= argument to sort.

eg:
>>> arr = [('a', 5), ('b', 3), ('c', 7), ('d', 1), ('e', 2)]
>>> arr.sort(key=lambda x: x[1])
>>> arr
[('d', 1), ('e', 2), ('b', 3), ('a', 5), ('c', 7)]

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


Re: [Tutor] manipulating list of lists

2005-10-24 Thread John Fouhy
On 25/10/05, Brian van den Broek <[EMAIL PROTECTED]> wrote:
> To sort by the second item, try
>
>  >>> def sort_by_second(sequence):
> decorated = [(x[1], x) for x in sequence]
> decorated.sort()
> return [x[1] for x in decorated]

With python2.4, you can use the key= argument to sort.

eg:
>>> arr = [('a', 5), ('b', 3), ('c', 7), ('d', 1), ('e', 2)]
>>> arr.sort(key=lambda x: x[1])
>>> arr
[('d', 1), ('e', 2), ('b', 3), ('a', 5), ('c', 7)]

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


Re: [Tutor] manipulating list of lists

2005-10-24 Thread Brian van den Broek
Vincent Gulinao said unto the world upon 2005-10-24 09:29:
> I have a list of lists of constant width (2 rows). I need to:
> 1. delete sub-lists with None element
> 2. sort it by any sub-list index
> 
> say: [ ['c','d'], ['g',None], ['a','b',], ['e','f']
> if sorted using 2nd index: [ ['a','b'], ['c','d'], ['e','f'] ] (same result
> for 1st index for this example)
> 
> TIA.


Hi Vincent,

I'm no guru, so watch this space for better suggestions ;-)

I changed your example to one where the sort order is different for 
sort by the first and second items of the nested lists.

I'd use a list comprehension to remove the items with a None value:

 >>> orig_list = [ ['c','b'], ['g',None], ['a','g',], ['e','f'], ['d', 
None]]
 >>> noneless = [[x, y] for [x, y] in orig_list if not (x is None or y 
is None)]
 >>> noneless
[['c', 'b'], ['a', 'g'], ['e', 'f']]

Or:
 >>> noneless = [[x, y] for [x, y] in orig_list if not None in [x, y]]
 >>> noneless
[['c', 'b'], ['a', 'g'], ['e', 'f']]


To sort by the second item, try

 >>> def sort_by_second(sequence):
decorated = [(x[1], x) for x in sequence]
decorated.sort()
return [x[1] for x in decorated]

(google for DSU, Decorate Sort Undecorate for more info)

 >>> sort_by_second(noneless)
[['c', 'b'], ['e', 'f'], ['a', 'g']]


HTH. There's no explanation here (I'm feeling lazy); post again if you 
need some help sorting this out.

Best,

Brian vdB

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


Re: [Tutor] hand-holding for web development

2005-10-24 Thread Jay Loden
Sorry, didn't see your reply until now...

the directory section can go either in your main apache config file (in my 
case, /etc/httpd/conf/httpd.conf ) OR in a separate file in the conf.d 
directory. In my case, I have a python.conf file in /etc/httpd/conf.d/ that 
contains the following: 

LoadModule python_module modules/mod_python.so


AddHandler  mod_python .htm
PythonHandler parse
#  PythonDebug On


As for Django, I don't even know what that is, let alone how to interface to 
it, so you'd have to look elsewhere for help on that. I imagine there's 
someplace online you can get Django help such a specific mailing list.

-Jay

On Tuesday 18 October 2005 04:23 pm, nitin chandra wrote:
> Thanks Jay
>
> i guess the  can be added only in one of the conf
> file. Which one should i add in?
>
> Thaks you. could you please guide how to interface Django with
> mod_python, for effectively using in web site development?
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] : Threads?

2005-10-24 Thread Kent Johnson
Orri Ganel wrote:
> Not sure what IIUC stands for, but I am, indeed, running windows. XP 
> Home Edition, in fact, with Python 2.4.2 final

If I Understand Correctly
http://www.acronymfinder.com/ is helpful here.

Kent

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


Re: [Tutor] : Threads?

2005-10-24 Thread Orri Ganel
Not sure what IIUC stands for, but I am, indeed, running windows. XP Home Edition, in fact, with Python 2.4.2 finalOn 10/24/05, Kent Johnson <
[EMAIL PROTECTED]> wrote:Hugo González Monteverde wrote:> I have done scripts for decompressing MP3 in the past. I normally follow
> a fork() exec() subprocess scheme, and this helps me gain about 30%> improvement. I'm not an expert, but I have read that CPU time will be> better used by several processes than for just one, and while one
> process is waiting for disk IO and the like, another can be number> crunching.>> I have some code, but I will have to look for it and then post it.IIUC Orri is running on Windows and fork() is not supported there.
Kent___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
-- Email: singingxduck AT gmail DOT comAIM: singingxduckProgramming Python for the fun of it.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] testing for modules?

2005-10-24 Thread Bill Burns
Ed Hotchkiss wrote:
> i have a generic script that is using several modules on windows and 
> linux boxes. i need to have the scripts test if a module is installed, 
> and then if not - then to install the module. can anyone give me a 
> headsup on how to test for a module, returning something to indicate 
> whether or not it is installed, then after that executing file to 
> install the module.? just somewhere to start would be helpful! thanks in 
> advance.

Hi Ed,

You can at do this to test if a module is installed:

try:
 import SomeModule
except ImportError:
 print 'SomeModule is not installed!'

I'm not sure about the part regarding the module installation. I guess 
you would replace the print statement above with some code to install 
the module.

HTH,

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


Re: [Tutor] testing for modules?

2005-10-24 Thread Kent Johnson
Ed Hotchkiss wrote:
> i have a generic script that is using several modules on windows and 
> linux boxes. i need to have the scripts test if a module is installed, 
> and then if not - then to install the module. can anyone give me a 
> headsup on how to test for a module, returning something to indicate 
> whether or not it is installed, then after that executing file to 
> install the module.? just somewhere to start would be helpful! thanks in 
> advance.

I don't know a generic way to install a module but the testing part is easy - 
just try to import it:
try:
  import mymodule
except ImportError:
  # install mymodule

In general you need to download and unzip a module, then run 'python setup.py 
install'.

Kent
-- 
http://www.kentsjohnson.com

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


Re: [Tutor] Tkinter Data Passing Problem

2005-10-24 Thread Alan Gauld
> The problem is that when I specify that the frame be part of root the data
> appears in the entry boxes (using textvariable = StringVar()) but if a 
> second
> Tk() root is specified, the entry boxes appear, but there is no data. I 
> cannot
> figure out why.

Create your new dialog as a child of TopLevel instead of Tk()

Alan G 

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


[Tutor] testing for modules?

2005-10-24 Thread Ed Hotchkiss
i have a generic script that is using several modules on windows and linux boxes. i need to have the scripts test if a module is installed, and then if not - then to install the module. can anyone give me a headsup on how to test for a module, returning something to indicate whether or not it is installed, then after that executing file to install the module.? just somewhere to start would be helpful! thanks in advance.
-- edward hotchkiss 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tkinter Data Passing Problem

2005-10-24 Thread John Fouhy
On 25/10/05, mdcooper <[EMAIL PROTECTED]> wrote:
> The problem is that when I specify that the frame be part of root the data
> appears in the entry boxes (using textvariable = StringVar()) but if a second
> Tk() root is specified, the entry boxes appear, but there is no data. I cannot
> figure out why.
>
> Can someone help?

I'm not sure if I understand exactly --- but it is generally an error
to make two root windows.  If you want to have additional windows on
your screen, look into the Toplevel() class.

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


[Tutor] Tkinter Data Passing Problem

2005-10-24 Thread mdcooper
Hi,

I am having some trouble with tkinter.

I am creating a filled set of entry boxes so that a user can adjust certain 
data if desired. I would prefer that the box containing these data be separate 
from the main GUI.

The problem is that when I specify that the frame be part of root the data 
appears in the entry boxes (using textvariable = StringVar()) but if a second 
Tk() root is specified, the entry boxes appear, but there is no data. I cannot 
figure out why.

Can someone help?

Thanks,

Matt

def adjustGuassianData2(self, master):

self.frames.append(Frame(master))
self.frames[4].grid()
self.entries=[]
self.text=[]

Label(self.frames[4], text="Frequencies").grid(row=0, column=0)
Label(self.frames[4], text="Intensities").grid(row=0, column=1)
Label(self.frames[4], text="New Intensities").grid(row=0, column=2)
for r in range(len(self.frequencies)):
self.text.append([[],[],[]])
self.text[r][0]=StringVar()
self.text[r][1]=StringVar()
self.text[r][2]=StringVar()
self.text[r][0].set("%3.2f" % (self.frequencies[r]))
self.text[r][1].set("%3.2f" % (self.IR_intensities[r]))
self.text[r][2].set("%3.2f" % (self.IR_intensities[r]))
   
self.entries.append([Entry(self.frames[4],textvariable=self.text[r][0]),
Entry(self.frames[4],textvariable=self.text[r][1]),
Label(self.frames[4], textvariable=self.text[r][2])])
self.entries[r][0].grid(row=r+1, column=0)
self.entries[r][1].grid(row=r+1, column=1)
self.entries[r][2].grid(row=r+1, column=2)

b = Button(self.frames[4], text="UPDATE!", command=self.updateEntries)
b.grid(row=r+2,column=0,columnspan=3)


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


Re: [Tutor] pytunes (Was __slots__, struct, etc.)

2005-10-24 Thread John Fouhy
For all of them --- not guaranteed that you'll be able to achieve the optimum..

My solution is basically a greedy algorithm: Make a list of (artist,
tracks) pairs, and sort descending by len(tracks).  Then iteratively:
 1. Take the next track from the first artist on the list.
 2. Move that artist down to position total/len(tracks).

Repeat until all tracks have been selected :-)

Generally it works well, except at the end of the playlist sometimes. 
See attachment for my implementation. (uses mmpython, which you can
find on the net)

--
John.

On 21/10/05, Liam Clarke <[EMAIL PROTECTED]> wrote:
> Hmmm, that's interesting.
>
> Obviously, for a playlist with x songs, and n songs by a particular
> artist, the optimum separation between songs would be x/n.
>
> Which would be easy for one artist, but for all of them?
>
> Hmm...
>
> Let's see. First off, let's discount all the artists with only one
> song, they can be the space filler.
>
> Next, you'd have to work out optimal spacing for each artist's songs,
> and try to insert them into a list. If that slot was already taken,
> you'd want to look down and up the list for the next free space,
> choosing whichever maximised the distance. And you'd have to treat
> x[5] - 10 as x[96] for a list x where len(x) == 100.
>
> Err, there's got to be an algorithm for this sorta stuff, but I can't
> understand the big words when I google it... what's your solution?
>
> On 10/21/05, John Fouhy <[EMAIL PROTECTED]> wrote:
> > Hmm, neat. I don't have any feedback for you on your code, but since
> > you're working with this sort of thing, I have a puzzle for you:
> >
> > Suppose you have a collection of MP3 files.  You want to build a
> > random playlist, subject to the condition that tracks by the same
> > artist are as far apart as possible.  You can assume you have the
> > track / artist data in any structure you like.  How would you do this?
> >
> > (I have a solution, but I don't think it is optimal.  In fact, I'm not
> > sure how to actually define "optimal" here... And so I am interested
> > in how other people would solve this problem :-) )
> >
> > --
> > John.
import os
import mmpython
import random
from math import log, ceil
from itertools import *

def getFiles(directory):
""" Walk directory under root, getting a list of all regular files. """

res = []
for root, dirs, files in os.walk(directory):
for f in files:
res.append(os.path.join(root, f))

return res

def getMusic(files):
""" Filter a list of files for music files. """

return [f for f in files if os.path.splitext(f)[1][1:].lower() in ('mp3', 
'ogg')]

def addInfo(files):
""" Add tag info to a list of files. """

return [(mmpython.parse(f), f) for f in files]

def getMusicByArtist(musicInfo):
""" Process a list of (taginfo, filename) pairs into a dict of artist |-> 
filename. """

files = {}
errors = []
for info, filename in musicInfo:
if not info:
errors.append(filename)
continue
try:
files[info.artist].append((info, filename))
except KeyError:
files[info.artist] = [(info, filename)]

return files, errors

def extraRandom((musicByArtist, errors)):
""" Produce a list of files with maximum gaps between artists. """

# Do some shuffling first.
musicByArtist = dict(musicByArtist)
for stuff in musicByArtist.values():
random.shuffle(stuff)

data = musicByArtist.items()
data.sort(key=lambda x: len(x[1]), reverse=True)

# Total number of tracks.
total = sum(len(x) for x in musicByArtist.itervalues())

# Current position in list of each artist.
positions = dict(izip(musicByArtist.iterkeys(), repeat(0)))

randList = []
while len(randList) < total:
artist, tracks = data[0]
randList.append((artist, tracks[positions[artist]]))
jump = total / len(tracks)
del data[0]
positions[artist] += 1
if positions[artist] < len(tracks):
data[jump:jump] = [(artist, tracks)]

return randList, errors

def copy(source, dest):
f = file(dest, 'wb')
f.write(file(source, 'rb').read())
f.close()

def procFiles(inDir, outDir):
""" Take files from structure in inDir, randomize, produce flat list of 
numbered tracks in outDir. """

randList, errors = 
extraRandom(getMusicByArtist(addInfo(getMusic(getFiles(inDir)
files = [x[1] for x in randList]
precision = int(ceil(log(len(files), 10)))
for i, (info, fn) in enumerate(files):
ext = os.path.splitext(fn)[1]
name = '%0*d. %s - %s%s' % (precision, i, info.artist, info.title, ext)
for c in '?*\'"':
name = name.replace(c, '')
fullname = os.path.join(outDir, name)
copy(fn, fullname)

if __name__ == '__main__':
import sys
procFiles(*sys.argv[1:])
___
Tutor maillist  -  Tutor@python.org
http://mail.python.or

Re: [Tutor] py in a nut

2005-10-24 Thread Alan Gauld
> I noticed that the Python in a Nutshell book is version 2.2 and a few 
> years
> old. Does anyone know if there are plans to bring out a new edition

Disclaimer: I know nothing of O'Reilly or Alex Martelli's plans!
But from experience of my own book it takes a good year to 18 months
to do a full re-edit and all the other pre publication chores.

Given the book only came out in 2003 I'd be surprised to see an
update before next year... The problem is that open source software
tends to change so quickly an author can't hope to keep up.
My book started out when Python v1.5.2 was the latest stable release,
by the time it got published it was Python 2.0 and an alpha of 2.1 was
available! I put v2.0 on the CD but the text stayed at 1.5.2

The good news is that with Python 95%+ will still be applicable because
Python has a good tradition of suipporting backwards compatibility.

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] Time - sum/difference

2005-10-24 Thread Alan Gauld

> Anyway, I found a library for working with time zones
> http://pytz.sourceforge.net/

Thanks for pointing this one out, it looks good.

As someone who once commisioned a research paper on Time Zones and
programming I must say this looks like one of the most complete timezone
sites around. However this statement needs to be highlighted with an
anecdote :-)

"Note that if you perform date arithmetic on local times that cross DST 
boundaries,
the results may be in an incorrect timezone "

DST is not an agreed well defined entity. When on a skiing holiday in the 
tiny
country of Andorra the local council decided that the snow was melting
too much in the late afternoon.

Their brilliantly simple solution was to bring forward DST by a week
(a simple announcement on local radio and newspaper!) and the snow
slopes now closed an hour earlier saving the snow from skiers turning
it to slush in the late afternoon sun!

I can't imagine the havoc that created for their computer systems...
But tourism is king in Andorra.

A salutory lesson on how fragile is our grasp on time.

Alan G.

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


Re: [Tutor] about \

2005-10-24 Thread Alan Gauld

> Is there any difference if I remove the '/'

You mean the '\' I assume?

In this case no difference whatsoever because Python 
will keep on looking for the matching closing ']'

> intMatrix2 = [[1,1,2,4,1,7,1,7,6,9],\
> [1,2,5,3,9,1,1,1,9,1],\
> [0,0,5,1,1,1,9,7,7,7]]

> So what is the use of '\'?

\ is the line continuation character. Thus if you need to wrap a line but 
don't want python to interpret it as two lines use a \ character:

>>> print ' here is a long line of text ' + \
... 'extended by another string'
' here is a long line of text extended by another string'

Without the \ char you get an error.

But if there is an open bracket or paren then Python ignores the 
end of line until it finds the closing paren etc.

However many programmers like to put the \ char anyway just to 
indicate that it is a single logical line broken for readability

HTH,

Alan G.




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


Re: [Tutor] about FIND

2005-10-24 Thread Alan Gauld
>  find(s, sub [,start [,end]]) -> in
>
> what does *args mean (especially the '*')?

*args means that a variable number of arguments can be provided.
The exact nature of those being described in the next line.

So:
find =(s,sub)
find(s,sub,start)
find(s,sub,start,stop)

are all valid

> also, in the sub, why put a comma before start?

because start is optional but if you have it there must be a comma
separating it from the previous sub argument. That is the comma
is required as part of the syntax. The square brackets indicate that
start is optional.


> what does 'in' mean?

IT should be 'int'
The arrow shows the return value - in this case the location as an index 
number.

HTH<

Alan G

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


Re: [Tutor] string

2005-10-24 Thread Alan Gauld
> what does the following sentence mean? does it mean i can not use
> double-quoted string?
> SyntaxError: EOL while scanning single-quoted string

No, it means you didn't correctly terminate the string with a matching 
quote.
The error is slightly ambiguous, the word 'single' here means there is only
one quote sign, it is not referring to the use of  '  instead of  " ...

Alan G.


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


Re: [Tutor] dictionary

2005-10-24 Thread Alan Gauld
> A dictionary stores its values based on the keys. Internally Python 
> sorts the keys to make the lookup meet performance expectations.
> 
> You can not expect a dictionary to return keys in the other you added 
> them. If you want that, store the items as tuples in a list.

Or you can sort the keys and iterate over that:

keys = dic.keys()
keys.sort()  # sorts in place!
for key in keys.sort(): print key,dic[key]

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


Re: [Tutor] py in a nut

2005-10-24 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
> Hope this is not too off topic:
> I noticed that the Python in a Nutshell book is version 2.2 and a few 
> years old.  Does anyone know if there are plans to bring out a new 
> edition anytime soon?  I checked the O'reilly page and didnt find 
> anything, also googled it.

AFAIK it is still just a gleam in Alex Martelli's eye. He has recently 
resurfaced on comp.lang.python so maybe he will have time for some writing...we 
can hope!

Kent

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


Re: [Tutor] Help(!) with OOP/Composition from "Learning Python"

2005-10-24 Thread CPIM Ronin

I've been reading about composition vs inheritance, and went back to
"Learning Python" to look at something I found very confusing a year
ago.  Turns out I still find it very confusing :)


Try this example ecology simulation by Kirby Urner:

http://mail.python.org/pipermail/edu-sig/2000-April/000306.html

It does have a bug or two in it, but I was able to find and fix them by 
myself. But the bugs are discussed here if you get stuck:


http://mail.python.org/pipermail/edu-sig/2003-March/002742.html

and here:

http://mail.python.org/pipermail/edu-sig/2003-March/002744.html

Still, simple as it is, it gave me a much more profound grasp of Python 
based OOP than any of Learning Python's examples. I suspect the following 
book might be superb for leaning OOP:


Game Programming With Python (Game Development Series) (Paperback) by Sean 
Riley


In short, study actual simulations (of which games are a major subset)!

RC

_
FREE pop-up blocking with the new MSN Toolbar – get it now! 
http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/


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


[Tutor] py in a nut

2005-10-24 Thread carl.badgley
Hope this is not too off topic:
I noticed that the Python in a Nutshell book is version 2.2 and a few
years old.  Does anyone know if there are plans to bring out a new
edition anytime soon?  I checked the O'reilly page and didnt find
anything, also googled it.
If anyone knows anything let me know.
Thanks,
Carl
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] problem with class overloading (maybe it's just me)

2005-10-24 Thread Matt Richardson
Danny Yoo wrote:

> Hope this helps!

Helped a lot.  Shows that syntax errors aren't always visible (like 
whitespace) and that I should know better than to attempt anything 
before having at least one cup of coffee.

Thanks!
Matt

-- 
Matt Richardson
IT Consultant
College of Arts and Letters
CSU San Bernardino
(909)537-7598

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


Re: [Tutor] help

2005-10-24 Thread Michael Janssen
On 10/24/05, Shi Mu <[EMAIL PROTECTED]> wrote:

> I got confused by the following information from the help for "FIND":
> find(s, *args)
>   find(s, sub [,start [,end]]) -> in

Hello Shi Mu,

this is the help for the function find in the string module, which is
slightly out of date. Better you use the string method find:

###
s = ""
help(s.find)

find(...)
S.find(sub [,start [,end]]) -> int
 ###

so the "in" is simply a typo. find returns an "int" not an "in".
"*args" is the arbitrary number of arguments notation:
http://docs.python.org/tut/node6.html#SECTION00673

which might be misleading and is replaced by "..." in the string
method's online help. The comma before start ist mandatory: *when* you
want to give a "start" argument, you leave out the []-brackets but you
need the comma:

s.find('something', 1)

The builtin documentation ist meant (there are such statements by
Guido van Rossum in the web) as a brief mnemonic for things that are
explained in more detail in the library documentation and the
tutorial.

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


Re: [Tutor] problem with class overloading (maybe it's just me)

2005-10-24 Thread Danny Yoo


> this one fails:
> [EMAIL PROTECTED]:~/wxpy$ cat helloWorld.py
>
> #!/usr/bin/python

Hi Matt,

Ah, good for showing that cat command: it gave enough hints that we can
tell what's going on.


Take out the leading empty space in your file; it's interfering with the
magic line '#!/usr/bin/python'.


The error message you're seeing isn't Python:

> [EMAIL PROTECTED]:~/wxpy$ ./helloWorld.py
> ./helloWorld.py: line 6: syntax error near unexpected token `('
> ./helloWorld.py: line 6: `class MainWindow(wx.Frame):'

It's actually Bourne shell trying to interpret your program as Bourne
shell commands.  *grin*


Here's a session that verifies that those errors are symptomatic of
'/bin/sh' error messages:

##
[EMAIL PROTECTED] ~]$ cat foo.py
class Foo(object):
pass
[EMAIL PROTECTED] ~]$ /bin/sh foo.py
foo.py: line 1: syntax error near unexpected token `('
foo.py: line 1: `class Foo(object):'
##


Hope this helps!

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


Re: [Tutor] dictionary

2005-10-24 Thread Danny Yoo

> > I typed:
> > landUse = {'res': 1, 'com': 2, 'ind': 3, "other" :[4,5,6,7]}
> > and when i checked landUse, I found it become:
> > {'ind': 3, 'res': 1, 'other': [4, 5, 6, 7], 'com': 2}
> > why the order is changed?
>
> the docs warn you about this.


Hi Shi,

By the way, here's a post from a long long time ago that might help make
it clearer what dictionaries are doing:

http://mail.python.org/pipermail/tutor/2002-January/011281.html

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


[Tutor] problem with class overloading (maybe it's just me)

2005-10-24 Thread Matt Richardson
Hi all,

I've started the wxPython tutorials and have hit a problem already. 
When run from IDLE or by calling the script from the command line with

[EMAIL PROTECTED]:~/wxpy$ python helloWorld.py

the script works fine, generating a small text editor.  Making the file 
executable and including the shebang, running

[EMAIL PROTECTED]:~/wxpy$ ./helloWorld.py

generates a cross-hair looking mouse pointer.  Clicking the mouse 
generates the following error:

[EMAIL PROTECTED]:~/wxpy$ ./helloWorld.py
./helloWorld.py: line 6: syntax error near unexpected token `('
./helloWorld.py: line 6: `class MainWindow(wx.Frame):'

Which to me looks like it doesn't know what to do with wx.Frame, or some 
problem in extending the class.  In the hello world example previous to 
this, there's no problem with wx.Frame and the program runs when 
executed from the command line.

Here's the details:
python 2.3.5

this one works:

[EMAIL PROTECTED]:~/wxpy$ cat hello.py
#!/usr/bin/python

import wx

app = wx.PySimpleApp()
frame = wx.Frame(None, -1, "Hello World")
frame.Show(1)
app.MainLoop()



this one fails:
[EMAIL PROTECTED]:~/wxpy$ cat helloWorld.py

#!/usr/bin/python

import wx

class MainWindow(wx.Frame):
 """ We simply derive a new class of Frame. """
 def __init__(self, parent, id, title):
 wx.Frame.__init__(self, parent, wx.ID_ANY, title, 
size=(200,100),
 
style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
 self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
 self.Show(True)

app = wx.PySimpleApp()
frame = MainWindow(None, -1, 'Small editor')
app.MainLoop()


I'm sure it's something simple I'm overlooking, so I'll go get a cup of 
coffee and see if someone with better eyes spots my error.

thanks,
Matt


-- 
Matt Richardson
IT Consultant
College of Arts and Letters
CSU San Bernardino
(909)537-7598

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


Re: [Tutor] what does %25f mean?

2005-10-24 Thread Danny Yoo


On Mon, 24 Oct 2005, Shi Mu wrote:

> what does %25f mean?

Hi Shi Mu,

Without more context, I'd have to guess that this looks like a format
string.  Here's more information about them:

http://www.python.org/doc/lib/typesseq-strings.html


But can you show us where you saw this "%25f" thing though?  Like bytes,
words can be "interpreted" in different ways.  Offhand, another
alternative interpretation is as a url-escaped string:

##
>>> import urllib
>>>
>>> urllib.unquote('%25f')
'%f'
>>>
>>> urllib.quote_plus('hello world, this is a percent: %')
'hello+world%2C+this+is+a+percent%3A+%25'
##

So if you can tell us where you saw '%25f', that'll help us cut down on
the possible explanations that can better account for what you're seeing.


Good luck!

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


[Tutor] help

2005-10-24 Thread Shi Mu
I got confused by the following information from the help for "FIND":
find(s, *args)
   find(s, sub [,start [,end]]) -> in

what does *args mean (especially the '*')?

also, in the sub, why put a comma before start?

what does 'in' mean?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] define vars by iteration

2005-10-24 Thread Luke Jordan
Thanks for this insight into classes. It often takes me a few days to absorb and respond because my job limits the time I can give to programming. But thanks again for taking the time to respond in a meaningful way.
 

I guess I could say that you changed my world when it comes to programming (sorry, low-hanging fruit :)) 
 
Luke 
On 10/20/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
>  Also, I have done what I'm trying to do successfully by populating a> dictionary with class instances named after 
self.name ,> which, after the function runs, I can access this way>  >>> classDictionary["Yard"]> 
>  the thing is I would like to be able to get at Yard's attributes by typing>  >>> Yard.anAttribute> garbage cans>  at the prompt rather than>  >>> Yard = classDictionary["Yard"]
> >>> Yard.anAttribute> garbage cansHi Luke,One thing to note is that we can formally plunk and embed these places insome kind of World:##
class World:   def __init__(self):   self.places = {}   def attach(self, place):   """Given a place, attaches it to the world."""   self.places[
place.name] = place   def lookup(self, name):   return self.places[name]##If each place was aware that it was a part of a world --- that is, if we
embed the World inside each place as a part of a place's state --- thenthings might work out.For example, we might have a north-south corridor:##
class Corridor:   def __init__(self, world, name, northName, southName):   self.world, self.name, self.northName, self.southName = (   world, name, northName, southName)
   def N(self):   return self.world.lookup(self.northName)   def S(self):   return self.world.lookup(self.southName)##What's a little funny about this Corridor definition is that, because a
cooridor knows its in the world, it can also ask the world what place'northName' stands for in its N() method.Here's a small test:##>>> world = World()>>> world.attach
(Corridor(world, "Water cooler",...   north="Stairs", south="Boss Office"))>>> world.attach(Corridor(world, "Stairs",...   north="Wall", south="Water cooler"))
> world.lookup("Water cooler")<__main__.Corridor instance at 0x403a7fcc world.lookup("Water cooler").name'Water cooler'
>>> world.lookup("Water cooler").N()<__main__.Corridor instance at 0x403a7f6c world.lookup("Water cooler").N().name'Stairs'##Another advantage of having a central place is that saving and restoring
the environment is just a matter of pickling the world.  Hmmm... brinypickles... *grin* Sorry, I'm getting distracted by food.Does this make sense?  Please feel free to ask more questions.

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


Re: [Tutor] Time - sum/difference

2005-10-24 Thread Jonas Melian
Anyway, I found a library for working with time zones
http://pytz.sourceforge.net/

Hugo González Monteverde wrote:

> What I usually do is convert them all to UNIX epoch and then substact 
> the values in seconds:
>
> >>> import time
> >>> early = time.time()
> >>> sleep(5)
> >>> time.sleep(5)
> >>> late = time.time()
> >>> print late - early
> 5.7889997959
> >>>
>
>
> Jonas Melian wrote:
>
>> I would get the local time of a country, using UTC (Universal Time 
>> Coordinated) and DST (Daylight SavingTime) of that country.
>>
>> An example, utc time -02:30 and dst +1 :
>>
>> country_utc = datetime.time(2,30)
>> isUTCNegative = True
>> dst = datetime.time(1,0)
>>
>> Now I would the difference of both times.
>> -02:30 + 01:00 -> -01:30
>>
>> Is possible get sum/difference of time values? How?
>>
>> Thanks in advance
>> ___
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>

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


Re: [Tutor] : Threads?

2005-10-24 Thread Kent Johnson
Hugo González Monteverde wrote:
> I have done scripts for decompressing MP3 in the past. I normally follow 
> a fork() exec() subprocess scheme, and this helps me gain about 30% 
> improvement. I'm not an expert, but I have read that CPU time will be 
> better used by several processes than for just one, and while one 
> process is waiting for disk IO and the like, another can be number 
> crunching.
> 
> I have some code, but I will have to look for it and then post it.

IIUC Orri is running on Windows and fork() is not supported there.

Kent

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


Re: [Tutor] about \

2005-10-24 Thread Hugo González Monteverde
Hi,

The '\' character is used to break lines and ask the interpreter to 
treat them as a single line, but Python is smart enough to allow 
breaking lines inside parenthesis and braces...so:

NOT WORKING:

 >>> a, e, i, o, u = 1, 2,
Traceback (most recent call last):
   File "", line 1, in ?
ValueError: unpack tuple of wrong size
 >>> 3, 4, 5
   File "", line 1
 3, 4, 5
 ^
SyntaxError: invalid syntax

WORKS:

 >>> (a, e, i, o, u) = (1, 2,
...   3, 4, 5)
 >>>


What's the difference? The parenthesis... the interpreter sees the open 
parenthesis and assumes correctly that the line is not yet finished.

Hugo

Shi Mu wrote:
> Is there any difference if I remove the '/'
> from the following statement?
> intMatrix2 = [[1,1,2,4,1,7,1,7,6,9],\
>  [1,2,5,3,9,1,1,1,9,1],\
>  [0,0,5,1,1,1,9,7,7,7]]
> print intMatrix2
> I removed one '\' and it still works.
> So what is the use of '\'?
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Time - sum/difference

2005-10-24 Thread Hugo González Monteverde
What I usually do is convert them all to UNIX epoch and then substact 
the values in seconds:

 >>> import time
 >>> early = time.time()
 >>> sleep(5)
 >>> time.sleep(5)
 >>> late = time.time()
 >>> print late - early
5.7889997959
 >>>


Jonas Melian wrote:
> I would get the local time of a country, using UTC (Universal Time 
> Coordinated) and DST (Daylight SavingTime) of that country.
> 
> An example, utc time -02:30 and dst +1 :
> 
> country_utc = datetime.time(2,30)
> isUTCNegative = True
> dst = datetime.time(1,0)
> 
> Now I would the difference of both times.
> -02:30 + 01:00 -> -01:30
> 
> Is possible get sum/difference of time values? How?
> 
> Thanks in advance
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] : Threads?

2005-10-24 Thread Hugo González Monteverde
I have done scripts for decompressing MP3 in the past. I normally follow 
a fork() exec() subprocess scheme, and this helps me gain about 30% 
improvement. I'm not an expert, but I have read that CPU time will be 
better used by several processes than for just one, and while one 
process is waiting for disk IO and the like, another can be number 
crunching.

I have some code, but I will have to look for it and then post it.

I do:

pid = os.fork()
if pid == 0:#child
 os.system("my mp3 decompressor")
 raise SystemExit

Doing this for all files that I have to convert, with up to, say, 5 
subprocesses. Then, on the parent, os.waitpid() will be used to check 
when  subprocesses have terminated and respawned until I run out of files..

I will post some code when I find it.

Hugo


Orri Ganel wrote:
> Kent Johnson wrote:
> 
> 
>>Orri Ganel wrote:
>> 
>>
>>
>>>Hello all,
>>>
>>>I've been working on a program for a week or two now that will convert 
>>>all the wav files in a folder to mp3s, filling the id3 tags with the 
>>>correct information as collected from gracenote.com.  This part works 
>>>fine.  However, the actual conversion to mp3 takes between 30 and 50 
>>>seconds per song, so it's usually about 10 minutes per album.  With this 
>>>in mind, I thought, why not try to use threads so all the conversions 
>>>happen simultaneously?  That way, the whole album will take between 30 
>>>and 50 seconds.  Unfortunately, I can't seem to get a working threaded 
>>>version that significantly reduces the time involved . . . The 
>>>   
>>>
>>
>>The only part you are doing in a thread is the actual conversion. This is 
>>likely to be CPU-intensive so running it in multiple threads may not help - 
>>you still have only the one CPU to run on. To the extent that you can overlap 
>>disk I/O in one conversion with processing in another you may get a win; on 
>>the other hand you could just as well have contention for the disk as you try 
>>to read and write a bunch of files at the same time.
>>
>>The fetch from gracenote.com seems like a better candidate for threading 
>>because there is some latency...but the total time is still probably small 
>>compared to the conversion time.
>>
>>Maybe if you have multiple CPUs you can get a speedup by using as many 
>>threads as CPUs...I'm not sure how os.system() behaves in this case. You may 
>>have to explicitly fork to get a new process.
>>
>>Hmm...come to think of it, os.system() may block other threads, I don't 
>>know...you could try subprocess.Popen() instead.
>>
>>Kent
>>
> 
> Thanks for the tip.  Unfortunately, I only have 1 CPU and not the 
> slightest idea how to code for multiple CPUs in any case.  Looks like 
> I'll just hafta deal with a 10-minute time per album.
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] manipulating list of lists

2005-10-24 Thread Vincent Gulinao
I have a list of lists of constant width (2 rows). I need to:
1. delete sub-lists with None element 
2. sort it by any sub-list index

say: [ ['c','d'], ['g',None], ['a','b',], ['e','f']
if sorted using 2nd index: [ ['a','b'], ['c','d'], ['e','f'] ] (same result for 1st index for this example)

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


Re: [Tutor] about \

2005-10-24 Thread Kent Johnson
Please don't duplicate post to python-tutor and comp.lang.python. You are 
getting two sets of answers to all your questions which wastes the time of 
those kind enough to reply.

Thanks,
Kent

Shi Mu wrote:
> Is there any difference if I remove the '/'
> from the following statement?
> intMatrix2 = [[1,1,2,4,1,7,1,7,6,9],\
>  [1,2,5,3,9,1,1,1,9,1],\
>  [0,0,5,1,1,1,9,7,7,7]]
> print intMatrix2
> I removed one '\' and it still works.
> So what is the use of '\'?
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
http://www.kentsjohnson.com

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


[Tutor] about \

2005-10-24 Thread Shi Mu
Is there any difference if I remove the '/'
from the following statement?
intMatrix2 = [[1,1,2,4,1,7,1,7,6,9],\
 [1,2,5,3,9,1,1,1,9,1],\
 [0,0,5,1,1,1,9,7,7,7]]
print intMatrix2
I removed one '\' and it still works.
So what is the use of '\'?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Modify to Print All Results After Sort (Alan) Or Self Inflected - When runs in MS active python the output is no good

2005-10-24 Thread Alan
I did this and it worked
1. However will be nice to print output into filenames without me using
>
2. Another problem: when run in Linux the output is OK BUT when runs in
windows active python the output is no good

# modify1: PRINT THE ABOVE CALL IT SORTEDkanz.TXT

I commented the last lines in the script:
#write the merged items
#print "writing ",len(hadithItems),"..."
#map(HadithEntry.write,hadithItems)

I added the following


# Ahmad to insert here the print the SORTEDkanz.TXT using
>SORTEDkanz.TXT
#write the merged items
print "writing ",len(hadith2Items),"..."
map(HadithEntry.write,hadith2Items)
print "successMerges=",successMerges
# END Ahmad to insert here the print command


# modify1: PRINT THE ABOVE CALL IT SORTEDkanz.TXT

# Ahmad to insert here the print command

#write the merged items
#print "writing ",len(hadithItems),"..."
#map(HadithEntry.write,hadithItems)
#print "successMerges=",successMerges


# END Ahmad to insert here the print command


will be nice to print SORTEDkanz.TXT, newKanzMater.txt etc
 

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.778 / Virus Database: 525 - Release Date: 10/15/2004
 

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


[Tutor] about FIND

2005-10-24 Thread Shi Mu
I got confused by the following information from the help for "FIND":
find(s, *args)
  find(s, sub [,start [,end]]) -> in

what does *args mean (especially the '*')?

also, in the sub, why put a comma before start?

what does 'in' mean?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] neat join

2005-10-24 Thread Kent Johnson
Vincent Gulinao wrote:
> is there any simple syntax for joining strings such that if any (or all) 
> of the params is white space or None, it won't be included in the 
> resulting string?
> 
> e.g. str1, str2, str3 = "foo", "bar", None, if delimiter is " " would 
> result to "foo bar"; str1, str2 = None, None would result to None.

If all your values are in a list, use a list comprehension to strip out the 
empty ones and join() to make a string:

 >>> def joinNoWs(lst):
 ...   lst = [s for s in lst if s and s.strip() ]
 ...   if lst:
 ... return ' '.join(lst)
 ...   return None
 ...
 >>> joinNoWs( [ "foo", "bar", None ] )
'foo bar'
 >>> joinNoWs( [ None, None ] )

If it's OK to return an empty string instead of None when all the inputs are 
empty, you can do this in one line:

 >>> def joinNoWs(lst):
 ...   return ' '.join( [s for s in lst if s and s.strip()] )
 ...
 >>> joinNoWs( [ None, None ] )
''
 >>> joinNoWs( [ "foo", "bar", None ] )
'foo bar'

Kent

-- 
http://www.kentsjohnson.com

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


[Tutor] neat join

2005-10-24 Thread Vincent Gulinao
is there any simple syntax for joining strings such that if any (or
all) of the params is white space or None, it won't be included in the
resulting string?

e.g. str1, str2, str3 = "foo", "bar", None, if delimiter is " " would
result to "foo bar"; str1, str2 = None, None would result to None.

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


Re: [Tutor] string

2005-10-24 Thread Pujo Aji
please show us the code
 
cheers,
pujo 
On 10/24/05, Shi Mu <[EMAIL PROTECTED]> wrote:
what does the following sentence mean? does it mean i can not usedouble-quoted string?SyntaxError: EOL while scanning single-quoted string
___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

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


[Tutor] string

2005-10-24 Thread Shi Mu
what does the following sentence mean? does it mean i can not use
double-quoted string?
SyntaxError: EOL while scanning single-quoted string
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Modify to Print All Results After Sort

2005-10-24 Thread Alan
Dear Python's Gurus

I have this nice over-my-head scripts

1. It loads two files (daifmaster.txt and sahihmaster.txt)
HELP ONE
Please I NEED to print these unified two sorted files as one = call it
dsmaster.txt
 
2. It load file (Kanzmaster.txt) and sort it
HELP TWO
Please I need to print this sorted kanzmaster.txt and call it
KSmaster.txt

3. Please Explain to me the lines
def addCommand(self,command,callback,flags):

self.callbacks[command]={'callback':callback,'command':command,'flags':f
lags}

def findCallback(self,command):

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import codecs
import re

TYPE_MULTILINE=0x1

class ReaderBase:
def __init__(self):
self.callbacks={}

def addCommand(self,command,callback,flags):

self.callbacks[command]={'callback':callback,'command':command,'flags':f
lags}

def findCallback(self,command):
try:
return self.callbacks[command[0]]
except KeyError:
return None

def processFile(self,path):
#f=open(path, 'r')
f = codecs.open(path, encoding='CP1256', mode='r')
val=''
citem=None
for line in f.readlines():
parts=line.split('|')
if citem!=None:
if citem['flags']&TYPE_MULTILINE:
val+=parts[0]
for part in parts[1:]:
if citem!=None:

citem['callback'](citem['command'],val.strip())
lineparts=part.split(' ',1)
cmd=lineparts[0]
if(len(lineparts)>1):
val=lineparts[1]
else:
val=''
if len(cmd)>0:
citem=self.findCallback(cmd)
else:
citem=None
if citem!=None:
citem['callback'](citem['command'],val.strip())
f.close()

entryCount=0
class HadithEntry:
def __init__(self):
self.keys=[]
self.values=[]

def addValue(self,key,val):
for i in range(len(self.keys)):
if self.keys[i]==key:
self.values[i]=val
return

self.keys.append(key)
self.values.append(val)

def write(self,f=sys.stdout):
global entryCount
entryCount=entryCount+1
for i in range(len(self.keys)):
if not self.keys[i].endswith('-tmp'):

f.write(('|'+self.keys[i]+str(entryCount)+'
'+self.values[i]+'\n').encode('utf-8'))

def getValue(self,key):
for i in range(len(self.keys)):
if self.keys[i]==key:
return self.values[i]
return ''

hadithItems=[]

sortByH_regex_punct = re.compile(u"[ ,،.:()?{}\n.]")
def sortByH(a,b):
a=a.getValue('H-tmp')
b=b.getValue('H-tmp')

#remove punctuation before comparison
#a=re.sub(sortByH_regex_punct,'',a)
#b=re.sub(sortByH_regex_punct,'',b)

if(a==b):
return 0
if(a>b):
return 1
return -1

currentEntry=None
#reads the 40k hadith entries
def fill1stHadithEntries(cmd,val):
global hadithItems
global currentEntry

#the last tag in a record is H
if cmd=='H':
currentEntry=HadithEntry()
hadithItems.append(currentEntry)
a=val
a=re.sub(sortByH_regex_punct,'',a)
currentEntry.addValue('H-tmp',a)

if currentEntry!=None:
currentEntry.addValue(cmd,val)

hadith2Items=[]
#reads the 15K files format
def fill2stHadithEntries(cmd,val):
global hadith2Items
global currentEntry

if cmd=='R':
currentEntry=HadithEntry()

if currentEntry!=None:
currentEntry.addValue(cmd,val)

#The last tag in a record if F
if cmd=='F':
a=currentEntry.getValue('H')
a=re.sub(sortByH_regex_punct,'',a)
currentEntry.addValue('H-tmp',a)
hadith2Items.append(currentEntry)

tempEntry=None
tempEntryPos=0
successMerges=0
#both lists must be sorted, otherwise it will fail.
def mergeHadithEntries(val):
global

Re: [Tutor] dictionary

2005-10-24 Thread Sean Perry
Shi Mu wrote:
> I typed:
> landUse = {'res': 1, 'com': 2, 'ind': 3, "other" :[4,5,6,7]}
> and when i checked landUse, I found it become:
> {'ind': 3, 'res': 1, 'other': [4, 5, 6, 7], 'com': 2}
> why the order is changed?

the docs warn you about this.

A dictionary stores its values based on the keys. Internally Python 
sorts the keys to make the lookup meet performance expectations.

You can not expect a dictionary to return keys in the other you added 
them. If you want that, store the items as tuples in a list.

landUse = [('res', 1), ('com', 2), ('ind', 3), ("other", [4,5,6,7])]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionary

2005-10-24 Thread Jan Erik Moström
Shi Mu <[EMAIL PROTECTED]> 2005-10-24 09:13:

> why the order is changed?

By definition a dictionary has no order.

jem
-- 
Jan Erik Moström, www.mostrom.pp.se
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionary

2005-10-24 Thread Pujo Aji
you work with dictionary.
In dictionary you work with the key to get your value. You don't care about how python arrange the key.
your key here are: 'res', 'com', 'ind', and  'other'
when you want to get your value you just type:
landUse['res'] this you will get 1
landUse['ind'] this you will get 3
 
cheers,
pujo 
On 10/24/05, Shi Mu <[EMAIL PROTECTED]> wrote:
I typed:landUse = {'res': 1, 'com': 2, 'ind': 3, "other" :[4,5,6,7]}and when i checked landUse, I found it become:
{'ind': 3, 'res': 1, 'other': [4, 5, 6, 7], 'com': 2}why the order is changed?___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] dictionary

2005-10-24 Thread Shi Mu
I typed:
landUse = {'res': 1, 'com': 2, 'ind': 3, "other" :[4,5,6,7]}
and when i checked landUse, I found it become:
{'ind': 3, 'res': 1, 'other': [4, 5, 6, 7], 'com': 2}
why the order is changed?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] what does %25f mean?

2005-10-24 Thread Pujo Aji
it will reserve the 25 space for your number.
example:
    print '%25.2f' % (1.222,)
 
It will use 25 space and 2 digit of your 1.222result is: 
 1.22
 
cheers,
pujo 
On 10/24/05, Shi Mu <[EMAIL PROTECTED]> wrote:
what does %25f mean?___Tutor maillist  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] what does %25f mean?

2005-10-24 Thread Shi Mu
what does %25f mean?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor