Ara Kooser wrote:
> Hello all,
>
> On my continuing quest to grapple with OO programming Kent showed
> me that I could call instances and store them in a list like:
> yeasts =
> [Yeast("Red_1","Red","ade","lys"),Yeast("Yellow_1","Yellow","lys","ade"),
>
> Yeast("Red_2","Red","ade","lys"),Yeast("Yellow_2","Yellow","lys","ade")]
>
> Give certain conditions I want the yeast cell to die. Kent suggested I
> use something this:
> yeasts = [yeast for yeast in yeasts if yeast.isAlive()] to clear out
> dead yeast.
>
> Is the translation for the above line of code into pseudocode?
> yeast for every yeast in the list yeasts if the yeast method returned
> isAlive()
Almost.
yeast for every yeast in the list yeasts if the yeast method isAlive()
returned True
This is called a list comprehension, it is a very handy way to do things
with lists. Some examples here:
http://docs.python.org/tut/node7.html#SECTION007140000000000000000
> def chem_need(self):
> if self.need == "ade":
> if self.need in chemicals:
> print self.name,"is taking ade"
> self.life = self.life+1
> chemicals.remove(self.need)
> print chemicals
> print "Life", self.life
> print
> else:
> print self.name, "found no ade present"
> self.life = self.life-1
>
> elif self.need == "lys":
> if self.need in chemicals:
> print self.name," is taking lys"
> self.life = self.life+1
> chemicals.remove(self.need)
> print chemicals
> print "Life",self.life
> print
> else:
> print self.name, "found no lys present"
> self.life = self.life-1
Note that the above two blocks are almost identical. The only difference
is the print statements. Can you figure out a way to combine them into a
single block? Then you could say
if self.need in ('ade', 'lys'):
# handle both ade and lys
> def isAlive(self):
> if self.life > 0:
> self.alive = True
> else:
> self.alive = False
This could be just
self.alive = (self.life > 0)
but I think what you want here is actually to *return* a flag indicating
whether the yeast is alive:
def isAlive(self):
return (self.life > 0)
>
> #The line below will eventually clean out dead yeast
> #yeast for every yeast in the list yeasts if the yeast method returned isAlive
> yeasts = [yeast for yeast in yeasts if yeast.isAlive()]
This will work correctly if you change isAlive() as above.
Kent
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor