[Tutor] A simpler mousetrap

2004-12-16 Thread Liam Clarke
Hi all, 

I'm writing some code, and I want to take a given path + filename, and
change the file extension to *.bak.

In doing so, (entirely internal this function), I am assuming -

That the file will always have an extension
Thathe extension will vary
But, it will follow the general DOS format of name.ext

So, I came up with this -

a="./tc/arc/gab.pct"

x=a.replace(a[a.rfind('.'):len(a)],'.bak')

x="./tc/arc/gab.bak"

So, it works, but it feels a bit, well, hacky to me. Not nearly hacky
as using an regex though ; )

I thought about 

a="./tc/arc/gab.pct"

aList=a.split('.')
aList[-1]='bak'
a=".".join(aList)

but I'm wondering if there's a simpler way, as there usually seems to
be, and it's always so obvious once I'm shown it, like 6 down - Six on
vehicle live in the manse (VI + car). Obvious once you know.

Regards,

Liam Clarke
-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] am I missing another simpler structure?

2004-12-16 Thread Brian van den Broek
Liam Clarke said unto the world upon 2004-12-16 02:05:
Alright, so that was a quick example, but

return not x % 2

A light dawns.
On Thu, 16 Dec 2004 15:58:38 +0900, Guillermo Fernandez Castellanos
<[EMAIL PROTECTED]> wrote:
Well...

I find multiple returns to be rather useful
def isOdd(x):
   if not x % 2: return False
   return True
I find this easier though...
def isOdd(x):
   return not x % 2
Enjoy,
Guille
Hi Liam, Guille, and all,
Liam, the relationship between the code you put up and the suggestion 
Guille made closely parallel the my code from Marc's check_range thread 
and the suggestion DogWalker made. Thinking that our common slip in 
these two chucks might be more common in my code than I can currently 
recognize is what moved me to start the present thread.

If my original bit of code, the structure was like:
output_value = False
if condition:
output_value = True
return output_value
Mine would be like yours if transformed to:
if condition:
return True
return False
It seems to me that the two structures are inter-substitutable without 
difference to outcome (speed, readability, and other 'pragmatics' aside 
-- my structure will be slower for the assignments, for instance).

What makes me lean toward mine still? I'd encountered a general 
injunction to avoid multiple exit point somewhere on the wild web 
(cannot recall where). At the time, it didn't make sense to me. But, as 
I posted earlier today in reply to Kent, I was burned by multiple exits 
a while ago. (To be fair, by multiple exits and overlong functions which 
obscured the multiplicity from me -- stupid low res monitor!)

The best discussion I found with a quick google was 
. Much of the 
anti-multiple-exits rational there only applies to languages like C that 
make the coder manage the memory. But "Having MultipleReturns is the 21 
century equivalent of GotoConsideredHarmful" resonates with me. The idea 
is that multiple returns, particularly when separated by numerous lines 
of code, makes for spaghetti code.

('Goto Considered Harmful' is a famous short and fairly accessible paper 
[no math or code] by Dijkstra arguing that the use of Goto's makes code 
hard to follow . When I first 
started with Python, I'd not programmed in a decade or so after some 
highschool BASIC. My first reaction was "where's the bleedin' goto?". 
Once I coded some and noticed substantially less frustration than I 
recall from managing my gotos, I learned to appreciate that there wasn't 
a goto after all.)

Anyway, that's plenty of ramble for ce soir.
But, Liam, this is the first post I've made in your direction since I 
read you mention it: congrats for your new son!

Best to all,
Brian vdB
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Re: A simpler mousetrap

2004-12-16 Thread Liam Clarke
x=os.path.splitext(a)[0]+'.bak'

Ah, jolly good, looks a bit simpler. Thanks!

Regards,

Liam Clarke

On Thu, 16 Dec 2004 09:44:03 +0100, Wolfram Kraus
<[EMAIL PROTECTED]> wrote:
> Liam Clarke wrote:
> > Hi all,
> >
> > I'm writing some code, and I want to take a given path + filename, and
> > change the file extension to *.bak.
> >
> > In doing so, (entirely internal this function), I am assuming -
> >
> > That the file will always have an extension
> > Thathe extension will vary
> > But, it will follow the general DOS format of name.ext
> >
> > So, I came up with this -
> >
> > a="./tc/arc/gab.pct"
> >
> > x=a.replace(a[a.rfind('.'):len(a)],'.bak')
> >
> > x="./tc/arc/gab.bak"
> >
> > So, it works, but it feels a bit, well, hacky to me. Not nearly hacky
> > as using an regex though ; )
> >
> > I thought about
> >
> > a="./tc/arc/gab.pct"
> >
> > aList=a.split('.')
> > aList[-1]='bak'
> > a=".".join(aList)
> >
> > but I'm wondering if there's a simpler way, as there usually seems to
> > be, and it's always so obvious once I'm shown it, like 6 down - Six on
> > vehicle live in the manse (VI + car). Obvious once you know.
> >
> > Regards,
> >
> > Liam Clarke
> 
> Hey Liam!
> 
> The os.path module is your friend, especially split and splitext:
> http://docs.python.org/lib/module-os.path.html
> 
> HTH,
> Wolfram
> 
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A simpler mousetrap

2004-12-16 Thread Kent Johnson
As Wolfram pointed out, os.path.splitext() is a good way to do this. It is also more robust than the 
other solutions because it does the right thing if there is no extension on the original file name. 
I just want to say that your first solution can be written much more simply as
x=a[:a.rfind('.')] + '.bak'

Kent
Liam Clarke wrote:
Hi all, 

I'm writing some code, and I want to take a given path + filename, and
change the file extension to *.bak.
In doing so, (entirely internal this function), I am assuming -
That the file will always have an extension
Thathe extension will vary
But, it will follow the general DOS format of name.ext
So, I came up with this -
a="./tc/arc/gab.pct"
x=a.replace(a[a.rfind('.'):len(a)],'.bak')
x="./tc/arc/gab.bak"
So, it works, but it feels a bit, well, hacky to me. Not nearly hacky
as using an regex though ; )
I thought about 

a="./tc/arc/gab.pct"
aList=a.split('.')
aList[-1]='bak'
a=".".join(aList)
but I'm wondering if there's a simpler way, as there usually seems to
be, and it's always so obvious once I'm shown it, like 6 down - Six on
vehicle live in the manse (VI + car). Obvious once you know.
Regards,
Liam Clarke
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Multiple returns in a function

2004-12-16 Thread Kent Johnson
Brian van den Broek wrote:
Kent Johnson said unto the world upon 2004-12-15 20:16:
 > I would write
 > def is_leap_year(year):
 > try:
 > datetime.date(year, 2, 29)
 > return True
 > except ValueError:
 > return False
Not an adherent of the "only one exit point" doctrine then, hey? I spent 
a while a few weeks ago with a bug in a function that happened because 
I'd not noticed that I had two return statements, so I'm leery of this 
at the moment. (I concede if the function was long enough to hide that 
from me, it was probably too long.) I also like the conceptual purity of 
one way in and one way out. But, in my code above, that is indeed 
purchased at the cost of the ugly and a bit anomalous assignment of True.
Right you are. I wondered if anyone would notice :-)
I find multiple returns very handy. They can often reduce the indentation of a block or eliminate 
the need for flag variables. And I don't see any benefit from having a single return.

