Why does way_1() obtain the correct list but way_2() gets an empty list?

2009-02-12 Thread WP
Hello group! This is probably a silly newbie mistake but consider the 
following program:


import libsbml

def getSBMLModel(biomodel_path):
reader = libsbml.SBMLReader()

sbml_doc = reader.readSBML(biomodel_path)
sbml_model = None

if sbml_doc.getNumErrors() > 0:
print 'I couldn\'t read the file %s!' % biomodel_path
return None
else:
sbml_model = sbml_doc.getModel()

return sbml_doc.getModel() # None if file couldn't be opened


def way_1(biomodel_path):
reader = libsbml.SBMLReader()
sbml_doc = reader.readSBML(biomodel_path)
sbml_model = sbml_doc.getModel()

if sbml_model == None:
return

l = sbml_model.getListOfSpecies()
print 'In way_1(): Got list %s with the length %i' % (l, len(l))


def way_2(biomodel_path):
sbml_model = getSBMLModel(biomodel_path)

if sbml_model == None:
return

l = sbml_model.getListOfSpecies()
print 'In way_2(): Got list %s with the length %i' % (l, len(l))


file = '../BIOMD03.xml'
# Changing the order of these two calls doesn't help, only way_1() works.
way_1(file)
way_2(file)

When run, the output is:
In way_1(): Got list type 'ListOfSpecies *' at 0x291c8bc> > with the length 3
In way_2(): Got list type 'ListOfSpecies *' at 0x27fb57c> > with the length 0


I don't get it way the species list obtained in way_2() is empty? For 
the input file I'm using I should be getting 3 species for the test file 
I'm using.
I'm sorry that this program uses a third-party library which is probably 
unknown to many, but since I make a lot of newbie mistakes I thought 
that it's very likely that this is a issue in how I use python, not a 
library issue. To compensate somewhat I tried to show my entire test 
program and its output and make that test program as clear as possible.


So if anyone knows why I get this behavior I would like to hear it and I 
will have learned something today too! :)


- WP
--
http://mail.python.org/mailman/listinfo/python-list


Can I replace this for loop with a join?

2009-04-13 Thread WP

Hello, I have dictionary {1:"astring", 2:"anotherstring", etc}

I now want to print:
"Press 1 for astring"
"Press 2 for anotherstring" etc

I could do it like this:
dict = {1:'astring', 2:'anotherstring'}
for key in dict.keys():
print 'Press %i for %s' % (key, dict[key])

Press 1 for astring
Press 2 for anotherstring

but can I use a join instead?

Thanks for any replies!

- WP
--
http://mail.python.org/mailman/listinfo/python-list


My very first python program, need help

2008-08-10 Thread WP
Hello, below is my very first python program. I have some questions 
regarding it and would like comments in general. I won't be able to get 
my hands on a good python book until tomorrow at the earliest. The 
program takes a string and sums all numbers inside it. I'm testing with 
the following string: "123xx,22! p1" which should yield a sum of 123 + 
22 + 1 = 146. My solution to this exercise was to write a function that 
takes a string and splits it into a list of numbers and then I will sum 
up the numbers in the list. In fact, I wrote two versions of this 
function: One uses a for loop to replace all characters that is not a 
digit and not a space with a space. That should leave me with the 
numbers intact and with only spaces separating these numbers. Then I 
call split to get a list of numbers (here I discovered I must not use a 
sep equal to ' ' or the returned list would contain empty strings as 
well). This is calculate_sum_1() and look at the comment in the code to 
see what worries me there. The second one uses regular expressions and 
the problem I have with that is that I get a list of containing not just 
the numbers but empty strings as well. I'm working around that in my 
loop that sums the numbers but it would be better to not have these 
empty string in the list in the first place. Here's the code:


import re

def calculate_sum_1(str):
for c in str:
if c.isdigit() == False and c != ' ':
# That we assign to the variable we're looping over worries 
me...

str = str.replace(c, ' ')

mylist = str.split()

print "(for loop version) mylist after replace() and split() = ", 
mylist


sum = 0

for item in mylist:
   sum += long(item)

return sum

def calculate_sum_2(str):
#print "In replace_nondigits_2(), str = ", str
p = re.compile('[^0-9]')

mylist = p.split(str)

print "(regex version) mylist after calling split(): ", mylist

sum = 0

for item in mylist:
if item.isdigit():
sum += long(item)

return sum

str = "123xx,22! p1" # Sum = 123 + 22 + 1 = 146

print "str = ", str

print "calculate_sum_1(str): %d" % calculate_sum_1(str)
print "calculate_sum_2(str): %d" % calculate_sum_2(str)

