473,765 Members | 2,097 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Checking for a full house

Hi, I'm new to python, and I'm not sure if this is the place to post
this kind of question; so feel free to tell me if I should take this
elsewhere.

So, to start me off on python, I decided to put together a little
script to test the probabilities of rolling certain combinations of
dice. Below is my code for checking for a full house (when rolling
with 5 dice). A roll is a list, eg [1, 3, 5, 1, 4] (this example is
not a full house)

def removeAll(eleme nt, num2Rem, list):
l = list[:]
for num in range(0, num2Rem):
l.remove(elemen t)
return l

def isfullHouse(rol l):
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?

ps. A roll of [1, 2, 1, 1, 2] is a full house (three of one kind and
two of another)

Jul 19 '05 #1
10 8747
mwdsmith wrote:
Hi, I'm new to python, and I'm not sure if this is the place to post
this kind of question; so feel free to tell me if I should take this
elsewhere.

So, to start me off on python, I decided to put together a little
script to test the probabilities of rolling certain combinations of
dice. Below is my code for checking for a full house (when rolling
with 5 dice). A roll is a list, eg [1, 3, 5, 1, 4] (this example is
not a full house)

def removeAll(eleme nt, num2Rem, list):
l = list[:]
for num in range(0, num2Rem):
l.remove(elemen t)
return l

def isfullHouse(rol l):
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?

ps. A roll of [1, 2, 1, 1, 2] is a full house (three of one kind and
two of another)


def isFullHouse(rol l):
counts = [roll.count(die) for die in range(1,7)]
counts.sort()
return counts == [0, 0, 0, 0, 2, 3]

--
Robert Kern
rk***@ucsd.edu

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Jul 19 '05 #2
"mwdsmith" <re**********@y ahoo.com> wrote:
Hi, I'm new to python, and I'm not sure if this is the place to post
this kind of question; so feel free to tell me if I should take this
elsewhere.
Well, that depends. Are we doing your homework assignment for you? :-)
So, to start me off on python, I decided to put together a little
script to test the probabilities of rolling certain combinations of
dice. Below is my code for checking for a full house (when rolling
with 5 dice). A roll is a list, eg [1, 3, 5, 1, 4] (this example is
not a full house)

def removeAll(eleme nt, num2Rem, list):
l = list[:]
for num in range(0, num2Rem):
l.remove(elemen t)
return l

def isfullHouse(rol l):
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?


Well, I think I might do two trips through a dictionary. Something like
the following. The arguments to the two dict() constructors are list
comprehensions. I don't normally use them a lot, and I don't normally like
complicated expressions like this, but I tried a few ways, and this just
seems to be the most compact way by far to do the counting. So, even
though I'm not convinced this is the clearest way to write it, you did ask
for the most pythonic way, and I think this might be that :-)

#!/usr/bin/env python

def isFullHouse (roll):
# count how many of each value you have, i.e. how many 1's,
# how many 2's, etc
valueDict = dict ([(x, 0) for x in range(1,7)])
for die in roll:
valueDict[die] += 1

# count how many of each set size you have, i.e. how many
# voids, how many singletons, how many pairs, etc.
setDict = dict ([(x, 0) for x in range(0,6)])
for setSize in valueDict.value s():
setDict[setSize] += 1

# A full house is one pair and one three-of-a-kind
return setDict[2] == 1 and setDict[3] == 1

print isFullHouse ([1, 1, 1, 2, 2]) == True
print isFullHouse ([1, 1, 1, 1, 1]) == False
print isFullHouse ([1, 2, 3, 4, 5]) == False
print isFullHouse ([3, 4, 3, 3, 4]) == True
print isFullHouse ([1, 2, 1, 1, 1]) == False
Jul 19 '05 #3
[mwdsmith]
Below is my code for checking for a full house (when rolling
with 5 dice).


There are many ways to do this. Here's one:

