dynamic names
Robert Brewer
fumanchu at amor.org
Sun Mar 7 17:08:39 EST 2004
More information about the Python-list mailing list
Sun Mar 7 17:08:39 EST 2004
- Previous message (by thread): How do I define a __del__ method for an object?
- Next message (by thread): dynamic names
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Val Bykoski wrote:
> I'm currently in a familiar to many business of filing my tax
> return. Being a big fan of Python and to make the process
> less painful,
> i started by writing my favored schedules A,B,C, and the most favored
> form 1040 in Python. Everything was a real fun until i got to the
> very famous motif "add lined Lx to Ly".
> This is my naive (master)piece:
>
> def sumL(L1,L2):
> # sum up a range of Ls
> tot=0.
> for L in range(L1,L2+1):
> #nL=exec("L%s" % L)
> tot=tot + ("L%s" % L)
> return tot
Val,
If I were writing the same thing, I would probably stop using a separate
name for L1, L2, etcetera; instead I would put them in a list:
def sum_lines(lines, lowerbound, upperbound):
tot=0.
for line in lines[lowerbound:upperbound + 1]:
tot += line
return tot
>>> lines = [3.0, 4.0, 5.0, 6.0, 7.0]
>>> sum_lines(lines, 2, 4)
18.0
Of course, once you've put them in a list, you can just use the builtin
sum() function:
>>> sum(lines[2:5])
18.0
...which saves the extra function definition and call overhead, and
makes your code more readable and more manageable. Hope that helps!
Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
- Previous message (by thread): How do I define a __del__ method for an object?
- Next message (by thread): dynamic names
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list