[Tutor] Newbie Q's
alan.gauld@bt.com
alan.gauld@bt.com
Tue, 11 Jun 2002 14:09:36 +0100
> I have two quick questions for you. First, if I have a
> list made up of integers, is there a simple command to
> let me find the sum of the integers (and assign the
> value to a variable)?
The most direct way is with a loop:
result = 0
for num in numlist:
result += num
Or using Pythons reduce function:
result = reduce(operator.add, numlist)
Which does the same thing.
> The biggest difficulty I'm having is dealing with
> aces, which can be valued at 1 or 11. I thought I had
> everything figured out, until a hand came up that had
> two aces in it :-) I'm sure many people have tried
> making this kind of a program. How did you (or would
> you) deal with this aspect of the program?
Special cases need special code. For blackjack you would
count the Ace as 11 if the total was <= 21 else count them
as 1...
So something like the following untested code:
def AddCards(cardlist):
tot = reduce(operator.add, cardlist)
if tot > 21: #too high
while 11 in cardlist: #do we have high aces?
if tot-10 <= 21: # total too high so use low ace
pos = cardist.index(11)
cardlist[pos] = 1 # change from 11 to 1
tot = reduce(operator.add, cardlist)
return tot
Theres probably a neater way but that might help...
Alan g