..def isfullHouse(han d):
.. counts = [hand.count(card ) for card in set(hand)]
.. return (3 in counts) and (2 in counts) and len(hand)==5
And here's a one-liner:

..def isfullHouse(han d):
.. return sorted(hand.cou nt(card) for card in set(hand)) == [2,3]
Raymond Hettinger

Jul 19 '05 #4
Your use case for gathering roll statistics probably needs a more
general solution:

hands = {
(1,1,1,1,1): 'nothing',
(1,1,1,2): 'one pair',
(1,2,2): 'two pair',
(1,1,3): 'three of a kind',
(2,3): 'full house',
(1,4): 'four of a kind',
(5): 'flush (five of a kind)'
}

def eval_hand(hand) :
counts = tuple(sorted(ha nd.count(card) for card in set(hand)))
return hands.get(count s, 'misdeal')
Raymond Hettinger

Jul 19 '05 #5
"Raymond Hettinger" <py****@rcn.com > writes:
Your use case for gathering roll statistics probably needs a more
general solution:

hands = {
(1,1,1,1,1): 'nothing',
(1,1,1,2): 'one pair',
(1,2,2): 'two pair',
(1,1,3): 'three of a kind',
(2,3): 'full house',
(1,4): 'four of a kind',
(5): 'flush (five of a kind)'
}

def eval_hand(hand) :
counts = tuple(sorted(ha nd.count(card) for card in set(hand)))
return hands.get(count s, 'misdeal')


1. "Flush" means 5 cards of the same suit (i.e. all hearts), not 5 of
a kind.