One simple use of multiple returns is to handle different conditions in a function. Especially for 
error conditions. I like to handle special cases early in a function. (This is the GuardClause idiom 
from the web page you cited: http://c2.com/cgi/wiki?GuardClause) For example something like

def fn(a, b):
  if not a:
return None
  if b == 0:
return 0
  # Calculate result from a and b
  return result
Without the multiple returns this might look like
def fn(a, b):
  if not a:
result = None
  elif b == 0:
result = 0
  else:
# Calculate result
  return result
To me the first version is cleaner and clearer. The exceptional cases are handled unambiguously at 
the start of the fn, the rest of the code just handles the normal case.

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


[Tutor] sorting and editing large data files

2004-12-16 Thread Scott Melnyk
Hello!

I recently suffered a loss of programming files (and I had been
putting off my backups...)

The project I am working on involved the use of programs which I had
been assisted with by some of the group.

I am rewritten the programs however my results are not what I expected.

I would appreciate anyone who could follow through the steps and
programs below and tell me if it seems correct, which it does to me. 
It could be the error is based on a flaw that I had made before.

I will give very simplified explanations of the data to help.

Starting a file with genetic data about 95 mb

A sample of the file format is:

>ENSE1384652.1|ENSG0166157.5|ENST0359693.1
assembly=NCBI35|chr=21|strand=reverse|bases 10012801 to 10012624|exons
plus upstream and downstream regions for exon
GCGGCCGTTCAAGGCAGCCGTCTCCGAGCGGCCCAAGGGAGGGCACAACAGCTGCTACCTGAACAGTTTCTGACCCAACAGTTACCCAGCGCCGGACTCGCTGCGGGCGGCTCTAGGGACGGCGCCTACACTTAGCTCCGCGCCCGAGGTGAGCCCAG

It is hard to tell due to email formating however  from the ">" to the
words "regions for exon" is one line, all the GCATs are on one line.

ENSExxx is an exon id tag  followed by a ENSGxgene id tag then
a ENSTxxx transcript id tag followed by information about the
location of exon.

the letters GCTA are the actually exon sequence.

1 gene can have different versions, these are called transcripts and
each transcript contains a number of exons

In order to visually understand the data better I made a script to
organize it into sections with Gene ID, then Trancript ID followed by
the different  Exon IDs like so:



NEW GENE
ENSG0166157.5 ENST0359693.1 ENSE1384652.1
ENSE1365174.1 ENSE1372282.1 ENSE1369818.1
ENSE1371166.1 ENSE1369770.1 ENSE1122873.3
ENSE1156126.1 ENSE1156118.1 ENSE1378322.1
ENSE1156105.1 ENSE1156099.1 ENSE1156092.1
ENSE1156083.1 ENSE1156075.1 ENSE1156069.1
ENSE1156063.1 ENSE1156057.1 ENSE1100323.1
ENSE1156046.1 ENSE1126180.1 ENSE1100365.1
ENSE1156031.1 ENSE1231719.5

NEW TRANSCRIPT
ENSG0166157.5 ENST0298232.4 ENSE1384652.1
ENSE1365174.1 ENSE1372282.1 ENSE1369818.1
ENSE1371166.1 ENSE1369770.1 ENSE1156126.1
ENSE1156118.1 ENSE1378322.1 ENSE1156105.1
ENSE1156099.1 ENSE1156092.1 ENSE1156083.1
ENSE1156075.1 ENSE1156069.1 ENSE1156063.1
ENSE1156057.1 ENSE1100323.1 ENSE1156046.1
ENSE1126180.1 ENSE1100365.1 ENSE1156031.1
ENSE1231719.5

NEW TRANSCRIPT
ENSG0166157.5 ENST0342420.2 ENSE1384652.1
ENSE1365174.1 ENSE1372282.1 ENSE1369818.1
ENSE1371166.1 ENSE1369770.1 ENSE1156118.1
ENSE1378322.1 ENSE1156105.1 ENSE1156099.1
ENSE1156092.1 ENSE1156083.1 ENSE1156075.1
ENSE1156069.1 ENSE1156063.1 ENSE1156057.1
ENSE1100323.1 ENSE1156046.1 ENSE1126180.1
ENSE1100365.1 ENSE1156031.1 ENSE1231719.5

NEW TRANSCRIPT
ENSG0166157.5 ENST0339704.2 ENSE1384652.1
ENSE1364671.1 ENSE1387876.1 ENSE1384389.1
ENSE1156111.1 ENSE1156105.1 ENSE1156099.1
ENSE1156092.1 ENSE1156083.1 ENSE1156075.1
ENSE1156069.1 ENSE1156063.1 ENSE1156057.1
ENSE1100323.1 ENSE1156046.1 ENSE1126180.1
ENSE1100365.1 ENSE1156031.1 ENSE1231719.5
end of gene group

NEW GENE
ENSG0187172.4 ENST0335369.2 ENSE1428001.1
ENSE1331994.3 ENSE1398768.1 ENSE1429773.1
etc.

This was accomplished with the following program I called OrganizeData.py

#3
#execute with python datafile outputfile

import re,sys,string

#regular expression to pull out gene, transcript and exon ids

info=re.compile('^>(ENSE\d+\.\d).+(ENSG\d+\.\d).+(ENST\d+\.\d)')
#   sample from the file 
#>>ENSE1373825.1|ENSG0187908.1|ENST0344467.1


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

#initialize some variables  GENEID is the name of the gene, TRANSID is
name of the transcript etc
sOldGene=""
sGENEID=""
sOldTrans=""
sTRANSID=""
sEXONID=""

for line in file:
if info.match(line):
Matched= info.match(line)

sEXONID=Matched.group(1)
sGENEID=Matched.group(2)
sTRANSID=Matched.group(3)

if sOldGene==sGENEID:   #if current line is the same gene as 
last line
if sOldTrans == sTRANSID:  #if current line is same 
transcript as last line
print >> WriteFile, sEXONID,#add new exon 
to the current transcript line

else:
print >> WriteFile,"\n\n\tNEW TRANSCRIPT\n", 
sGENEID, sTRANSID,
sEXONID,   #new transcript of same gene 

Re: [Tutor] AttributeError: instance has no __call__ method

2004-12-16 Thread Juan Shen
Marc Gartler wrote:
Hi everybody,
Prior to this chunk of code 'glass' has been chosen from a list of 
colors via user input, and I now want to have that choice connect to 
one of several possible classes:

def glass_type(glasstype):
if glasstype == 'Red':
myglass = RedGlassCost()
elif glasstype == 'Blue':
myglass = BlueGlassCost()
elif glasstype == 'Yellow':
myglass = YellowGlassCost()
return myglass
glasschoice = glass_type(glass)
myglass = glasschoice()
I've tried various approaches and keep getting different errors.  But 
this one seems closest to my goal, as I know it is at least passing 
'glass' into the function:

AttributeError: RedGlassCost instance has no __call__ method
What is this trying to tell me?  Or is that irrelevant as I would be 
better off trying some other approach altogether?

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

I have guessed your meaning by that code.  Try the following:
glasstype={\
'Red':RedGlassCost,\
'Blue':BlueGlassCost,\
'Yellow':YellowGlassCost}
# RedGlassCost ... are types.FunctionType
myglass=glasstype[glass]()
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] am I missing another simpler structure?

2004-12-16 Thread Kent Johnson
It's probably worth pointing out that these two functions are not entirely 
equivalent:
def t1():
  if condition:
return True
  return False
def t2():
  return condition
because 'condition' does not have to evaluate to a boolean value, it can be any 
Python value.
Here is a simple example where 'condition' is just the value of a parameter:
>>> def t1(a):
...   if a:
... return True
...   return False
...
>>> def t2(a):
...   return a
...
If a is actually True or False these two functions return the same value:
>>> a=True; print t1(a), t2(a)
True True
>>> a=False; print t1(a), t2(a)
False False
For other values of a they return different values; t1 will always return True or False, while t2, 
obviously, returns a:
>>> a=1; print t1(a), t2(a)
True 1
>>> a=None; print t1(a), t2(a)
False None
>>> a=[]; print t1(a), t2(a)
False []

Usually this is fine; code such as
if t1(a): print 'a is True'
will work the same with t1 or t2. OTOH, if you explicitly test the return value (which is *not* 
recommended practice), you will get different results:
>>> if t1(100) == True: print '100 is True'
...
100 is True

>>> if t2(100) == True: print '100 is True'
...
(nothing prints)
I recommend *not* testing explicitly for True, and I recommend the t2() form. Then Python will do 
what you expect. But I thought it was worth pointing out the difference.

Kent
Gregor Lingl wrote:

Brian van den Broek schrieb:
If my original bit of code, the structure was like:
output_value = False
if condition:
output_value = True
return output_value
Mine would be like yours if transformed to:
if condition:
return True
return False
Hi Brian!
Do you mean, that condition is something which is
True od False?
And if condition is True you want to return True?
And if condition is False you want to return False?
So why not simlpy:
return condition
?
Regards,
Gregor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] am I missing another simpler structure?

2004-12-16 Thread Loptr Chaote
On Wed, 15 Dec 2004 19:58:56 -0500, Brian van den Broek
<[EMAIL PROTECTED]> wrote:
> As I mentioned, I feel as though I have a mental block getting in the
> way of coming up with code in the smoother fashion of the second snippet
> above. As I have been making a lot of use of a construct (pattern?)
> similar to my code above, wherein I try something, and return True if it
> works, False if it doesn't, I've begun to wonder if I am overlooking a
> improvement similar to that in DogWalker's suggestion. As an example of
> the sort of thing I have been doing:

This reply might seem embarassingly short compared to the other
answers you got. But I would like to point out two things that could
be worth thinking about and that could help you "tune in" to a more
direct line of thinking.

1) Every operation has a return value [unless purposefully left out]
This includes, but is not limited to; mathematical operations (of
course), variable assignment, compare blocks, etc..
2) If you collect the value first, and then use the collect-variable
for checking things, chances are you might be able to exclude the
collect-variable completely. This also applies to "state
flag"-variables (like in_range in your own solution suggestion).

Might not be much worth, but it's my two cents. ;)

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


Re: [Tutor] am I missing another simpler structure?

2004-12-16 Thread Juan Shen
Kent, Bingle!
Python's 'and' and 'or' operation only returns the right value (any kind 
of value: integer, string, list, excuting a function and so on) not 
Boolean value (True or False).  It's a real fuzzy tip for beginners. 
See Chapter 4.6 of Dive into Python for futher reading
   Juan Shen

