[Tutor] Re: sorting a 2 gb file- i shrunk it and turned it around

2005-01-28 Thread Scott Melnyk
Hello again!

Thank you everyone for all the help.  The most important step in
dealing with Blast results is getting rid of all the extraneous
information.  The standard result file gives you everything you could
ask for when comparing DNA sequences, however at this step I am
looking for specific data.  Once I have my relevant matches I can go
back and pull out the info for just those matches from the file.

Following Kent's advice I came up with the following (I should set up
defs and a modular system for renewability, that will be next)

import sys   #my system complained when I had them on 1 line as sys, sets, re
import sets  #not sure why but that's another issue (2.4 on win XP)
import re

result=re.compile('^(hg17.+)5\'.+')  #the import part of the line is in the ( )
query=re.compile('^.+(ENST\d+\.\d)+') #matches the line up to the
important transcriptID
   #and groups the ID info

TFILE = open(sys.argv[1], 'r' ) #file to read from
WFILE=open(sys.argv[2], 'w') # file to write to

results={}

for line in TFILE:
isQueryLine= query.match(line)
isResultLine= result.match(line)
if isQueryLine:
current_query = isQueryLine.group(1)
if isResultLine:
key = isResultLine.group(1)
results.setdefault(key, []).append(current_query) # see
explanation below



# Now go through results looking for entries with more than one query
for key, queries in results.iteritems():
  if len(queries) > 1:
print >> WFILE
print >> WFILE, key
for query in queries:
  print >> WFILE, query

I am almost there the program seemed to run well will minimal swapping
and finished in 5 minutes. My output file is only 45 mb.

A sample of the output file is:


hg17_chainMm5_chr15 range=chr7:148238502-148239073
ENST0339563.1
ENST0342196.1
ENST0339563.1
ENST0344055.1

hg17_chainMm5_chr13 range=chr5:42927967-42928726
ENST0279800.3
ENST0309556.3

hg17_chainMm5_chr6 range=chr1:155548627-155549517
ENST0321157.3
ENST0256324.4

hg17_chainMm5_chr13 range=chr1:81386270-81386967
ENST0011649.3
ENST0348636.1

hg17_chainMm5_chr19 range=chr11:56050656-56051559
ENST0341231.1
ENST0341231.1
ENST0331792.1
ENST0341231.1
ENST0341231.1
ENST0331792.1

hg17_chainMm5_chr9 range=chr11:123561223-123562097
ENST0341493.1
ENST0318666.4
ENST0341493.1

I can see where any of the chains appear more than once, which is good
and I am looking for situations like first example where
ENST0339563.1 is the first and third on the list or the fifth
example.
Next step is to cut out the ENST lines that only show up once and wind
up with just the places where there are matches at least twice to a
given transcript (using the ENST0...) ids.  Like in the final
example I only want the first and third so I know it is twice in that
transcript.

Back to it and other things.  Thanks for all the help so far,
Scott
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: sorting a 2 gb file- i shrunk it and turned it around

2005-01-28 Thread Kent Johnson
Scott Melnyk wrote:
Hello again!
Thank you everyone for all the help.
Congratulations on getting this working!
I can see where any of the chains appear more than once, which is good
and I am looking for situations like first example where
ENST0339563.1 is the first and third on the list or the fifth
example.
Next step is to cut out the ENST lines that only show up once and wind
up with just the places where there are matches at least twice to a
given transcript (using the ENST0...) ids.  Like in the final
example I only want the first and third so I know it is twice in that
transcript.
See the tutor thread "Unique items in lists" if you need help with this step, we just had an 
extensive discussion of how to do it.

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


Re: [Tutor] Preffered way to search posix filesystem

2005-01-28 Thread Miles Stevenson
Thanks for the advice! My problem was that the built-in Python docs in Kdevelop 
weren't up-to-date, and 
I had trouble finding walk() in the docs. Here is the approach that I used 
being a python newbie 
(improvements are welcome):



def getfiles(path):
"""Recursively search a path and generate a lit of OGG files found

Takes a filesystem path as an argument. The path is recursively searched for
OGG files. Returns a list of each file found (in absolute path format) with
the first element of the list set to 'start'"""
filelist = ['start']
for root, dirs, files in os.walk(path):
for name in files:
a = os.path.join(root, name)
if os.path.isfile(a) and fnmatch.fnmatch(a, '*.ogg'):
filelist.append(a)
return filelist



What is interesting is that the latest 2.4 Python docs say that walk() returns 
a Tuple, which is untrue. 
It returns a generator object according to type(). This had me heavily confused 
as to how to use 
what was returned from walk() and it took a good hour of troubleshooting to 
figure it out.

-Miles

On Wednesday 26 January 2005 11:27 pm, you wrote:
> Try the os module.  I think this should probably get you there.
> http://docs.python.org/lib/module-os.html
>
> Miles Stevenson wrote:
> >I would like to search filesystem structures using globs on Posix
>
> systems from
>
> >within Python. I don't see an obvious method to do this with in the
>
> standard
>
> >modules. What is the preferred way of doing this? Should I just use
>
> the find
>
> >command or is there a good module out there for searching?
> >
> >Thanks.
>
> __
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com

-- 
Miles Stevenson
[EMAIL PROTECTED]
PGP FP: 035F 7D40 44A9 28FA 7453 BDF4 329F 889D 767D 2F63
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Preffered way to search posix filesystem

2005-01-28 Thread Kent Johnson
Miles Stevenson wrote:
What is interesting is that the latest 2.4 Python docs say that walk() returns a Tuple, which is untrue. 
It returns a generator object according to type(). This had me heavily confused as to how to use 
what was returned from walk() and it took a good hour of troubleshooting to figure it out.
The docs are correct but maybe a little subtle. They say,
walk(  	top[, topdown=True  [, onerror=None]])
walk() generates the file names in a directory tree, by walking the tree either top down or 
bottom up. For each directory in the tree rooted at directory top (including top itself), it yields 
a 3-tuple (dirpath, dirnames, filenames).

To someone familiar with Python generators, the words "generates" and "yields" are strong clues that 
walk is a generator and when you iterate over it you get tuples. If you are not familiar with this 
terminology I can see how it would be confusing.

OTOH there are two examples in the same section that show correct usage...
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Advise...

2005-01-28 Thread Johan Nilsson




Jacob,

Apart from all the other comments you received, here are my thoughts.

I think you could do one more thing to speed up your calculations and
that is to use a more efficient method. The Reimann sum is not a very
efficient. 
One simple method that is rahter popular is Simpson's rule.

The calculations are not much more complicated than what you already
have




You then you just need to make sure that the number of intervals are
even. 

Johan

Jacob S. wrote:
Hi all.
  
  
   Long time no see. (About five days, right?)
  
Anyway, I know the first thing that some of you are going to say is
using eval(). I don't want a whole
  
guilt trip on security risks and all that. I do not want to share the
code with anyone else while it's on my
  
computer, and I sure don't have anyone near me that knows python. I
would be surprised if more than 50
  
people in Portland, IN knew anything about python. So security is not a
problem. I guess what I'm
  
looking for is someone who knows the Reimann Sum better than I do and
can tell me whether I can do
  
something to make it more efficient. It's horribly slow with ten
thousand steps-- I don't know the notation
  
very well, but it loops the loop O(step*(maximum-minimum)) times, which
is horribly sucky.
  
   In case anyone doesn't know, Reimann's sum is the computer's version
of the definite integral, the area
  
under a curve in a particular domain.
  
  
Basic input and output.
  
If a curve is a straight line, say y = x, the area under the line on an
interval can be found by geometric means.
  
However, if you use a parabola, or any other function, say y = 3*x**2,
  
  
  
What is the function? 3*x*x
  
What is the minimum? 2
  
What is the maximum? 5
  
117.000435
  
  
Which, considering that it is supposed to be exactly 117, It's darn
good. Unfortunately, it also takes about
  
10 seconds to do all that.
  
Any suggestions? Any advice? TIA
  
Jacob Schmidt
  
  
  

  
from __future__ import division
  
import psyco
  
psyco.full()
  
fofx = raw_input("What is the function? ")
  
minimum = raw_input("What is the minimum? ")
  
maximum = raw_input("What is the maximum? ")
  
minimum = float(minimum)
  
maximum = float(maximum)
  
total = 0
  
step = 10
  
x = minimum
  
while minimum <= x <= maximum:
  
   area = eval(fofx)*1/step
  
   total = total+area
  
   x = x+1/step
  
print total
  
# 
___
  
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] How does import work?

2005-01-28 Thread Johan Nilsson
Hi all,
I am rather new to python. I am trying to write a program using the 
scipy package. I have come across a problem that confuses me, and I hope 
that someone could give me an hint on how to solve this.

Here is what I do
Start idle
>>> from scipy.signal.signaltools import *
/Traceback (most recent call last):
 File "", line 1, in -toplevel-
   from scipy.signal.signaltools import *
ImportError: No module named signaltools/
So I try the methodic way and this works, giving me access to the 
functions I need

>>> from scipy import *
>>> from scipy.signal import *
>>> from scipy.signal.signaltools import *
Now what confuses me is that when I put the above three lines in a file 
(of course without the >>>) and execute them I get a long error message.

/ Traceback (most recent call last):
 File "/home/johan/pyton/import_test.py", line 5, in -toplevel-
   from scipy.signal import *
 File "/usr/local/lib/python2.3/site-packages/scipy_base/ppimport.py", 
