I've been learning python for the past few weeks using a combination of the Learn Python the Hard Way website and the MIT OCW 6.000 materials. I don't have any formal training in CS, although my day job involves "programming" in statistical packages, and much of Python's syntax is similar to how these packages work. As an exercise, I wrote a function to rank a poker hand of the form ['Ac', '8d', '8h', '2c', 'Ah'].
My first draft had a lot of if statements, and after several revisions I got rid of those largely by using a dictionary and paired the program down to something about half as long.
Code:
def rank(hand):
handVals, handSuits, counts, straight, flush, i, j = [], [], [], 0, 0, 0, 0
values = map(str, range(2, 10)) + ['T', 'J', 'Q', 'K', 'A']
handcodeRank = {11:'Straight flush', 42:'Four of a kind', 32:'Full house',
10:'Flush', 01:'Straight', 33:'Three of a kind',
23:'Two pair', 24:'One pair', 15:'High card'}
for h in hand: #split hand into values and suit
handVals += (values.index(h[0]), )
handSuits += (h[1], )
handVals.sort()
while i < len(handVals): #count occurrences of values in hand
counts += [handVals.count(handVals[i]), ]
i += counts[j]
j += 1
flush = + len(set(handSuits)) == 1
straight = + max(handVals) - min(handVals) == 4 and max(counts) == 1
straight += + (handVals == [0, 1, 2, 3, 12])
handcode = abs(max(straight, flush) - 1)*(10*max(counts) + len(counts))
handcode += 10*flush + straight
return handcodeRank[handcode]
Any tips as far as avoiding bad habits?
Also I was curious about the use of Boolean values as integers, e.g.
Code:
flush = + len(set(handSuits)) == 1
I frequently use this type of code in my data work to define dummy variables. But I was wondering whether if statements are preferred for readability (especially in Python)?
Code:
if len(set(handSuits)) == 1:
flush = 1