RE: [Tutor] Newbie Q's
by other posts by this author
Jun 11 2002 1:09PM messages near this date
RE: [Tutor] Re: Newbie OOP Question.
(diff between function, modu le and class)
|
Re: [Tutor] Newbie Q's
> 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
_______________________________________________
Tutor maillist - Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor
Thread:
Jeff Shannon
|