AN ENROLMENT PROJECTION PROBLEM
Steven Taschuk
staschuk at telusplanet.net
Mon Jun 30 08:25:47 EDT 2003
Quoth Ajith Prasad:
> I would appreciate advice on how best to formulate the following
> problem in Python. [...]
If you really want to bring out the linear algebra guns, I'm sure
Numeric has everything you need. But for a problem this simple,
I'd just write
def enrollment(year, intake, survivalrate):
return sum([intake[year-i]*rate
for i, rate in enumerate(survivalrate)])
That's for Python 2.3. In 2.2 you could write
def enrollment(year, intake, survivalrate):
sum = 0
for i in range(len(survivalrate)):
sum = sum + intake[year-i]*survivalrate[i]
return sum
In either case, using it might look something like this:
# survivalrate[n] is proportion of students who survive n years.
survivalrate = [1, 0.5, 0.25, 0.1]
# intake[n] is the number of students intook in year n.
actualintake = {
1993: 980, 1994: 1019, 1995: 1038, 1996: 1046, 1997: 1043,
1998: 970, 1999: 954, 2000: 980, 2001: 952, 2002: 1047,
}
plannedintake = {2003: 1000, 2004: 1000, 2005: 1100, 2006: 1200}
intake = actualintake.copy()
intake.update(plannedintake)
print enrollment(2004, intake, survivalrate)
Note that the intake vectors are dicts, not lists; I do this so I
can avoid index-twiddling. I find the code to be easier to read
and write this way.
--
Steven Taschuk staschuk at telusplanet.net
Every public frenzy produces legislation purporting to address it.
(Kinsley's Law)
More information about the Python-list
mailing list