The output when run is:
str =  123xx,22! p1
(for loop version) mylist after replace() and split() =  ['123', '22', '1']
calculate_sum_1(str): 146
(regex version) mylist after calling split():  ['123', '', '', '22', '', 
'', '1']

calculate_sum_2(str): 146


Hope I made some sense and thanks for reading!

- Eric (WP)
--
http://mail.python.org/mailman/listinfo/python-list


Re: My very first python program, need help

2008-08-10 Thread WP

Wojtek Walczak wrote:
[snip]
Thanks for all your help. I've incorporated your suggestions and moved 
on to my next program. See new thread. :)


- Eric (WP)
--
http://mail.python.org/mailman/listinfo/python-list


Second python program: classes, sorting

2008-08-10 Thread WP
Hello, here are some new things I've problems with. I've made a program 
that opens and reads a text file. Each line in the file contains a name 
and a score. I'm assuming the file has the correct format. Each 
name-score pair is used to instantiate a class Score I've written. This 
works fine, but here's my problem: After reading the file I have list of 
Score objects. Now I want to sort them in descending order. But no 
matter how I write my __cmp__ the order remains unchanged. I've 
determined that __cmp__ is called but it's only called twice for three 
list elements, isn't that odd?


Complete program:
class Score:
def __init__(self, name_, score_):
self.name = name_
self.score = score_

def __str__(self):
return "Name = %s, score = %d" % (self.name, self.score)

def __cmp__(self, other):
print "in __cmp__"
return self.score >= other.score

name  = ""
score = 0
# End class Score

filename = "../foo.txt";

try:
infile = open(filename, "r")
except IOError, (errno, strerror):
print "IOError caught when attempting to open file %s. errno = %d, 
strerror = %s" % (filename, errno, strerror)

exit(1)

lines = infile.readlines()

infile.close()

lines = [l.strip() for l in lines] # Strip away trailing newlines.

scores = []

for a_line in lines:
splitstuff = a_line.split()

scores.append(Score(splitstuff[0], int(splitstuff[1])))

scores.sort()

for a_score in scores:
print a_score

Test file contents:
Michael 11
Hanna 1337
Lena 99

Output:
in __cmp__
in __cmp__
Name = Michael, score = 11
Name = Hanna, score = 1337
Name = Lena, score = 99

What am I doing wrong here?

- Eric (WP)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Second python program: classes, sorting

2008-08-10 Thread WP

WP wrote:
Solved the problem, see below...

Hello, here are some new things I've problems with. I've made a program 
that opens and reads a text file. Each line in the file contains a name 
and a score. I'm assuming the file has the correct format. Each 
name-score pair is used to instantiate a class Score I've written. This 
works fine, but here's my problem: After reading the file I have list of 
Score objects. Now I want to sort them in descending order. But no 
matter how I write my __cmp__ the order remains unchanged. I've 
determined that __cmp__ is called but it's only called twice for three 
list elements, isn't that odd?


Complete program:
class Score:
def __init__(self, name_, score_):
self.name = name_
self.score = score_

def __str__(self):
return "Name = %s, score = %d" % (self.name, self.score)

def __cmp__(self, other):
print "in __cmp__"
return self.score >= other.score

name  = ""
score = 0
# End class Score

filename = "../foo.txt";

try:
infile = open(filename, "r")
except IOError, (errno, strerror):
print "IOError caught when attempting to open file %s. errno = %d, 
strerror = %s" % (filename, errno, strerror)

exit(1)

lines = infile.readlines()

infile.close()

lines = [l.strip() for l in lines] # Strip away trailing newlines.

scores = []

for a_line in lines:
splitstuff = a_line.split()

scores.append(Score(splitstuff[0], int(splitstuff[1])))

scores.sort()

for a_score in scores:
print a_score

Test file contents:
Michael 11
Hanna 1337
Lena 99

Output:
in __cmp__
in __cmp__
Name = Michael, score = 11
Name = Hanna, score = 1337
Name = Lena, score = 99

What am I doing wrong here?

- Eric (WP)


I solved it, I rewrote __cmp__ to:
def __cmp__(self, other):
   if self.score == other.score:
  return cmp(self.name, other.name)
   else:
  return cmp(other.score, self.score)

This sorts so that score goes from highest to lowest. If two person have 
the same score, I sort on names in alphabetical order. The following 
text file:

Michael 11
Hanna 1337
Lena 99
Anna 99
yields (just as I want):
Name = Hanna, score = 1337
Name = Anna, score = 99
Name = Lena, score = 99
Name = Michael, score = 11

- Eric (WP)
--
http://mail.python.org/mailman/listinfo/python-list