2. That code doesn't detect flushes or straights.
Jul 19 '05 #6
[Paul Rubin]
1. "Flush" means 5 cards of the same suit (i.e. all hearts), not 5 of
a kind.
More importantly, the (5) should be (5,). Also the poker terminology
should be expressed in terms of dice rolls (the OP's use case).

2. That code doesn't detect flushes or straights.


It also doesn't cook hamburgers, drink beer, play chess, or anything
else unrelated to the OP's use case.

Jul 19 '05 #7
Paul Rubin wrote:
"Raymond Hettinger" <py****@rcn.com > writes:
Your use case for gathering roll statistics probably needs a more
general solution:

hands = {
(1,1,1,1,1): 'nothing',
(1,1,1,2): 'one pair',
(1,2,2): 'two pair',
(1,1,3): 'three of a kind',
(2,3): 'full house',
(1,4): 'four of a kind',
(5): 'flush (five of a kind)'
}

def eval_hand(hand) :
counts = tuple(sorted(ha nd.count(card) for card in set(hand)))
return hands.get(count s, 'misdeal')

1. "Flush" means 5 cards of the same suit (i.e. all hearts), not 5 of
a kind.

2. That code doesn't detect flushes or straights.


It would be interesting to see how complicated it would get to write
code to detect the correct hands in poker with wildcards included.
I tried that a year or 2 ago when i wanted to write a pokergame in java
but i failed miserably in doing so.

I have a gut feeling that with python this is easier. I might give it
another go. Is there any of such code available somewhere?
The reason i wanted to do so is that there isn't a game that allows a
player to specify it's own games. I wanted to make a simple network
enabled game with simple graphics and scriptable poker games via a wizard.
But as i said, i first wanted to construct my "card" code to deal,
evaluate a hand and compare 2 or more hands, and to find the highest
hand in a number of hands. And all this with wildcards, cards in the
hands varying from 5 to 7 and high low. I toyed with on several
occasions but never could seem to find an easy way to do it.

Benedict
Jul 19 '05 #8
[Benedict]
It would be interesting to see how complicated it would get to write
code to detect the correct hands in poker with wildcards included.
There is an interesting SF project with code written in C:
http://pokersource.sourceforge.net/

In contrast, Python makes short work of these kind of problems. Here
are some primitives to get you started (just add a representation for
suits, flush detection, and controlling logic for ranking hands):

def is_straight(han d, numwildcards=0) :
"""Checks for a five card straight

Inputs: list of non-wildcards plus wildcard count
2,3,4, ... 10, 11 for Jack, 12 for Queen,
13 for King, 14 for Ace
Hand can be any length (i.e. it works for seven card games).

Outputs: highest card in a five card straight
or 0 if not a straight.
Original list is not mutated.
Ace can also be a low card (i.e. A2345).
is_straight([14,2,3,4,5]) 5 is_straight([14,2,3,4,6]) 0 is_straight([10,11,12,13,14]) 14 is_straight([2,3,5], 2) 6 is_straight([], 5) 14 is_straight([2,4,6,8,10], 3) 12 is_straight([2,4,4,5,5], 2) 6
"""

hand = set(hand)
if 14 in hand:
hand.add(1)
for low in (10,9,8,7,6,5,4 ,3,2,1):
needed = set(range(low, low+5))
if len(needed & hand) + numwildcards >= 5:
return low+4
return 0

def groups(hand, numwildcards=0) :
"""Checks for pairs, threes-of-kind, fours-of-a-kind,
and fives-of-a-kind

Inputs: list of non-wildcards plus wildcard count
2,3,4, ... 10, 11 for Jack, 12 for Queen,
13 for King, 14 for Ace
Hand can be any length (i.e. it works for seven card games)
Output: tuple with counts for each value (high cards first)
for example (3, 14), (2, 11) full-house Aces over Jacks
for example (2, 9), (2, 7) two-pair Nines and Sevens
Maximum count is limited to five (there is no seven of a kind).
Original list is not mutated.
groups([11,14,11,14,14]) [(3, 14), (2, 11)] groups([7, 9, 10, 9, 7]) [(2, 9), (2, 7)] groups([11,14,11,14], 1) [(3, 14), (2, 11)] groups([9,9,9,9,8], 2) [(5, 9), (2, 8)] groups([], 7)

[(5, 14), (2, 13)]
"""

result = []
counts = [(hand.count(v), v) for v in range(2,15)]
for c, v in sorted(counts, reverse=True):
newcount = min(5, c + numwildcards) # Add wildcards upto five
numwildcards -= newcount - c # Wildcards remaining
if newcount > 1:
result.append(( newcount, v))
return result

import doctest
print doctest.testmod ()

Jul 19 '05 #9
Raymond Hettinger wrote:
[Benedict]
It would be interesting to see how complicated it would get to write
code to detect the correct hands in poker with wildcards included.

There is an interesting SF project with code written in C:
http://pokersource.sourceforge.net/

In contrast, Python makes short work of these kind of problems. Here
are some primitives to get you started (just add a representation for
suits, flush detection, and controlling logic for ranking hands):

def is_straight(han d, numwildcards=0) :
"""Checks for a five card straight

Inputs: list of non-wildcards plus wildcard count
2,3,4, ... 10, 11 for Jack, 12 for Queen,
13 for King, 14 for Ace
Hand can be any length (i.e. it works for seven card games).

Outputs: highest card in a five card straight
or 0 if not a straight.
Original list is not mutated.
Ace can also be a low card (i.e. A2345).
>>> is_straight([14,2,3,4,5]) 5 >>> is_straight([14,2,3,4,6]) 0 >>> is_straight([10,11,12,13,14]) 14 >>> is_straight([2,3,5], 2) 6 >>> is_straight([], 5) 14 >>> is_straight([2,4,6,8,10], 3) 12 >>> is_straight([2,4,4,5,5], 2) 6
"""

hand = set(hand)
if 14 in hand:
hand.add(1)
for low in (10,9,8,7,6,5,4 ,3,2,1):
needed = set(range(low, low+5))
if len(needed & hand) + numwildcards >= 5:
return low+4
return 0

def groups(hand, numwildcards=0) :
"""Checks for pairs, threes-of-kind, fours-of-a-kind,
and fives-of-a-kind

Inputs: list of non-wildcards plus wildcard count
2,3,4, ... 10, 11 for Jack, 12 for Queen,
13 for King, 14 for Ace
Hand can be any length (i.e. it works for seven card games)
Output: tuple with counts for each value (high cards first)
for example (3, 14), (2, 11) full-house Aces over Jacks
for example (2, 9), (2, 7) two-pair Nines and Sevens
Maximum count is limited to five (there is no seven of a kind).
Original list is not mutated.
>>> groups([11,14,11,14,14]) [(3, 14), (2, 11)] >>> groups([7, 9, 10, 9, 7]) [(2, 9), (2, 7)] >>> groups([11,14,11,14], 1) [(3, 14), (2, 11)] >>> groups([9,9,9,9,8], 2) [(5, 9), (2, 8)] >>> groups([], 7)

[(5, 14), (2, 13)]
"""

result = []
counts = [(hand.count(v), v) for v in range(2,15)]
for c, v in sorted(counts, reverse=True):
newcount = min(5, c + numwildcards) # Add wildcards upto five
numwildcards -= newcount - c # Wildcards remaining
if newcount > 1:
result.append(( newcount, v))
return result

import doctest
print doctest.testmod ()


Wow Raymond that's amazing !
Makes we feel stupid, happy and in awe of python at the same time.
I only felt this weird before when i got married :)