line 270, in __getattr__
   module = self._ppimport_importer()
 File "/usr/local/lib/python2.3/site-packages/scipy_base/ppimport.py", 
line 233, in _ppimport_importer
   raise PPImportError,\
PPImportError: Traceback (most recent call last):
 File "/usr/local/lib/python2.3/site-packages/scipy_base/ppimport.py", 
line 243, in _ppimport_importer
   module = __import__(name,None,None,['*'])
 File "/usr/lib/python2.3/site-packages/scipy/signal/__init__.py", line 
11, in ?
 File "/usr/lib/python2.3/site-packages/scipy/signal/ltisys.py", line 
14, in ?
 File "/usr/local/lib/python2.3/site-packages/scipy_base/ppimport.py", 
line 270, in __getattr__
   module = self._ppimport_importer()
 File "/usr/local/lib/python2.3/site-packages/scipy_base/ppimport.py", 
line 233, in _ppimport_importer
   raise PPImportError,\
PPImportError: Traceback (most recent call last):
 File "/usr/local/lib/python2.3/site-packages/scipy_base/ppimport.py", 
line 243, in _ppimport_importer
   module = __import__(name,None,None,['*'])
 File "/usr/lib/python2.3/site-packages/Numeric/Matrix.py", line 5, in ?
   import LinearAlgebra
 File 
"/usr/local/lib/python2.3/site-packages/Numeric/LinearAlgebra.py", line 
8, in ?
   import lapack_lite
ImportError: 
/usr/local/lib/python2.3/site-packages/Numeric/lapack_lite.so: undefined 
symbol: dgesdd_/

What I dont understand is how can the import statements work, when I 
type them in manually in IDLE and not when I execute them in a file? Has 
anyone come across this type of behavior before?

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


Re: [Tutor] Should this be a list comprehension or something?

2005-01-28 Thread Terry Carroll
On Fri, 28 Jan 2005, Alan Gauld wrote:

> > Oh wait, I know: let's all start writing code in MS Word .doc
> format!
> > Arial for functions, Times New Roman for classes. Who's with me?
> ;-)
> 
> So you've been looking at Eiffel then?
> :-)

I don't get this joke, but it sounds like the basis for it 
would be interesting.  Can you explain?

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


Re: [Tutor] Should this be a list comprehension or something?

2005-01-28 Thread Terry Carroll
Sorry for not responding earlier to thank all the people who weighed in on 
my question.  I'm glad to find that my first take on it was sufficiently 
pythonic.

Alan, I'd never seen the criterion befor that list comprehensions should 
be used to generate other lists.  That's helpful, and I'll keep it in 
mind.

Thanks to Max and Tony for their comments and tests on efficiency.  
Although I was primarily interested in finding out if I was thinking in 
the right way, this was helpful.

Karl, I hadn't thought about overloading, although I knew about the 
possibility.  That's really cool, and quite clear.

Sean, I wasn't even aware of reduce() before.  Thanks, I'll look into 
that.




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