Kent Johnson wrote:
It's probably worth pointing out that these two functions are not 
entirely equivalent:
def t1():
  if condition:
return True
  return False

def t2():
  return condition
because 'condition' does not have to evaluate to a boolean value, it 
can be any Python value.

Here is a simple example where 'condition' is just the value of a 
parameter:
>>> def t1(a):
...   if a:
... return True
...   return False
...
>>> def t2(a):
...   return a
...

If a is actually True or False these two functions return the same value:
>>> a=True; print t1(a), t2(a)
True True
>>> a=False; print t1(a), t2(a)
False False
For other values of a they return different values; t1 will always 
return True or False, while t2, obviously, returns a:
>>> a=1; print t1(a), t2(a)
True 1
>>> a=None; print t1(a), t2(a)
False None
>>> a=[]; print t1(a), t2(a)
False []

Usually this is fine; code such as
if t1(a): print 'a is True'
will work the same with t1 or t2. OTOH, if you explicitly test the 
return value (which is *not* recommended practice), you will get 
different results:
>>> if t1(100) == True: print '100 is True'
...
100 is True

>>> if t2(100) == True: print '100 is True'
...
(nothing prints)
I recommend *not* testing explicitly for True, and I recommend the 
t2() form. Then Python will do what you expect. But I thought it was 
worth pointing out the difference.

Kent
Gregor Lingl wrote:

Brian van den Broek schrieb:
If my original bit of code, the structure was like:
output_value = False
if condition:
output_value = True
return output_value
Mine would be like yours if transformed to:
if condition:
return True
return False
Hi Brian!
Do you mean, that condition is something which is
True od False?
And if condition is True you want to return True?
And if condition is False you want to return False?
So why not simlpy:
return condition
?
Regards,
Gregor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


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


Re: [Tutor] am I missing another simpler structure?

2004-12-16 Thread Gregor Lingl

Kent Johnson schrieb:
It's probably worth pointing out that these two functions are not 
entirely equivalent:
def t1():
  if condition:
return True
  return False

def t2():
  return condition
...
 >>> if t1(100) == True: print '100 is True'
...
100 is True
 >>> if t2(100) == True: print '100 is True'
...
(nothing prints)
If you really need this property, you may use
type-conversion with bool:
>>> t2(100)
100
>>> bool(t2(100))
True
>>>
So in this case
def t3(a):
return bool(a)
should work correctly
Regards,
Gregor
Remark for Brian: Please note, that Kent wrote about a feature
specific to Python, whereas the main part of this thread
contains considerations concerning boolean expressions in general.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] am I missing another simpler structure?

2004-12-16 Thread Blake Winton
Juan Shen wrote:
def is_leap_year(year):
is_leap = True
try:
datetime.date(year, 2, 29)
except ValueError:
is_leap = False
return is_leap
I would write
def is_leap_year(year):
try:
datetime.date(year, 2, 29)
return True
except ValueError:
return False
Yeah, I support Kent.  Brian's code is obviously C style,  define a 
variable and give it an origin value, then use it, modify its value and 
so on.  If you choose Python, you should adapt to it that variable 
needn't to be defined specificly before being used!
I far prefer the Brian's version, because it lets me set a single 
breakpoint while I'm debugging, and I can look at the return value 
before returning it, instead of having to set n breakpoints (or, usually 
n-1 because I've overlooked the one that's actually being executed) and 
looking at what's being returned on each line.  (Yes, I do the same 
thing in C and C++, but I originally started using it in Java, and after 
a few debugging sessions it makes a lot of sense.)  Only having one 
return point from a function is a long-standing convention that is 
supposed to make programs easier to read/debug/optimize/prove correct.

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


Re: [Tutor] am I missing another simpler structure?

2004-12-16 Thread Gonçalo Rodrigues
Loptr Chaote wrote:
On Wed, 15 Dec 2004 19:58:56 -0500, Brian van den Broek
1) Every operation has a return value [unless purposefully left out]
This includes, but is not limited to; mathematical operations (of
course), variable assignment, compare blocks, etc..
A small correction: every function has a return value. If left out (that 
is, no return statement) then it returns None. E.g.

>>> def noret():
... 2 + 2
... 
>>> print noret()
None
>>>
Statements have no return value, e.g.
>>> a = 1
>>> print a = 1
Traceback (  File "", line 1
print a = 1
^
SyntaxError: invalid syntax
Like the above shows, assigment has no return value -- it's a statement. 
This is precisely the distinction between a *statement* (like 
assignment) and an expression (like a function call). Python has this 
distinction like most languages. A language like Scheme doesn't since 
everything is an expression.

With my best regards,
G. Rodrigues
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] am I missing another simpler structure?

2004-12-16 Thread Brian van den Broek
Blake Winton said unto the world upon 2004-12-16 09:20:
Juan Shen wrote:


Yeah, I support Kent.  Brian's code is obviously C style,  define a 
variable and give it an origin value, then use it, modify its value 
and so on.  If you choose Python, you should adapt to it that variable 
needn't to be defined specificly before being used!
Hi Juan and Blake,
Juan: I wish my problem were coming from competency in C infecting my 
approach to Python! Apart from some happily ill-remembered BASIC, I am 
unlingual as a programmer.

I far prefer the Brian's version, because it lets me set a single 
breakpoint while I'm debugging, and I can look at the return value 
before returning it, instead of having to set n breakpoints (or, usually 
n-1 because I've overlooked the one that's actually being executed) and 
looking at what's being returned on each line.  (Yes, I do the same 
thing in C and C++, but I originally started using it in Java, and after 
a few debugging sessions it makes a lot of sense.)  Only having one 
return point from a function is a long-standing convention that is 
supposed to make programs easier to read/debug/optimize/prove correct.
Blake,
the point about making debugging easier is what I was (trying to be) 
pointing towards. Thanks for making it clearly, unencumbered by the sort 
of basic efficiency error (of overlooking that I can just return the 
boolean result of some condition) that I keep putting into my examples ;-)

Best to all,
Brian vdB
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python structure advice ?

2004-12-16 Thread Dave S
Dave S wrote:
Im sorry to bang on about Python structure, but I do struggle with it, 
having in the past got into very bad habits with loads of BASIC where 
everything was global, and Forth, and hand coded 8031, 8051, 6502  
I cant get my head round how you guys handle a modern structured 
language :-)
(PS before anyone flames me - I think Python is great and am 
determined to learn it ;-) )

I have ended up with my application in several separate directories.
I have 'live_datad' a demon that extracts web data, at preset times 
and archives it, this will be run as a thread, and possible using a 
queue ... (still digesting info from query about IPCing)

I have a 'data_core' which accepts data from either live_datad real 
time or the archive for testing, it builds up a large multi 
dimensional array with various pointers into the array.

I have a statistical module 'data_stats' which analises the array 
pulling various stats.

And finally I have an analytical module 'data_predict' which using the 
output from 'data_stats' & data directly from the 'data_core' outputs 
statistical predictions of future data.

I have written my 'live_datad', I have written my 'data_core' & have a 
fairly good idea how to write the rest.

My problem is that pretty much all the modules need to fix where they 
are when they exit and pick up from that point later on, ie more data 
comes from live_datad, it is passed to 'data_core' which updates the 
matrix, then 'data_stats' then 'data_predict'  all called form the 
main script.  This OK till the main script realizes that more data is 
avalible from 'live_datad', passes it to 'data_core' which must 
remember where it was and move on, and the same for the rest of the 
modules. To make the problem more acute the modules may not be called 
in exactly the same order depending on what I am trying to achieve.

The 'remembering where is was' seems a continuous stumbling block for 
me. I have though of coding each module as a class but this seems like 
a cheat. I could declare copious globals, this seems messy, I could 
define each module as a thread & get them talking via queues, given 
this serious thought but heeded warning in previous posts. I have 
thought about returning an list of saved 'pointers' which would be 
re-submitted when the function is called. I don't know which way to turn.

With my code now running to a few hundred lines (Don't laugh this is 
BIG for me :-D ) I am going to have to make a structure decision and 
any suggestions would be appreciated.

How would you approach it ?
Dave

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

Having written this email, it has put my thoughts in order, though it 
seems a bit cheaty, wouldn't defining all modules that have to remember 
their internal state as classes be the best bet ?

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


Re: [Tutor] Python structure advice ?

2004-12-16 Thread Kent Johnson
Dave S wrote:
Dave S wrote:
The 'remembering where is was' seems a continuous stumbling block for 
me. I have though of coding each module as a class but this seems like 
a cheat. I could declare copious globals, this seems messy, I could 
define each module as a thread & get them talking via queues, given 
this serious thought but heeded warning in previous posts. I have 
thought about returning an list of saved 'pointers' which would be 
re-submitted when the function is called. I don't know which way to turn.

