Checking for a full house
Tony Meyer
t-meyer at ihug.co.nz
Wed May 25 22:00:40 EDT 2005
> def removeAll(element, num2Rem, list):
> l = list[:]
> for num in range(0, num2Rem):
> l.remove(element)
> return l
>
> def isfullHouse(roll):
> for die in range(1,7):
> if roll.count(die)==3:
> l = removeAll(die, 3, roll)
> if l[0]==l[1]:
> return 1
> return 0
>
> My questions is this: is there a better way to do this? A way that's
> more natural to python, or just more efficient perhaps?
This is an alternative that doesn't muck about making a second list:
def isfullHouse(roll):
has_pair = False
has_triple = False
for die in xrange(1,7):
if has_pair and has_triple:
return True
count = roll.count(die)
if count > 3:
return False # easy out; can't have four/five and full house
if count == 2:
has_pair = True
elif count == 3:
has_triple = True
return False
If you want it in one line (and have Python 2.4):
def isfullHouse(roll):
return len(set(roll)) != 2
If you create a set from the list, it will remove duplicates. If there are
3,4, or 5 different numbers, then you don't have a triplet. (I assume that
[1,1,1,1,1] isn't a full house, or this answer is wrong, since that will
have the length be 1).
(These are both untested).
=Tony.Meyer
More information about the Python-list
mailing list