Search code examples
pythonpoker

Detect Straight in 7-card poker hand


The following code checks for all straights in a five-card hand (except 5-high, which I add in as an elif)

def straight(values,vset):
    if (max(vset) - min(vset) == 4) and numpair(values) == False and detset(values) == False and quads(values) == False:
#STRAIGHT DETECTED

Vset is just a set containing the values. The problem is, I cannot figure out a way to adapt this code to evaluate a 7-card holdem hand. Any advice?


Solution

  • While @JohnGordon's solution works it wastefully iterates 5 times for each rank value.

    A more efficient approach would be to iterate the rank from 2 to 14 and simply use a counter to keep track of the number of times so far the rank exists in the cards consecutively, and if a consecutive rank doesn't exist, reset the counter. Determine that there is a straight if the counter reaches 5. To account for the fact that an Ace (assuming its rank is 14 here) can be regarded as a 1 to form a straight with 2, 3, 4, and 5 as well, you can prepend 14 to the range of 2 to 14 for iteration:

    count = 0
    for rank in (14, *range(2, 15)):
        if rank in vset:
            count += 1
            if count == 5:
                print('Straight found')
                break
        else:
            count = 0
    else:
        print('Straight not found')