[Tutor] Re: you may regret that comment Magnus!!
Magnus Lycka
magnus@thinkware.se
Thu Jan 30 22:21:01 2003
At 18:49 2003-01-30 -0800, Mic Forster wrote:
>--- Magnus Lycka <magnus@thinkware.se> wrote:
> >I have some trouble distinguishing between 1 (one)
> >and l (ell) in the picture. Could you clarify that?
>
>Thanks for your help, Magnus. They are all ones in the
>algorithm; there are no ells.
Ok. Then I imagine it's something like below.
>I thought the algorithm
>was rather elaborate and could be simplified.
I still don't have a clue what it does... :)
But the main loop is only 12 lines of code.
from random import random as rnd
# This only works in newer Python versions...
class growList(list):
'''A list that does as in Perl: Grows when
we assign to new indices. I.e. x[1] = 5 will
work if x was previously empty.'''
def __setitem__(self, i, val):
while i >= len(self):
self.append(None)
list.__setitem__(self, i, val)
def __getitem__(self, i):
'Return 0 for unused slots'
if i < len(self):
return list.__getitem__(self, i)
else:
return 0
abund = growList()
abund[1] = 1
cumul = growList()
jM = 10
theta = 5
def nsp():
'''Number of species must be the same as the size of the
abundence list (I guess). Note that first position is
unused to match the 1-based algorithm syntax.'''
return len(abund) - 1
for j in range(2, jM + 1):
x = rnd()
if x < (theta / float(theta + j - 1)):
abund.append(1)
else:
cumul[1] = abund[1] / float(j-1)
for i in range(2, nsp()+1):
cumul[i] = cumul[i-1] + abund[i] / float(j-1)
i = 1
while x >= cumul[i]:
i += 1
abund[i] += 1
print "Abund", abund[1:]
print "Cumulative", cumul[1:]
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se