Having written this email, it has put my thoughts in order, though it 
seems a bit cheaty, wouldn't defining all modules that have to remember 
their internal state as classes be the best bet ?

Dave
Why do you say this is 'cheaty'? A class is basically a collection of data (state) and functions to 
operate on that state.

You might be interested in this essay:
http://www.pycs.net/users/323/stories/15.html
It might well make sense to organize your program as a collection of cooperating classes, or maybe a 
collection of classes with a top-level function that stitches them all together.

You might also want to learn about iterator classes and generator functions, they are a technique 
for returning a bit of data at a time while maintaining state. You might be able to structure your 
input stage as an iterator or generator.
http://docs.python.org/tut/node11.html#SECTION001190
http://docs.python.org/lib/typeiter.html

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


Re: [Tutor] sorting and editing large data files

2004-12-16 Thread Danny Yoo


On Thu, 16 Dec 2004, Scott Melnyk wrote:

> I recently suffered a loss of programming files (and I had been
> putting off my backups...)

Hi Scott,


[Side note that's not really related to Python: if you don't use a version
control system to manage your software yet, please learn to use one.
There's a very good one called Subversion:

http://subversion.tigris.org/

A good version control system is invaluable to programmers, since many
programs are not really written once, but are rather maintained and
revised for a long time.]


Rich Krauter already caught the bug that was occurring: the intersection()
method of sets produces a brand new set, rather than do a mutation on the
old set.



Here are some more comments on the programs you've shown us:


> A sample of the file format is:
>
> >ENSE1384652.1|ENSG0166157.5|ENST0359693.1
> assembly=NCBI35|chr=21|strand=reverse|bases 10012801 to 10012624|exons
> plus upstream and downstream regions for exon
> GCGGCCGTTCAAGGCAGCCGTCTCCGAGCGGCCCAAGGGAGGGCACAACAGCTGCTACCTGAACAGTTTCTGACCCAACAGTTACCCAGCGCCGGACTCGCTGCGGGCGGCTCTAGGGACGGCGCCTACACTTAGCTCCGCGCCCGAGGTGAGCCCAG


Ah, ok, so this is a FASTA file.

(For others on the list, see:

http://ngfnblast.gbf.de/docs/fasta.html

for a description of the BLAST format.)



> ENSExxx is an exon id tag  followed by a ENSGxgene id tag then
> a ENSTxxx transcript id tag followed by information about the
> location of exon.

[text cut]

Ok, so it sounds like your program will mostly pay attention to each
description line in the FASTA file.




> In order to visually understand the data better I made a script to
> organize it into sections with Gene ID, then Trancript ID followed by
> the different Exon IDs like so:

[lots of text cut]

There's one big assumption in the code to OrganizeData.py that may need to
be explicitely stated: the code appears to assume that the sequences are
already sorted and grouped in order, since the code maintains a variable
named 'sOldGene' and maintains some state on the last FASTA sequence that
has been seen.  Is your data already sorted?



As a long term suggestion: you may find it easier to write the extracted
data out as something that will be easy to work with for the next stages
of your pipeline.  Human readability is important too, of course, so
there's a balance necessary between machine and numan convenience.

If possible, you may want to make every record a single line, rather than
have a record spread across several lines.  Your program does do this in
some part, but it also adds other output, like announcements to signal the
start of new genes.  That can complicates later stages of your analysis.


Eric Raymond has summarized the rules-of-thumb that the Unix utitilies try
to follow:

http://www.faqs.org/docs/artu/ch05s02.html#id2907428

As a concrete counterexample, the 'BLAST' utility that bioinformaticians
use has a default output that's very human readable, but so ad-hoc that
programs that try to use BLAST output often have to resort to fragile,
hand-crafted BLAST parsers.  The situation's a lot better now, since newer
versions of BLAST finally support a structured format.

So I'd strongly recommend dropping the "NEW GENE", "end of gene group",
and "NEW TRANSCRIPT" lines out of your output.  And if you really want to
keep them, you can write a separate program that adds those notes back
into the output of OrganizeData.py for a human reader.

If you drop those decorations out, then the other parts of your pipeline
can be simplified, since you can assume that each line of the input file
is data.  The other stages of your analysis pipeline appear to try to
ignore those lines anyway, so why put them in?  *grin*

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


RE: [Tutor] hello i need help

2004-12-16 Thread Robert, Andrew
I recommend you use vim.

You can get it at http://www.vim.org/download.php


Thank you,
Andrew Robert
Systems Architect
Information Technology - OpenVMS
Massachusetts Financial Services
Phone:  617-954-5882
Pager:   781-764-7321
E-mail:  [EMAIL PROTECTED]
Linux User Number: #201204

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Jason Child
Sent: Thursday, December 16, 2004 2:43 PM
To: [EMAIL PROTECTED]
Subject: Re: [Tutor] hello i need help

alex biggerstaff wrote:

> is it possible 2 write a script for wordpad or something, i only 
> started so i dont know much
> i do know a little about if ($1 == hi)  && (£2 == m8)
> but im not sure how 2 make this apply to other programs. i can only 
> write scripts on a thing called mIRC.
> ne help would b great
> thnxs
>
> * ALL-NEW Yahoo! Messenger * 
>  * - 
> all new features - even more fun!* * *
>
>
>
>___
>Tutor maillist  -  [EMAIL PROTECTED]
>http://mail.python.org/mailman/listinfo/tutor
>  
>

I do not belive that Notepad supports scripting. Take a look at: 
http://www.python.org/moin/PythonEditors

in particular you may want to look at JeXt, Syn or Zues.


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


"MFS Relay Service" made the following
 annotations on 12/16/2004 03:01:08 PM
--
This email communication and any attachments may contain proprietary, 
confidential, or privileged information.  If you are not the intended 
recipient, you are hereby notified that you have received this email in error 
and that any review, disclosure, dissemination, distribution or copying of it 
or its contents is prohibited.  The sender does not waive confidentiality or 
any privilege by mistransmission.  If you have received this email in error, 
please notify the sender immediately, delete this email, and destroy all copies 
and any attachments.
==

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


Re: [Tutor] am I missing another simpler structure?

2004-12-16 Thread Jeff Shannon
Blake Winton wrote:
def is_leap_year(year):
is_leap = True
try:
datetime.date(year, 2, 29)
except ValueError:
is_leap = False
return is_leap

I would write
def is_leap_year(year):
try:
datetime.date(year, 2, 29)
return True
except ValueError:
return False
If one insists on single-return style, then I'd prefer to do it this way:
def is_leap_year(year):
try:
datetime.date(year, 2, 29)
is_leap = True
except ValueError:
is_leap = False
return is_leap
You still have to type 'is_leap' multiple times, but at least it's a 
little bit more clear which conditions will result in it being True or 
False.

[...]  Only having one
return point from a function is a long-standing convention that is 
supposed to make programs easier to read/debug/optimize/prove correct.
Indeed, it is supposed (by some) to be better, and is thought by 
others to sometimes make things more complicated.  In the above code, 
a single return point gives you one place to set breakpoints during 
debugging, etc, but it also means that you introduce a new variable 
that you must type at least three times, introducing multiple 
opportunities for typos.  As with most programming choices, 
single-return has both a benefit and a cost.  In some situations the 
cost can be very large relative to the benefit; in others the cost is 
very small.  I find it best not to be too dogmatic about most such 
stylistic questions -- I try to stay aware of the costs of a 
particular approach, but I'll happily use it when the net effect is to 
make the code simpler and more understandable.

Similar to the example that Kent later points out, in my work life I 
often find myself writing functions (to use as the body of a loop) 
where a number of unrelated tests must be done before proceeding with 
processing.  (This is actually in an old, crufty dialect of Basic, but 
the same principle applies)  I have a few choices in this case.  I can 
 simply write the loop body in-line and use gotos to skip segments if 
the tests fail (ew).  I can write the loop body in-line and use 
multiply nested if/else statements, but it can get difficult to track 
what nesting level I'm at.  I can use nested functions, each with just 
one test in it, something like this:

def func1(data):
result = None
if test1:
result = func2(data)
return result
def func2(data):
result = None
if test2:
result = func3(data)
return result
def func3(data):
[...]
This gets pretty darn ugly to trace through, especially when I've got 
six or eight different tests.  Or, I can simply use multiple returns:

def func(data)
if not test1:
return
if not test2:
return
if not test3:
return
# do stuff with data...
It really does make it much simpler to track through the code, since I 
don't care, later in the function, about the specific results of each 
test, only about whether I should continue afterwards or not.  In this 
case, I'm weighing the cost of multiple returns against the cost of 
multiple nestings or of using flag variables, and I find multiple 
returns to be the lowest-cost option.

Jeff Shannon
Technician/Programmer
Credit International
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] hello i need help

2004-12-16 Thread alex biggerstaff
is it possible 2 write a script for wordpad or something, i only started so i dont know much
i do know a little about if ($1 == hi)  && (£2 == m8)
but im not sure how 2 make this apply to other programs. i can only write scripts on a thing called mIRC.
ne help would b great
thnxs
		 ALL-NEW 
Yahoo! Messenger 
- all new features - even more fun! 
 ___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] removedirs ?

2004-12-16 Thread Jason Child
is this what you want to do?
import os
from os.path import join
# Delete everything reachable from the directory named in 'top'.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
for root, dirs, files in os.walk(top, topdown=False):
   for name in files:
   os.remove(join(root, name))
   for name in dirs:
os.rmdir(join(root, name))
I cant take credit for the code, as I found it when I was trying to hack 
together a recirsive file remover script. It was in the help files for 
the os module, under walk(). Go figure; when you try to do things the 
"hard way" python keeps it simple!

Peace
Jason
Ertl, John wrote:
Jason,
I could...That is the exact feature I am trying to replicate, but I would
just like to do it in Python if I can (in a simple way).  I am writing this
code in Python to avoid some funny scripting that I would need to do. To go
back to combing shell and Python again would be a bit deflating...but the
straight forward path might be the best.
Thanks,
John Ertl 

-Original Message-
From: Jason Child [mailto:[EMAIL PROTECTED]
Sent: Thursday, December 16, 2004 12:36
Cc: [EMAIL PROTECTED]
Subject: Re: [Tutor] removedirs ?
Ertl, John wrote:
 

I am trying to remove a directory that has other directories and files in
it.  I thought removedirs was supposed to do a recursive remove of files
   

and
 

directories.
When I try it I get

   

os.removedirs("DAF")
 

 

Traceback (most recent call last):
File "", line 1, in -toplevel-
  os.removedirs("DAF")
File "/home/ertlj/ertljVersion/lib/python2.3/os.py", line 167, in
removedirs
  rmdir(name)
OSError: [Errno 17] File exists: 'DAF'
Thanks,
John Ertl
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor

   

it seems to me that if its on a *nix box you could use the shell command
rm -rf 
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
 

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


Re: [Tutor] least squares

2004-12-16 Thread Danny Yoo


On Thu, 16 Dec 2004, mdcooper wrote:

> I am trying to run a least squares program (written by Konrad Hinsen)

Hi Matthew,

You're assuming that we know who Konrad Hinsen is.  *grin* Ok, when you're
referring to the least-squared code, are you referring to a module in
Scientific Python?

Please point us to the code that you're running, and we can give better
help.  Most of us are just learning Python, so many of us may not really
be familiar with the tools that you are using.  Make it easier for us to
help you!  *grin*


> but I would like to only have positive values returned. Can anyone help
> is altering the code to do this?

This shouldn't be too bad: it sounds like a filtering of the return value
is what you're looking for.  Show us a concrete example of what you're
getting so far, and what you want to get.



Good luck to you.

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


Re: [Tutor] removedirs ?

2004-12-16 Thread Jason Child
Ertl, John wrote:
I am trying to remove a directory that has other directories and files in
it.  I thought removedirs was supposed to do a recursive remove of files and
directories.
When I try it I get 

 

os.removedirs("DAF")
   

Traceback (most recent call last):
 File "", line 1, in -toplevel-
   os.removedirs("DAF")
 File "/home/ertlj/ertljVersion/lib/python2.3/os.py", line 167, in
removedirs
   rmdir(name)
OSError: [Errno 17] File exists: 'DAF'
Thanks,
John Ertl
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
 

it seems to me that if its on a *nix box you could use the shell command 
rm -rf 
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


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

2004-12-16 Thread Jacob S.
Ha! That's what I was looking for! The builtin apply function! The only way
I could send the *args to the function was through a list, and function
calls see a list as one argument. The apply argument doesn't! Thanks Bob.

Jacob Schmidt

> At 12:39 PM 12/8/2004, Bob Gailer wrote:
> >At 11:27 AM 12/8/2004, Dick Moores wrote:
> >>My thanks to both Max and Kent. So Python tries, and fails, to see 2()
as
> >>a function!
> >>
> >>I also got some help from 
> >
> >Note that SOME languages use () for call. There are other call
constructs,
> >such as:
> >
> >DO function WITH parameters (FoxPro, similar in COBOL)
> >
> >function parameter   or   parameter1 function parameter2 (APL)
>
> I should add the Python builtin function apply: apply(function,
parameters...)
>
> Bob Gailer
> [EMAIL PROTECTED]
> 303 442 2625 home
> 720 938 2625 cell
>
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>
>

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


Re: [Tutor] Address book sort of

2004-12-16 Thread Jacob S.
Hey, I made some changes to my address book, with help from Oh darn,
well whoever you are, I haven't forgotten the help you gave me in changing
my if/if/if/if/if/else things into mapping objects Anyway, if anybody
wants a look, here it is.
P.S. I made some changes to the file reading part too. Got rid of some
unnecessary code.


[start]
from os.path import exists as ex

tel = {}
tempname = "Telephone.cfg"
if not ex(tempname):
open(tempname,"w").close()
file = open(tempname,"r")
stuff = file.read()
file.close()
if stuff == '':
a = 1
print "No entries on file."
else:
tel = eval(stuff)
a = 0

print """\
Commands are:
add
get
save
delete
quit
all is a wildcard
"""

def dispatch(command,entity,tel):
tfunct = functs[command]
tfunct(entity,tel)

def add(person,tel):
if tel.has_key(person):
print "That person is already in there. If you wish to edit the
file, please delete the record first."
else:
tel[person] = raw_input("What is their phone number? ")

def get(person,tel):
if a == 1:
print "Sorry, there are no entries available."
else:
if person == 'all':
key = tel.keys()
key.sort()
print
for x in key:
print "%s\n%s\n" % (x,tel[x])
elif tel.has_key(person):
print "\n%s\n%s\n" % (person,tel[person])
else:
print "%s is not in your records." % person

def delete(person,tel):
if not a:
if person == 'all':
tel={}
open('Telephone.cfg', 'w').close()
else:
if tel.has_key(person):
del tel[person]
else:
print "%s is not in your records." % person
else:
print "There is no one to delete."

def save(entitynotneeded,tel):
file=open('Telephone.cfg', 'w')
file.write(str(tel))
file.close()
print 'Saved in Telephone.cfg'

functs = {'add':add,'get':get,'save':save,'delete':delete}

while 1:
ask = raw_input('Tell me what you wish to do. ')
if ask == "quit":
break
ask = ask.split(" ")
command = ask[0]
entity = " ".join(ask[1:])
if entity == '' and command != 'save':
entity = raw_input("Who do you want to %s? " % command)
dispatch(command,entity,tel)

file = open('Telephone.cfg', 'w')
file.write(str(tel))
file.close()
[end]

Jacob Schmidt

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


Re: [Tutor] Complex roots

2004-12-16 Thread Jacob S.
Finding the all the roots of a complex number shouldn't be too difficult. I
tend to do it on paper sometimes. Maybe I can write a script to do it for me
instead.  I stongly caution you though. The methods that I show below are
unstable and should be verified by a math web site as it has been quite a
few months since I last used the equations. In fact, I'll almost bet they're
wrong. If you want me to check them, I'll gladly google for the right
equations if you want.

where i == sqrt(-1)

[pseudo-code]
p = (a+bi)**n
n = polar(p)  ## polar is a function that converts rectangular coordinates
to polar coordinates.
radius = n[0]
angle = n[1]

1st rootradius**n cis (angle/(180*n))  ## Where cis is short for
(cos(angle) + i*sin(angle))
2nd rootradius**n cis (angle/(360*n))
...
qth rootradius**n cis (angle/(180*q*n))
[/pseudo-code]

So saying, I would set a for i in range loop for n times to run these root
finders through. Note unless you call some sort of polar to rectangular
function on the roots, they will still be in polar.

HTH as always,
Jacob Schmidt

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


Re: [Tutor] Address book sort of

2004-12-16 Thread Jacob S.
You know, instead of that long or thing you've set up, you could do this.

if select in [ 'l', 'v', 'V' ]:

> [quote]
> if select == '1' or select == 'v' or select == 'V':
> if file_in_disk in os.listdir('/home/jerimed'): #
change???
> fhandle = open(file_in_disk, 'r')   # read mode
> cPickle.load(fhandle)   # restore saved
data
> fhandle.close()
> show_contacts()
> elif len(data_holder) > 0:
> show_contacts()
> else:
> is_empty()
> [/quote]


I'd swear that your standard disclaimer changes weekly. : )

Happy Holidays,
Jacob

> Standard disclaimer -
>
> There's probably an easier way to do it, and a more elegant way. Which
> someone will post shortly.
>
> Cheers,
>
> Liam Clarke

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


Re: [Tutor] Problem with python2.4.

2004-12-16 Thread Jacob S.
If you mean the "Internet Connection Firewall" thingy that you access from
the network connection options, then Nope, that's not the problem, because
it's disabled.

Thanks for your help,
Jacob

>
> Seeing this comment reminded me of some conversations I've seen in
> comp.lang.python recently.  Apparently newer versions of IDLE create a
> subprocess to run user-code in (so that IDLE runs in a different
> interpreter than the code you type into IDLE), and communicates with
> that subprocess through sockets on the loopback interface (that is,
> the 'network connection' that connects only to itself).  Overly
> aggressive firewall programs may block those socket operations.
>
> I'd check whether XP's built-in firewall is enabled, and if so, check
> whether it might be blocking connections to loopback / localhost /
> 127.0.0.1 (all of these indicate the same thing).
>
> Jeff Shannon
> Technician/Programmer
> Credit International
>
> ___
> Tutor maillist  -  [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/tutor
>

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


Re: [Tutor] Python structure advice ?

2004-12-16 Thread Alan Gauld
> everything was global, how you guys handle a modern structured
> language

Don't worry this is one of the hardest bad habits to break.
You are not alone. The easiest way is to just pass the data
from function to function in the function parameters. Its not
at all unusual for functions to have lots of parameters, "global"
programmers tend to panic when they have more than a couple,
but its not at all bad to have 5 or 6 - more than that gets
unweildy I admit and is usually time to start thinking about
classes and objects.

> I have ended up with my application in several separate directories.

Separate modules is good. Separate directories for anything
other than big programs (say 20 or more files?) is more hassle
than its worth. The files are better kept in a single directory
IMHO. The exception being modules designed for reuse...
It just makes life simpler!

> My problem is that pretty much all the modules need to fix where
they
> are when they exit and pick up from that point later on,

There are two "classic" approaches to this kind of problem:

1) batch oriented - each step of the process produces its own
output file or data structure and this gets picked up by the
next stage. Tis usually involved processing data in chunks
- writing the first dump after every 10th set of input say.
This is a very efficient way of processing large chuinks of
data and avoids any problems of synchronisation since the
output chunks form the self contained input to the next step.
And the input stage can run ahead of the processing or the
processing aghead of the input. This is classic mainframe
strategy, ideal for big volumes. BUT it introduces delays
in the end to end process time, its not instant.

2) Real time serial processing, typically constructs a
processing chain in a single process. Has a separate thread
reading the input data and kicks off a separate processing
thread (or process) for each bit of data received. Each
thread then processes the data to completion and writes
the output. A third process or thread then assembles the
outputs into a single report.