I will have a good look at your code. Excellent :)

Regards,
Benedict Verheyen
Jul 19 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1237
by: lennart | last post by:
Hi, For a website i'm looking for a script which can check the availabililty of several users for an $event. There are several apps that does the job the other way: checking the availability of an object (eg a house, car) and bind it to a person. That's not what i looking for. In my case, you've to make an event (meeting) and add some users the
4
2384
by: Patient Guy | last post by:
Does anyone have any coding rules they follow when doing argument checking? When arguments fail during check, do you return from the call with an ambiguous return value, or do you throw exceptions?
6
7034
by: brian.j.parker | last post by:
I inherited an application (or two) that run on SQL Server 6.5, which I haven't used in years, and am having a problem. I get the error: ------------------------------------------------------------------------ Can't allocate space for object 'Syslogs' in database 'master' because the 'logsegment' segment is full. If you ran out of space in Syslogs, dump the transaction log. Otherwise, use ALTER DATABASE or sp_extendsegment to increase...
16
2634
by: lawrence k | last post by:
I've made it habit to check all returns in my code, and usually, on most projects, I'll have an error function that reports error messages to some central location. I recently worked on a project where someone suggested to me I was spending too much time writing error messages, and that I was therefore missing the benefit of using a scripting language. The idea, apparently, is that the PHP interpreter writes all the error messages that are...
125
6600
by: jacob navia | last post by:
We hear very often in this discussion group that bounds checking, or safety tests are too expensive to be used in C. Several researchers of UCSD have published an interesting paper about this problem. http://www.jilp.org/vol9/v9paper10.pdf Specifically, they measured the overhead of a bounds
1
1341
by: Gemmalouise1988 | last post by:
Hi everyone, My most important college assignment to date seems pretty basic on the outside but I'm sure this will interest a few of you. If you see this document: http://stair.stcoll.ac.uk/jowen/btecsd/pconc/docs/IVA1.pdf and take a brief look to see what it's all about, (a fixtures and points system for a school) take a look on page 3, to see the list of students with their names, house and class. Then look on page 2 to see the...
46
1855
by: John | last post by:
Hi How can I check for existence of a certain table by name in and access database and if the table exists find the number of records in it? I guess I can access this information by setting up a dataset for the database but I am wondering if there is a quick way to find this. Thanks
2
1342
by: Stef Mientki | last post by:
hello, In the code below, I can build a large street like this: large_street = house * 25 but not a small street. like this: small_street = 5 * house Why is this different ? And more interesting, how do I get the right results ?
0
9568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10156
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9951
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9832
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5275
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5419
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3531
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.