[Tutor] Naming conventions (was: Should this be a list comprehension or something?

2005-01-28 Thread Terry Carroll
On Wed, 26 Jan 2005, Sean Perry wrote:

> And now, for the pedant in me. I would recommend against naming
> functions with initial capital letters. In many languages, this implies
> a new type (like your Water class). so CombineWater should be combineWater.

I hate hate hate hate hate camelcase and will never use it.  In my book,
if the name has *any* capitals in it, the first letter is capitalized,
too.  Anything else is unaesthetic.  

To me, when I have names that are composed of multiple words (say, "rice
quantity"), I have two approaches: distinguishing the words by case 
(RiceQuantity) or separating by underscores (rice_quantity).

I never confuse classes/instances and methods, because I use noun phrases
for classes and instances (HeatedWater, VerifiedInput) and verb phrases
for the methods (CombineWater, CookRice).  I suppose I could get
confusion, for example, when the combination either a noun phrase or 
verb phrase (SoundOut: is that a name describing the Sound that's being 
put Out, or is it a method that's is tentatively Sounding Out somthing?) 
but so far that hasn't been an issue for me.

Of course in my case, I write code only for myself, so I have the luxury 
of not worrying about what Joe in the next cubicle is doing, and what Jane 
will do when she's trying to read Bob's and my code together.  So I have 
the luxury of turning my nose up at camelCase.

I should add that, the one time I made changes to someone else's Python
code for release (a minor patch to nntplib.py), I used the same case
conventions already in place in the module.

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


Re: [Tutor] Naming conventions

2005-01-28 Thread Kent Johnson
Terry Carroll wrote:
On Wed, 26 Jan 2005, Sean Perry wrote:

And now, for the pedant in me. I would recommend against naming
functions with initial capital letters. In many languages, this implies
a new type (like your Water class). so CombineWater should be combineWater.

I hate hate hate hate hate camelcase and will never use it.  In my book,
if the name has *any* capitals in it, the first letter is capitalized,
too.  Anything else is unaesthetic.  

To me, when I have names that are composed of multiple words (say, "rice
quantity"), I have two approaches: distinguishing the words by case 
(RiceQuantity) or separating by underscores (rice_quantity).
Separating with underscores is quite common in the Python community, actually it is the preferred 
spelling for library modules. So maybe you should adopt that, just to reduce the confusion when your 
code does have an encounter with the outside world :-)

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


[Tutor] Control flow

2005-01-28 Thread Gilbert Tsang
Hi there, I have this logic that I cannot wrap my mind it:
def go_jogging():
   # go out and jog
   return
if ( bad_weather =='y' ):
   # ask user only if weather is bad.
   b = input ( "Weather is really bad, still go out to jog?[y/n]" )
   if b == 'y':
  go_jogging()
   else:
   # program should exit now
else:
   go_jogging()
 

I can't get the program to stop processing further in the middle 
(apparently neither exit nor goto-label exist in Python, sorry for the 
C++ mindset) so I used exception to achieve what I want. I know in that 
example you could probably manipulate the logic so that program ends at 
the bottom of the if-tree. My question is then how to exit in the middle 
of a if-then-else tree? Thanks, Gilbert.

try:
   if ( bad_weather =='y' ):
   b = input ( "Weather is really bad, still go out to jog?[y/n]" )
   if b == 'y':
   go_jogging()
   else:
   raise Exception( "quit" )
   else:
   go_jogging()
except Exception, inst:
   print "Program exits now"
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Control flow

2005-01-28 Thread Orri Ganel
Gilbert Tsang wrote:
Hi there, I have this logic that I cannot wrap my mind it:
def go_jogging():
   # go out and jog
   return
if ( bad_weather =='y' ):
   # ask user only if weather is bad.
   b = input ( "Weather is really bad, still go out to jog?[y/n]" )
   if b == 'y':
  go_jogging()
   else:
   # program should exit now
else:
   go_jogging()
 

I can't get the program to stop processing further in the middle 
(apparently neither exit nor goto-label exist in Python, sorry for the 
C++ mindset) so I used exception to achieve what I want. I know in 
that example you could probably manipulate the logic so that program 
ends at the bottom of the if-tree. My question is then how to exit in 
the middle of a if-then-else tree? Thanks, Gilbert.

try:
   if ( bad_weather =='y' ):
   b = input ( "Weather is really bad, still go out to jog?[y/n]" )
   if b == 'y':
   go_jogging()
   else:
   raise Exception( "quit" )
   else:
   go_jogging()
except Exception, inst:
   print "Program exits now"
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
Well, if its in a function you can just do return instead of  raise 
Exception("quit") since the function exits once it returns something.  
It's sort of the same as the following:

Say you have a recursive function  fact(n) which takes in a number and 
returns the factorial of that number.  One way to code this would be:

def fact(n):
   if n > 3:
  return n*fact(n-1)
   else:
  return 2*n
However, since the function 'exits' after a  return statement, it saves 
space in general to do the following:

def fact(n):
   if n > 3:
  return n*fact(n-1)
   return 2*n
Because the only way  return 2*n will be reached is if n is smaller than 
or equal to three, which is what we wanted anyway.

BTW, the way this function works is like this:  Let's say you want to 
calculate fact(10).  10 is greater than 3, so the program calculates 
10*fact(9) and so on until fact(3) is reached, at which point it will 
return 10*(9*(8*(7*(6*(5*(4*(6))) (6 is 2 * 3). or the factorial of 10.

I probably didn't do too good a job explaining that, and that's probably 
not the most efficient implementation (it breaks @ around fact(1000) by 
default, and around  fact(11462) when you use  
sys.setrecursionlimit(2000) (11462 is as high as it'll go on my 
machine)), so please feel free to ask questions.

HTH,
Orri
--
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Control flow

2005-01-28 Thread Orri Ganel
Gilbert Tsang wrote:
Hi there, I have this logic that I cannot wrap my mind it:
def go_jogging():
   # go out and jog
   return
if ( bad_weather =='y' ):
   # ask user only if weather is bad.
   b = input ( "Weather is really bad, still go out to jog?[y/n]" )
   if b == 'y':
  go_jogging()
   else:
   # program should exit now
else:
   go_jogging()
 

I can't get the program to stop processing further in the middle 
(apparently neither exit nor goto-label exist in Python, sorry for the 
C++ mindset) so I used exception to achieve what I want. I know in 
that example you could probably manipulate the logic so that program 
ends at the bottom of the if-tree. My question is then how to exit in 
the middle of a if-then-else tree? Thanks, Gilbert.

try:
   if ( bad_weather =='y' ):
   b = input ( "Weather is really bad, still go out to jog?[y/n]" )
   if b == 'y':
   go_jogging()
   else:
   raise Exception( "quit" )
   else:
   go_jogging()
except Exception, inst:
   print "Program exits now"
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
Well, if its in a function you can just do return instead of  raise 
Exception("quit") since the function exits once it returns something.  
It's sort of the same as the following:

Say you have a recursive function  fact(n) which takes in a number and 
returns the factorial of that number.  One way to code this would be:

def fact(n):
   if n > 3:
  return n*fact(n-1)
   else:
  return 2*n
However, since the function 'exits' after a  return statement, it saves 
space in general to do the following:

def fact(n):
   if n > 3:
  return n*fact(n-1)
   return 2*n
Because the only way  return 2*n will be reached is if n is smaller than 
or equal to three, which is what we wanted anyway.

BTW, the way this function works is like this:  Let's say you want to 
calculate fact(10).  10 is greater than 3, so the program calculates 
10*fact(9) and so on until fact(3) is reached, at which point it will 
return 10*(9*(8*(7*(6*(5*(4*(6))) (6 is 2 * 3). or the factorial of 10.

I probably didn't do too good a job explaining that, and that's probably 
not the most efficient implementation (it breaks @ around fact(1000) by 
default, and around  fact(11462) when you use  
sys.setrecursionlimit(2000) (11462 is as high as it'll go on my 
machine)), so please feel free to ask questions.

HTH,
Orri
--
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Should this be a list comprehension or something?

2005-01-28 Thread Alan Gauld
> > So you've been looking at Eiffel then?
> > :-)
> 
> I don't get this joke, but it sounds like the basis for it 
> would be interesting.  Can you explain?

Bertrand Meyer, the inventor of Eiffel uses rich text to display
code in his books. The commercial Eiffel IDE that his company 
ISE sells used to display the code the same way. Thus different 
fonts were used for comments, keywords etc as well as the 
usual syntax colouring. I note that the freeware version of the 
tool seems to be more conventional in approach!

The best way to see what I mean is probably to visit 

http://archive.eiffel.com/doc/manuals/technology/oosc/acrobat.html

and view the pdf files. Unlike most programming books the code 
is not in a fixed space font and the original ISE IDE copied 
the books style...

As an aside Meyer's book Object Oriented Software Construction 
is huge (1200+ pages) but is also one of the very best books 
on OOP anywhere. (Even is all the code is in Eiffel!)

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


Re: [Tutor] Should this be a list comprehension or something?

2005-01-28 Thread Alan Gauld
> I don't get this joke, but it sounds like the basis for it 
> would be interesting.  Can you explain?

After sending my last message I was browsing the Eiffel site and 
found an example of the IDE.

Its here:

http://archive.eiffel.com/eiffel/nutshell.html

and you scroll down to the question:

What does a class look like?

The code under that is a direct cut n paste from their 
commercial editor. (The freeware version is in a screenshot
a little bit above...)

Note the use of a proportional font(Arial?) as well as the 
documentation like style of Eiffel in general...

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


RE: [Tutor] Control flow

2005-01-28 Thread Smith, Jeff
One way out of the top level is to call
sys.exit(1)

-Original Message-
From: Orri Ganel [mailto:[EMAIL PROTECTED] 
Sent: Friday, January 28, 2005 4:26 PM
To: Gilbert Tsang; Tutor@python.org
Subject: Re: [Tutor] Control flow


Gilbert Tsang wrote:

> Hi there, I have this logic that I cannot wrap my mind it:
>
> def go_jogging():
># go out and jog
>return
>
> if ( bad_weather =='y' ):
># ask user only if weather is bad.
>b = input ( "Weather is really bad, still go out to jog?[y/n]" )
>if b == 'y':
>   go_jogging()
>else:
># program should exit now
> else:
>go_jogging()
>  
> 
> I can't get the program to stop processing further in the middle
> (apparently neither exit nor goto-label exist in Python, sorry for the

> C++ mindset) so I used exception to achieve what I want. I know in
> that example you could probably manipulate the logic so that program
> ends at the bottom of the if-tree. My question is then how to exit in 
> the middle of a if-then-else tree? Thanks, Gilbert.
>
> try:
>if ( bad_weather =='y' ):
>b = input ( "Weather is really bad, still go out to jog?[y/n]"
)
>if b == 'y':
>go_jogging()
>else:
>raise Exception( "quit" )
>else:
>go_jogging()
> except Exception, inst:
>print "Program exits now" 
> ___
> 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] Naming conventions

2005-01-28 Thread Terry Carroll
On Fri, 28 Jan 2005, Kent Johnson wrote:

> Separating with underscores is quite common in the Python community,
> actually it is the preferred spelling for library modules. So maybe you
> should adopt that, just to reduce the confusion when your code does have
> an encounter with the outside world :-)

I'm a lawyer by trade; my work is *supposed* to confuse the outside world!

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


Re: [Tutor] Should this be a list comprehension or something?

2005-01-28 Thread Alan Gauld
> Alan, I'd never seen the criterion befor that list comprehensions
should
> be used to generate other lists.

Its not so much a criterion that they *should* be used that way,
its just that its what they do. A list comprehension creates a list!
Thats why they are called *list* comprehensions. :-)

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] Should this be a list comprehension or something?

2005-01-28 Thread Terry Carroll
On Fri, 28 Jan 2005, Alan Gauld wrote:

> Its not so much a criterion that they *should* be used that way,
> its just that its what they do. A list comprehension creates a list!
> Thats why they are called *list* comprehensions. :-)

See, I'd always figured that the reason it was called a list 
comprehension was because the list comprehension operated on a list, 
and the operation was comprehension.

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


Re: [Tutor] Control flow

2005-01-28 Thread Alan Gauld
SEveral solutions here.

The best is to restructure the code a little:

> def go_jogging():
> # go out and jog
> return
>
> if not bad_weather == 'y':  # where is this initially set BTW?
go_jogging()
  else
> # ask user only if weather is bad.
> b = input ( "Weather is really bad, still go out to jog?[y/n]" )
> if b == 'y':
>go_jogging()

Its shorter, simpler and makes the most common case the default
(assuming that bad weather is the exception!)

> I can't get the program to stop processing further in the middle

Good, that would be really bad practice from a structured programming
point of view. :-)
But if you really, really must, you could always call

raise SystemExit

which bombs out more or less immediately - like exit() in C

> C++ mindset) so I used exception to achieve what I want.

Yes thats ok, and the exception to use is already there...

> example you could probably manipulate the logic so that program ends
at
> the bottom of the if-tree. My question is then how to exit in the
middle
> of a if-then-else tree?

You should never need to. One of the things that structured
programming
(Edsgar Dijkstra to be precise) showed was that you can *always*
rearrange
things so that goto's and intermediate exits are not needed and indeed
can introduce an extra level of complexity and error.

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] Control flow

2005-01-28 Thread Alan Gauld

> One way out of the top level is to call
> sys.exit(1)

Which works, but you need to import sys first.

Using

raise SystemExit

avoids the need for an import.

Alan G.


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


[Tutor] Diffing two files.

2005-01-28 Thread Ertl, John
All,

I have two text files that should contain a section of text that is the
same.  Luckily the section of text has a defined beginning and end.  It
looks like the most straightforward thing would be to read the targeted text
from each file (only 50 lines or so) into lists and then compare the lists.
I would think I could use sets to find a unique list (hopefully there would
not be anything)...or I could do line by line comparison.  Any advise on
what is the better method.  Should I avoid the list comparison approach...is
there a built in way of comparing entire files instead of dealing explicitly
with the lines? 

Thanks,

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


Re: [Tutor] Naming conventions

2005-01-28 Thread Kent Johnson
Terry Carroll wrote:
On Fri, 28 Jan 2005, Kent Johnson wrote:

Separating with underscores is quite common in the Python community,
actually it is the preferred spelling for library modules. So maybe you
should adopt that, just to reduce the confusion when your code does have
an encounter with the outside world :-)

I'm a lawyer by trade; my work is *supposed* to confuse the outside world!
Then you are using the wrong language entirely. May I suggest Brainf*ck or 
INTERCAL or Whitespace?
http://www.thefreecountry.com/compilers/esoteric.shtml
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Diffing two files.

2005-01-28 Thread Kent Johnson
You don't really say what you are trying to accomplish. Do you want to identify the common text, or 
find the pieces that differ?

If the common text is always the same and you know it ahead of time, you can just search the lines 
of each file to find it.

If you need to identify the common part, difflib might be useful. There is an example on this page 
of finding matching blocks of two sequences:
http://docs.python.org/lib/sequencematcher-examples.html

In your case the sequences will be lists of lines rather than strings (which are sequences of 
characters)

Kent
Ertl, John wrote:
All,
I have two text files that should contain a section of text that is the
same.  Luckily the section of text has a defined beginning and end.  It
looks like the most straightforward thing would be to read the targeted text
from each file (only 50 lines or so) into lists and then compare the lists.
I would think I could use sets to find a unique list (hopefully there would
not be anything)...or I could do line by line comparison.  Any advise on
what is the better method.  Should I avoid the list comparison approach...is
there a built in way of comparing entire files instead of dealing explicitly
with the lines? 

Thanks,
John Ertl 
___
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] Diffing two files.

2005-01-28 Thread Ertl, John
Kent

What I need to do is find what should be common and see if it really is.  I
have two output files...The output files will have a bunch of systems stuff
then the text of interest and then a bunch more systems stuff.  The systems
stuff may be different for each file but the text of interest will always
have a fixed line in front of it and behind it.  

The idea is to get the text of interest (using the known beginning and
ending flags in the text) from each file and then check to make sure the
text of interest is the same in both files. 

I have not done much text stuff so this is new territory for me.  I will
take a look at difflib.

Thanks again

John Ertl

Simplified example of a text files.

Sldfsdf
Sdfsdfsf
Sdfsdfsdfwefs
Sdcfasdsgerg
Vsadgfasgdbgdfgsdf
-Beginning flag
This
Text
Should be
The
Same in the other file.
-Ending flag
Sdfsdfsdfsd
Sdfsdfsdfasd
Sdfsadfsdf
Sdfsadfasdf
Sdfsdfasd
Sdfasdf
s


-Original Message-
From: Kent Johnson [mailto:[EMAIL PROTECTED]
Sent: Friday, January 28, 2005 15:23
Cc: Tutor@python.org
Subject: Re: [Tutor] Diffing two files.

You don't really say what you are trying to accomplish. Do you want to
identify the common text, or
find the pieces that differ?

If the common text is always the same and you know it ahead of time, you can
just search the lines
of each file to find it.

If you need to identify the common part, difflib might be useful. There is
an example on this page
of finding matching blocks of two sequences:
http://docs.python.org/lib/sequencematcher-examples.html

In your case the sequences will be lists of lines rather than strings (which
are sequences of
characters)

Kent

Ertl, John wrote:
> All,
>
> I have two text files that should contain a section of text that is the
> same.  Luckily the section of text has a defined beginning and end.  It
> looks like the most straightforward thing would be to read the targeted
text
> from each file (only 50 lines or so) into lists and then compare the
lists.
> I would think I could use sets to find a unique list (hopefully there
would
> not be anything)...or I could do line by line comparison.  Any advise on
> what is the better method.  Should I avoid the list comparison
approach...is
> there a built in way of comparing entire files instead of dealing
explicitly
> with the lines?
>
> Thanks,
>
> John Ertl
> ___
> 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 maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Please Help with Python Script for Xbox Media Center

2005-01-28 Thread Rodney Butler
I have written a script that is designed to load when you start your xbox, 
it gets a list of your music playlists then lets you select which one to 
load, shuffle and play, then the script exits.  What I need is for the 
script to automatically select the highlighted playlist if there is no user 
input for 10 seconds.  Been working on it for 3 days, no luck.  Help.

import os, xbmc, xbmcgui, time
try: Emulating = xbmcgui.Emulating
except: Emulating = False
#get actioncodes from keymap.xml
ACTION_PREVIOUS_MENU = 10
class MyClass(xbmcgui.Window):
def __init__(self):
   if Emulating: xbmcgui.Window.__init__(self)
		self.addControl(xbmcgui.ControlImage(0,0,720,480, 
"c:\\scripts\\background.jpg"))

# Make the List
self.list = xbmcgui.ControlList(290, 300, 150, 150)
self.addControl(self.list)
#Define Playlist Directory here
path = 'c:\\albums\\playlists\\'
list = os.listdir(path)
intcount = len(list)
for a in list :
self.list.addItem(a)
self.setFocus(self.list)
   def onAction(self, action):
if action == ACTION_PREVIOUS_MENU:
self.close()
def onControl(self, control):
if control == self.list:
item = self.list.getSelectedItem()
path1 = 'c:\\albums\\playlists\\'
xbmc.PlayList(0).load(path1+item.getLabel())
xbmc.PlayList(0).shuffle()
xbmc.Player().play()
self.close()
mydisplay = MyClass()
mydisplay.doModal()
del mydisplay
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] XBMC Python Script HELP! Needed

2005-01-28 Thread Rodney Butler
I have written a script that is designed to load when you start your xbox, 
it gets a list of your music playlists then lets you select which one to 
load, shuffle and play, then the script exits.  What I need is for the 
script to automatically select the highlighted playlist if there is no user 
input for 10 seconds.  Been working on it for 3 days, no luck.  Help.

import os, xbmc, xbmcgui, time
try: Emulating = xbmcgui.Emulating
except: Emulating = False
#get actioncodes from keymap.xml
ACTION_PREVIOUS_MENU = 10
class MyClass(xbmcgui.Window):
def __init__(self):
  if Emulating: xbmcgui.Window.__init__(self)
self.addControl(xbmcgui.ControlImage(0,0,720,480, 
"c:\\scripts\\background.jpg"))

# Make the List
self.list = xbmcgui.ControlList(290, 300, 150, 150)
self.addControl(self.list)
#Define Playlist Directory here
path = 'c:\\albums\\playlists\\'
list = os.listdir(path)
intcount = len(list)
for a in list :
self.list.addItem(a)
self.setFocus(self.list)
  def onAction(self, action):
if action == ACTION_PREVIOUS_MENU:
self.close()
def onControl(self, control):
if control == self.list:
item = self.list.getSelectedItem()
path1 = 'c:\\albums\\playlists\\'
xbmc.PlayList(0).load(path1+item.getLabel())
xbmc.PlayList(0).shuffle()
   xbmc.Player().play()
self.close()
mydisplay = MyClass()
mydisplay.doModal()
del mydisplay
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please Help with Python Script for Xbox Media Center

2005-01-28 Thread Danny Yoo


On Fri, 28 Jan 2005, Rodney Butler wrote:

> I have written a script that is designed to load when you start your
> xbox, it gets a list of your music playlists then lets you select which
> one to load, shuffle and play, then the script exits.  What I need is
> for the script to automatically select the highlighted playlist if there
> is no user input for 10 seconds.


Hi Rodney,

It appears that you're using some kind of GUI interface called 'xbmcgui'.
Only a few of us have done xbmc stuff; you may have better luck asking
from a XBMC-specific game forum.

You can set up a thread to do something in the background;  I did a quick
Google search and picked out:

http://www.ek-clan.vxcomputers.com/flashscripts/AQTbrowser.py

This appears to use threads to implement a http timeout, and you can
probably adapt this to automatically select a playlist if the user hasn't
selected one in time.



Without having an XBOX, however, I have no way of testing this. So we
recommend you talk with someone on one of the forums.

Oh!  I see that you've just posted on:

http://www.xboxmediaplayer.de/cgi-bin/forums/ikonboard.pl?s=0d6bed0f9584b8406d5f458ffaeb187c;act=ST;f=21;t=10108

and have gotten a similar advice to use threads.  Ok, good.  Use threads.
*grin*



If you have more questions, please feel free to ask.  But the folks on
that forum probably know better than us, so try them first.


Best of wishes to you!


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


Re: [Tutor] Should this be a list comprehension or something?

2005-01-28 Thread Jacob S.

Its not so much a criterion that they *should* be used that way,
its just that its what they do. A list comprehension creates a list!
Thats why they are called *list* comprehensions. :-)
See, I'd always figured that the reason it was called a list
comprehension was because the list comprehension operated on a list,
and the operation was comprehension.
It can easily be checked by...
Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
a = range(10)
b = [x for x in a if x % 2 == 0]
c = ['12','21','14','13']
d = [a[2] for x in c]
a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b
[0, 2, 4, 6, 8]
c
['12', '21', '14', '13']
d
[2, 2, 2, 2]
type(a)