This produces results quickly but can overload the computer
if data starts to arrive so fast that the threads start to
back up on each other. Also error handling is harder since
with the batch job data errors can be fixed at the
intermediate files but with this an error anywhere means
that whole data processing chain will be broken with no way
to fix it other than resubmitting the initial data.

> With my code now running to a few hundred lines
> (Don't laugh this is BIG for me :-D )

Its big for me in Python, I've only writtenone program with
more than a thousand lines of Python wheras I've written
many C/C++ programs in ecess of 10,000 lines and worked
on several of more than a million lines. But few if any
Python programs get to those sizes.

HTH,

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

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


Re: [Tutor] dbcp module

2004-12-16 Thread Rene Bourgoin

Yah i came across that site and was trying to learn from that code.
I just cant seem to find a download for a python version.

i came across this site while searching.

http://jakarta.apache.org/






 --- On Wed 12/15, Kent Johnson < [EMAIL PROTECTED] > wrote:
From: Kent Johnson [mailto: [EMAIL PROTECTED]
To: 
 Cc: [EMAIL PROTECTED]
Date: Wed, 15 Dec 2004 20:19:22 -0500
Subject: Re: [Tutor] dbcp module

Googling for 'python dbcp' turns up this recipe, is this what you are looking 
for?http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189KentRene
 Bourgoin wrote:> Anyone know where I can download the dbcp module for 
Python> > > > > > > 
___> No banners. No pop-ups. No 
kidding.> Make My Way your home on the Web - http://www.myway.com> 
___> Tutor maillist  -  
[EMAIL PROTECTED]> http://mail.python.org/mailman/listinfo/tutor> 
___Tutor maillist  -  
[EMAIL PROTECTED]http://mail.python.org/mailman/listinfo/tutor

___
No banners. No pop-ups. No kidding.
Make My Way your home on the Web - http://www.myway.com
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] am I missing another simpler structure?

2004-12-16 Thread Alan Gauld
> I far prefer the Brian's version, because it lets me set a single 
> breakpoint while I'm debugging, and I can look at the return value 
> before returning it, 

In most debiggers(including Pythons) you can still do that 
with a boolean condition provided the condition does not 
itself contain a function call. Simply evaluate the condition 
in the debugger - eg using the print command.

But if the condition has a function in it this is not wise 
since the function may have side-effects so every time you 
call it may result in a different result.

So my advise is to ony use the 

return 

trick on side-effect free simple expressions, otherwise 
go with the more verbose options.

Same applies to the C ?: operator or the python shortcuts 
using 'and' and 'or'...

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


Re: [Tutor] Python structure advice ?

2004-12-16 Thread Alan Gauld
> Having written this email, it has put my thoughts in order, though
it
> seems a bit cheaty, wouldn't defining all modules that have to
remember
> their internal state as classes be the best bet ?

Its one solution certainly, creeate objects and the objects carry
their state with them. But the problem can be tackled as per my
earlier post without delving into the world of objects.

Alan G.

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


Re: [Tutor] Complex roots

2004-12-16 Thread Dick Moores
Thanks. Tim Peters helped me out with his answer of 12/9. 


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


Re: [Tutor] removedirs ?

2004-12-16 Thread Juan Shen
Of course, shutil.rmtree() is a fast and direct method, but still a 
little warning, it could be dangerous.  No warning and ensure will be 
raised while removing a tree of files.
   Juan Shen
Kent Johnson wrote:

You misunderstand what removedirs does. It removes an empty directory; 
then, if the removed directory's parent is now empty, it removes that, 
too, and so on until it finds a directory with something in it or gets 
up to the root.

Try shutil.rmtree() or this recipe:
http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/Recursive_directory_deletes_and_special_files.html 

Kent
Ertl, John wrote:
I am trying to remove a directory that has other directories and 
files in
it.  I thought removedirs was supposed to do a recursive remove of 
files and
directories.

When I try it I get
os.removedirs("DAF")


Traceback (most recent call last):
  File "", line 1, in -toplevel-
os.removedirs("DAF")
  File "/home/ertlj/ertljVersion/lib/python2.3/os.py", line 167, in
removedirs
rmdir(name)
OSError: [Errno 17] File exists: 'DAF'
Thanks,
John Ertl
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


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


Re: [Tutor] removedirs ?

2004-12-16 Thread Juan Shen
This is an iterative method, although much slower than shutil.rmtree(),  
which can be useful sometimes, while some stdout/in is added:

#!/usr/bin/python
#Filename: myrmtree.py
import os,sys,shutil
def rmtree(top):
   uncleandir=[]
   for (root,dirs,files) in os.walk(top,topdown=False):
   for name in dirs+files:
   item=os.path.join(root,name)
   if item in uncleandir:
   uncleandir.append(root)
   continue
   print 'Delete %s : (Yes or No or All or Cancel)' %(item,),
   v=raw_input()
   if v=='Y' or v=='y':
   (os.path.isfile(item) and os.remove or os.rmdir)(item)
   elif v=='N' or v=='n':
   uncleandir.append(root)
   continue
   elif v=='A' or v=='a':
   shutil.rmtree(top)
   return 1
   elif v=='C' or v=='c':
   return 2
   else:
   print 'Take your input as No.'
   continue
   return 0
>>>from myrmtree import tree
>>>top='/home/juan/test' #Your dir need to be removed here
>>>rmtree(top)
Just try it and give suggestions and comments please, Hehe
   Juan Shen
Jason Child wrote:
is this what you want to do?
import os
from os.path import join
# Delete everything reachable from the directory named in 'top'.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
for root, dirs, files in os.walk(top, topdown=False):
   for name in files:
   os.remove(join(root, name))
   for name in dirs:
os.rmdir(join(root, name))
I cant take credit for the code, as I found it when I was trying to 
hack together a recirsive file remover script. It was in the help 
files for the os module, under walk(). Go figure; when you try to do 
things the "hard way" python keeps it simple!

Peace
Jason
Ertl, John wrote:
Jason,
I could...That is the exact feature I am trying to replicate, but I 
would
just like to do it in Python if I can (in a simple way).  I am 
writing this
code in Python to avoid some funny scripting that I would need to do. 
To go
back to combing shell and Python again would be a bit deflating...but 
the
straight forward path might be the best.

Thanks,
John Ertl
-Original Message-
From: Jason Child [mailto:[EMAIL PROTECTED]
Sent: Thursday, December 16, 2004 12:36
Cc: [EMAIL PROTECTED]
Subject: Re: [Tutor] removedirs ?
Ertl, John wrote:
 

I am trying to remove a directory that has other directories and 
files in
it.  I thought removedirs was supposed to do a recursive remove of 
files
  
and
 

directories.
When I try it I get

  

os.removedirs("DAF")



Traceback (most recent call last):
File "", line 1, in -toplevel-
  os.removedirs("DAF")
File "/home/ertlj/ertljVersion/lib/python2.3/os.py", line 167, in
removedirs
  rmdir(name)
OSError: [Errno 17] File exists: 'DAF'
Thanks,
John Ertl
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor

  
it seems to me that if its on a *nix box you could use the shell command
rm -rf 
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
 

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


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


[Tutor] Re: A simpler mousetrap

2004-12-16 Thread Wolfram Kraus
Liam Clarke wrote:
Hi all, 

I'm writing some code, and I want to take a given path + filename, and
change the file extension to *.bak.
In doing so, (entirely internal this function), I am assuming -
That the file will always have an extension
Thathe extension will vary
But, it will follow the general DOS format of name.ext
So, I came up with this -
a="./tc/arc/gab.pct"
x=a.replace(a[a.rfind('.'):len(a)],'.bak')
x="./tc/arc/gab.bak"
So, it works, but it feels a bit, well, hacky to me. Not nearly hacky
as using an regex though ; )
I thought about 

a="./tc/arc/gab.pct"
aList=a.split('.')
aList[-1]='bak'
a=".".join(aList)
but I'm wondering if there's a simpler way, as there usually seems to
be, and it's always so obvious once I'm shown it, like 6 down - Six on
vehicle live in the manse (VI + car). Obvious once you know.
Regards,
Liam Clarke
Hey Liam!
The os.path module is your friend, especially split and splitext: 
http://docs.python.org/lib/module-os.path.html

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


Re: [Tutor] am I missing another simpler structure?

2004-12-16 Thread Gregor Lingl

Brian van den Broek schrieb:
If my original bit of code, the structure was like:
output_value = False
if condition:
output_value = True
return output_value
Mine would be like yours if transformed to:
if condition:
return True
return False
Hi Brian!
Do you mean, that condition is something which is
True od False?
And if condition is True you want to return True?
And if condition is False you want to return False?
So why not simlpy:
return condition
?
Regards,
Gregor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] am I missing another simpler structure?

