EDIT: some crude testing suggests that my code works just as it should. Sometimes it's better to think things over twice before posting for help. Ah, well ...
Sometimes I'm feeling very stupid. Like ... just about now. Someone with a clearer mind should be able to help me out with this one.
I'm reworking the parts of my code that picks a random element from a set (of monsters, or items, or something else). First, the possible choices are put in a python dictionary, where the key is the name/identifier of the element, and the value is the relative probability of that element showing up. Something like this, in other words: {'sword':1, 'croquet club':2, 'knife and fork':4} In this example, croquet clubs should be twice as probable as swords, and cutlery four times as probable. Here's what I'm uncertain about:
def draw_lot(pd): # pd is the dictionary of stuff
full_prob=reduce(lambda x,y : x+y, pd.itervalues()) # adds all values,
# ie. sets full_prob to 7 in the example with the weapons
choice=random.randint(1,full_prob) # a number between 1 and full_prob
while 1:
k=pd.popitem() # pops a random key+value from the pd dictionary
if k[1]>=choice: # k[1] is the value, ie. 1, 2, or 4
return k[0] # returns name of picked item
else:
choice-=k[1]
This works pretty fast, but I'm unsure as to whether it produces the intended effect. Will it actually return clubs twice as often as swords, and cutlery twice as often as clubs? I feel like I've a short circuit here somewhere, but I can't wrap my mind around it. So, any help regarding this would be appreciated.
As always,
Minotauros