type(b)

type(c)

type(d)


Everything I did with list comprehensions above shows that list 
comprehensions return a list.
Mostly it is evidenced by the type function...

Maybe, this post is silly?
Oh, well.
Jacob 

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


Re: [Tutor] Naming conventions (was: Should this be a list comprehension or something?

2005-01-28 Thread Jacob S.
You're my best friend. Everyone else looves camelCase, and I hate it too. It 
doesn't make sense. It doesn't fit English.
It doesn't fit Spanish. It doesn't fit any other language AFAIK, so why 
should a human (who uses spoken language) to computer interpreter use a 
naming convention that doesn't match spoken language? That's my opinion.

Jacob Schmidt

On Wed, 26 Jan 2005, Sean Perry wrote:
And now, for the pedant in me. I would recommend against naming
functions with initial capital letters. In many languages, this implies
a new type (like your Water class). so CombineWater should be 
combineWater.
I hate hate hate hate hate camelcase and will never use it.  In my book,
if the name has *any* capitals in it, the first letter is capitalized,
too.  Anything else is unaesthetic.
To me, when I have names that are composed of multiple words (say, "rice
quantity"), I have two approaches: distinguishing the words by case
(RiceQuantity) or separating by underscores (rice_quantity).
I never confuse classes/instances and methods, because I use noun phrases
for classes and instances (HeatedWater, VerifiedInput) and verb phrases
for the methods (CombineWater, CookRice).  I suppose I could get
confusion, for example, when the combination either a noun phrase or
verb phrase (SoundOut: is that a name describing the Sound that's being
put Out, or is it a method that's is tentatively Sounding Out somthing?)
but so far that hasn't been an issue for me.
Of course in my case, I write code only for myself, so I have the luxury
of not worrying about what Joe in the next cubicle is doing, and what Jane
will do when she's trying to read Bob's and my code together.  So I have
the luxury of turning my nose up at camelCase.
I should add that, the one time I made changes to someone else's Python
code for release (a minor patch to nntplib.py), I used the same case
conventions already in place in the module.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

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