[Tutor] Help regarding lists, dictionaries and tuples (bob gailer)

Alan Gauld alan.gauld at btinternet.com
Wed Nov 24 10:08:34 CET 2010


"Robert Sjöblom" <robert.sjoblom at gmail.com> wrote

>> Why would you want to sum them? You start with 30 points in the 
>> pool,
>> then allocate them to the attributes. The sum will still be 30.
>
>Because the user should be able to spend 30 points, or remove points
> from an attribute and get them back in the pool. Like so:
>
> attributes { "Strength" : 0, "Health" : 0, "Wisdom" : 0, "Dexterity" 
> : 0)
> points = 30 - sum(attributes.values())
>
> Or is there a better way to achieve the same result?

If you write a couple of functions to add/remove points then they can
ensure that the total is correct without the need to sum the values.


attributes { "Strength" : 0, "Health" : 0, "Wisdom" : 0, "Dexterity" : 
0)
points = 30 - sum(attributes.values())

def addPoints(attribute, number):
    attributes[attribute] += number
    points -= number
    return points

def removePoints(attribute, number):
     return addPoints(attribute, -number)

Now you can add and remove the points and the function will
ensure there are only ever 30 points in total use. You would
really need checks to ensure the attribute values and points
never went negative of course... but you need that anyway.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list