2004-12-16 Thread Juan Shen
Kent Johnson wrote:
Brian van den Broek wrote:
I've begun to wonder if I am overlooking a improvement similar to 
that in DogWalker's suggestion. As an example of the sort of thing I 
have been doing:

import datetime
def is_leap_year(year):
'''-> boolean
Returns True or False as year is, or is not, a leap year.
'''
is_leap = True
try:
datetime.date(year, 2, 29)
except ValueError:
is_leap = False
return is_leap

I would write
def is_leap_year(year):
try:
datetime.date(year, 2, 29)
return True
except ValueError:
return False
Kent
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor

Yeah, I support Kent.  Brian's code is obviously C style,  define a 
variable and give it an origin value, then use it, modify its value and 
so on.  If you choose Python, you should adapt to it that variable 
needn't to be defined specificly before being used!
   Juan Shen

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


Re: [Tutor] AttributeError: instance has no __call__ method

2004-12-16 Thread Juan Shen
Juan Shen wrote:
Marc Gartler wrote:
Hi everybody,
Prior to this chunk of code 'glass' has been chosen from a list of 
colors via user input, and I now want to have that choice connect to 
one of several possible classes:

def glass_type(glasstype):
if glasstype == 'Red':
myglass = RedGlassCost()
elif glasstype == 'Blue':
myglass = BlueGlassCost()
elif glasstype == 'Yellow':
myglass = YellowGlassCost()
return myglass
glasschoice = glass_type(glass)
myglass = glasschoice()
I've tried various approaches and keep getting different errors.  But 
this one seems closest to my goal, as I know it is at least passing 
'glass' into the function:

AttributeError: RedGlassCost instance has no __call__ method
What is this trying to tell me?  Or is that irrelevant as I would be 
better off trying some other approach altogether?

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

I have guessed your meaning by that code.  Try the following:
glasstype={\
'Red':RedGlassCost,\
'Blue':BlueGlassCost,\
'Yellow':YellowGlassCost}
# RedGlassCost ... are types.FunctionType
myglass=glasstype[glass]()
BTW, if RedGlassCost is types.ClassType, my code also sounds.
   Juan Shen
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sorting and editing large data files

2004-12-16 Thread Rich Krauter
Scott Melnyk wrote:
Hello!
I recently suffered a loss of programming files (and I had been
putting off my backups...)
[snip]
#regular expression to pull out gene, transcript and exon ids
info=re.compile('^(ENSG\d+\.\d).+(ENST\d+\.\d).+(ENSE\d+\.\d)+')
#above is match gene, transcript, then one or more exons
#TFILE = open(sys.argv[1], 'r' )#read the various 
transcripts from
WFILE=open(sys.argv[1], 'w')# file to write 2 careful 
with 'w'
will overwrite old info in file
W2FILE=open(sys.argv[2], 'w')   #this file will have the 
names of
redundant exons
import sets
def getintersections(fname='Z:\datasets\h35GroupedDec15b.txt'):
exonSets = {}
f = open(fname)
for line in f:
if line.startswith('ENS'):
parts = line.split()
gene = parts[0]
transcript = parts[1]
exons = parts[2:]
exonSets.setdefault(gene,
 sets.Set(exons)).intersection(sets.Set(exons))
^^
	return exonSets

Hi Scott,
There may be other problems, but here's one thing I noticed:
exonSets.setdefault(gene,
sets.Set(exons)).intersection(sets.Set(exons))
should be
exonSets.setdefault(gene,
   sets.Set(exons)).intersection_update(sets.Set(exons))
Hope that helps.
Rich

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


Re: [Tutor] am I missing another simpler structure?

2004-12-16 Thread Brian van den Broek
Gregor Lingl said unto the world upon 2004-12-16 04:14:
Brian van den Broek schrieb:
If my original bit of code, the structure was like:
output_value = False
if condition:
output_value = True
return output_value
Mine would be like yours if transformed to:
if condition:
return True
return False
Hi Brian!
Do you mean, that condition is something which is
True od False?
And if condition is True you want to return True?
And if condition is False you want to return False?
So why not simlpy:
return condition
?
Regards,
Gregor
Hi Gregor,
why not indeed?
As I see what I've been blithering on about, there are two issues in the 
air: 1) single exit versus multiple exit functions, and 2) my seemingly 
entrenched tendency to overlook that I can do just what you point out.

The above was reply to Liam's:
I find multiple returns to be rather useful - 

def isOdd(x):
if not x % 2: return False
return True
*If* one isn't doing what you suggest (through a dogged determination to 
fail to learn from the past, I imagine ;-), I still prefer the single 
exit point way I give above. But, as Guille pointed out to Liam, neither 
of these ways are needed when your way is available, too. So, I like my 
way of being foolish and inefficient better, given a commitment to 
foolish inefficiency ;-)

(FWIW, I did manage to start this thread with code where the condition 
was of the form "this try block doesn't raise an exception" so, unless 
using one of Tim's helpful suggestions, no function with a single line 
that returns would do.)

On the plus side, publicly getting the same style of correction multiple 
times in a few days greatly increases the chance that some of this might 
actually making it into my own practise!

So, thanks to all who've responded.
Best,
Brian vdB
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] hello i need help

2004-12-16 Thread Jason Child
alex biggerstaff wrote:
is it possible 2 write a script for wordpad or something, i only 
started so i dont know much
i do know a little about if ($1 == hi)  && (£2 == m8)
but im not sure how 2 make this apply to other programs. i can only 
write scripts on a thing called mIRC.
ne help would b great
thnxs

* ALL-NEW Yahoo! Messenger * 
 * - 
all new features - even more fun!* * *


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

I do not belive that Notepad supports scripting. Take a look at: 
http://www.python.org/moin/PythonEditors

in particular you may want to look at JeXt, Syn or Zues.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] removedirs ?

2004-12-16 Thread Ertl, John
I am trying to remove a directory that has other directories and files in
it.  I thought removedirs was supposed to do a recursive remove of files and
directories.

When I try it I get 

>>> os.removedirs("DAF")

Traceback (most recent call last):
  File "", line 1, in -toplevel-
os.removedirs("DAF")
  File "/home/ertlj/ertljVersion/lib/python2.3/os.py", line 167, in
removedirs
rmdir(name)
OSError: [Errno 17] File exists: 'DAF'

Thanks,

John Ertl


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


RE: [Tutor] removedirs ?

2004-12-16 Thread Ertl, John
Jason,

I could...That is the exact feature I am trying to replicate, but I would
just like to do it in Python if I can (in a simple way).  I am writing this
code in Python to avoid some funny scripting that I would need to do. To go
back to combing shell and Python again would be a bit deflating...but the
straight forward path might be the best.

