"mwdsmith" <[EMAIL PROTECTED]> 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(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? 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.values(): 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 -- http://mail.python.org/mailman/listinfo/python-list