[Tutor] accessing dynamically created py objects
Baker, Michael
Michael.Baker@anchorgaming.com
Wed, 9 Jan 2002 13:22:38 -0800
yes thanks that'll do
here's my code:
def getStop(stops,awards,weightranges,iterations=1):
t1=time()
ran=random
STOPS={}
print "i'm workin..."
for item in range(len(stops)):
STOPS["STOP"+str(item)]=0.0
for a in range(iterations):
r=ran()*weightranges[-1]
for n in weightranges:
if r<=n:
#get slice index - NOT STOP NUMBER!
st=weightranges.index(n)
break
stop=stops[st]
award=awards[st]
STOPS['STOP'+str(stop)]+=1
#sort
print "...ok i'm done"
for d in STOPS.keys():
STOPS[d]=STOPS[d]/iterations*100
print "process took ",time()-t1," seconds"
return [stop,award,STOPS]
>>> stops=[0,1,2,3,4,5,6,7,8,9]
>>> awards=[2500,500,250,100,75,60,50,45,35,25]
>>> weights=[1,3,8,14,22,32,62,132,482,812]
>>> s=getStop(stops,awards,weights,1000000)
i'm workin...
...ok i'm done
28.2400000095 seconds
>>> s
[7, 35, {'STOP2': 0.23540000000000003, 'STOP3': 40.566800000000001, 'STOP0':
0.1245, 'STOP1': 3.7212000000000001, 'STOP6': 0.97499999999999998, 'STOP7':
43.130600000000001, 'STOP4': 0.62319999999999998, 'STOP5':
8.6646000000000001, 'STOP8': 0.74390000000000001, 'STOP9':
1.2148000000000001}]
-----Original Message-----
From: Kirby Urner [mailto:urnerk@qwest.net]
Sent: Wednesday, January 09, 2002 1:22 PM
To: Baker, Michael
Cc: 'tutor@python.org'
Subject: Re: [Tutor] accessing dynamically created py objects
>
>how can i make this work??
>
>thanks in advance
>mb
To me, it makes more sense to create your N0..Nn as keys
to a dictionary, and then use these to map to values.
If you need multiple values, you could map to lists. e.g.
>>> gens = {}
>>> def maker(n):
for i in range(n):
gens["N"+str(i)]=[0,0]
>>> maker(5)
>>> gens
{'N0': [0, 0], 'N1': [0, 0], 'N2': [0, 0], 'N3': [0, 0], 'N4': [0, 0]}
Here each Nn is paired with [0,0] i.e. you could populate either
or both elements.
Now you can go:
>>> gens['N4'][0] += 1 # increment 0th element of N4 list
>>> gens
{'N0': [0, 0], 'N1': [0, 0], 'N2': [0, 0], 'N3': [0, 0],
'N4': [1, 0]}
It's easier to mass-create distinct entities using some
data structure than to synthesize variables at the
outermost (module) level.
Kirby