Thanks,

John Ertl 


-Original Message-
From: Jason Child [mailto:[EMAIL PROTECTED]
Sent: Thursday, December 16, 2004 12:36
Cc: [EMAIL PROTECTED]
Subject: Re: [Tutor] removedirs ?

Ertl, John wrote:

>I am trying to remove a directory that has other directories and files in
>it.  I thought removedirs was supposed to do a recursive remove of files
and
>directories.
>
>When I try it I get
>
> 
>
os.removedirs("DAF")
   

>
>Traceback (most recent call last):
>  File "", line 1, in -toplevel-
>os.removedirs("DAF")
>  File "/home/ertlj/ertljVersion/lib/python2.3/os.py", line 167, in
>removedirs
>rmdir(name)
>OSError: [Errno 17] File exists: 'DAF'
>
>Thanks,
>
>John Ertl
>
>
>___
>Tutor maillist  -  [EMAIL PROTECTED]
>http://mail.python.org/mailman/listinfo/tutor
>
> 
>
it seems to me that if its on a *nix box you could use the shell command
rm -rf 
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] removedirs ?

2004-12-16 Thread Kent Johnson
You misunderstand what removedirs does. It removes an empty directory; then, if the removed 
directory's parent is now empty, it removes that, too, and so on until it finds a directory with 
something in it or gets up to the root.

Try shutil.rmtree() or this recipe:
http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/Recursive_directory_deletes_and_special_files.html
Kent
Ertl, John wrote:
I am trying to remove a directory that has other directories and files in
it.  I thought removedirs was supposed to do a recursive remove of files and
directories.
When I try it I get 


os.removedirs("DAF")

Traceback (most recent call last):
  File "", line 1, in -toplevel-
os.removedirs("DAF")
  File "/home/ertlj/ertljVersion/lib/python2.3/os.py", line 167, in
removedirs
rmdir(name)
OSError: [Errno 17] File exists: 'DAF'
Thanks,
John Ertl
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] least squares

2004-12-16 Thread mdcooper
Hi there,

I am trying to run a least squares program (written by Konrad Hinsen) but I 
would like to only have positive values returned. Can anyone help is altering 
the code to do this?

Thanks,

matthew


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


Re: [Tutor] least squares

2004-12-16 Thread Jason Child
well, not sure if there is a module with the function you are looking 
for, but...

#sloppy as hell method:
#...
if str(my_returned_value).find("-") != -1:
   return my_returned_value #or whatever you want to do with it
#...
#slightly less sloppy as hell method:
if my_returned_value < 0:
   return my_returned_value

mdcooper wrote:
Hi there,
I am trying to run a least squares program (written by Konrad Hinsen) but I 
would like to only have positive values returned. Can anyone help is altering 
the code to do this?

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

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


RE: [Tutor] least squares

2004-12-16 Thread mdcooper
Hi Danny,

Thanks for the reply - I was purposely vague just to see what people would ask 
for.

The code uses LinearAlgebra.py from Numeric and LeastSquares.py from 
Scientific.

I am trying to get a corrolation between a large number of variables and for 
many similar equations :
   (Ca1 * xa^2) + (Ca2 * ya^2) + (Ca3 * za^2) + ... = ta
   (Cb1 * xb^2) + (Cb2 * yb^2) + (Cb3 * zb^2) + ... = tb

which is solved to get:
   (C1 * x^2) + (C2 * y^2) + (C3 * z^2) + ... = t

where the submitted values of x,y, and z should give the correct t

and I am using the code to get C1, C2, C3,  These constants are not 
allowed to be negative and the submitted equations are such that there is no 
reason for the values to be negative, and although a good fit may allow them 
to be negative, another good fit will be found if they are all positive.

I need them to be all positive but also all to exist, so filtering out the 
negative numbers is not sufficient.

Thanks,

Matt

>= Original Message From Danny Yoo <[EMAIL PROTECTED]> =
>On Thu, 16 Dec 2004, mdcooper wrote:
>
>> I am trying to run a least squares program (written by Konrad Hinsen)
>
>Hi Matthew,
>
>You're assuming that we know who Konrad Hinsen is.  *grin* Ok, when you're
>referring to the least-squared code, are you referring to a module in
>Scientific Python?
>
>Please point us to the code that you're running, and we can give better
>help.  Most of us are just learning Python, so many of us may not really
>be familiar with the tools that you are using.  Make it easier for us to
>help you!  *grin*
>
>
>> but I would like to only have positive values returned. Can anyone help
>> is altering the code to do this?
>
>This shouldn't be too bad: it sounds like a filtering of the return value
>is what you're looking for.  Show us a concrete example of what you're
>getting so far, and what you want to get.
>
>
>
>Good luck to you.


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


RE: [Tutor] least squares

2004-12-16 Thread mdcooper
Hi Danny,

Thanks for the reply - I was purposely vague just to see what people would ask 
for.

The code uses LinearAlgebra.py from Numeric and LeastSquares.py from 
Scientific.

I am trying to get a corrolation between a large number of variables and for 
many similar equations :
   (Ca1 * xa^2) + (Ca2 * ya^2) + (Ca3 * za^2) + ... = ta
   (Cb1 * xb^2) + (Cb2 * yb^2) + (Cb3 * zb^2) + ... = tb

which is solved to get:
   (C1 * x^2) + (C2 * y^2) + (C3 * z^2) + ... = t

where the submitted values of x,y, and z should give the correct t

and I am using the code to get C1, C2, C3,  These constants are not 
allowed to be negative and the submitted equations are such that there is no 
reason for the values to be negative, and although a good fit may allow them 
to be negative, another good fit will be found if they are all positive.

I need them to be all positive but also all to exist, so filtering out the 
negative numbers is not sufficient.

Thanks,

Matt

>= Original Message From Danny Yoo <[EMAIL PROTECTED]> =
>On Thu, 16 Dec 2004, mdcooper wrote:
>
>> I am trying to run a least squares program (written by Konrad Hinsen)
>
>Hi Matthew,
>
>You're assuming that we know who Konrad Hinsen is.  *grin* Ok, when you're
>referring to the least-squared code, are you referring to a module in
>Scientific Python?
>
>Please point us to the code that you're running, and we can give better
>help.  Most of us are just learning Python, so many of us may not really
>be familiar with the tools that you are using.  Make it easier for us to
>help you!  *grin*
>
>
>> but I would like to only have positive values returned. Can anyone help
>> is altering the code to do this?
>
>This shouldn't be too bad: it sounds like a filtering of the return value
>is what you're looking for.  Show us a concrete example of what you're
>getting so far, and what you want to get.
>
>
>
>Good luck to you.


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


Re: [Tutor] hello i need help

2004-12-16 Thread Alan Gauld

> is it possible 2 write a script for wordpad or something,

Yes it is, using the COM interface. But frankly the interface
to Wordpad is pretty basic. Word has much more powerful COM
facilities. But...

> i only started so i dont know much

You probably need to do a bit of reading on the fundamentals
first because using COM is not a trivial programming task.
Its not rocket science but its not trivial either.

> i do know a little about if ($1 == hi)  && (#2 == m8)

Thats more than I do, I don;t recognoise that line at all.
Is that really supposed to be a pound sign in the second parens?

Try one of the beginner tutorials on the Python web site,
one of which is mine :-) And it has a few elementary bits
of COM code too...

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

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


Re: [Tutor] am I missing another simpler structure?

2004-12-16 Thread Alan Gauld
> What makes me lean toward mine still? I'd encountered a general 
> injunction to avoid multiple exit point somewhere on the wild web 

This goes back to Djikstra's original paper on structured 
programming (and he was really thinking about assembler!)
Multiple returns are a source of bugs, especially in maintenance, 
but with the advent and popularity of C they have become a 
standard ttechnique and with reasonable care they are OK in 
practice. The trick is to minimise them or to keep them 
collected together in similar patterns. For example in 
C it is common to see production code that looks like:

void someFunc(int p1,p2, char* p3)
{
   // validate the inputs
   if (p1 <0) return BAD_INPUT;

   if (p2 > 1000) return BUFFER_ERROR;

   if (!p3 or strlen(p3) < MIN_STR) return BAD_STRING;

   // real function code here
   return result;
}

So there are lots of return statements but they are used 
for a very clear purpose and are co-located at the top of 
the function. In more modern languages we avoid this kind 
of checking with try/except constructs so we would write
something like:

def someFunct(p1,p2,p3):
  try:
 # do some clever stuff
  except anError: raise AttributeError
  except anOther: raise ValueError

etc.

This leaves the if/else construct as the other likely place 
to have multiple returns, and there it is usually a matter 
of personal preference. A try/finally construct will remove 
the problem of not freeing resources that used to happen 
in C etc.

So in summary, while multiple retirns we a real problem 
in the 70's and 80's they have been brought under control
in modern languages such that they are not frowned upon
too much nowadays.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor