Search code examples
pythonarrayslistpoker

Python: How to find whether a specific number of items in a list are identical?


I am attempting to create a poker game, and I have a list of values which can be anything from Ace to King in a list (named "number"). In order to determine whether or not the player has a "Four of a Kind", the program needs to check if four items in the list of values are identical. I have no clue how to do this. Would you somehow use the number[0] == any in number function four times, or is it something completely different?


Solution

  • Supposing that your number variable is a list of 5 elements (five cards) you can probably try something like:

    from collections import Counter
    numbers = [1,4,5,5,6]
    c = Counter(numbers)
    

    This leverages the awesome Counter class. :)

    Once you have the counter you can check for what is the number of most common occurencies by doing:

    # 0 is to get the most common, 1 is to get the number
    max_occurrencies = c.most_common()[0][1]   
    # this will result in max_occurrencies=2 (two fives)
    

    If you also want to know which one is the card that is so frequent you can get both information in one go using tuple unpacking:

    card, max_occurrencies = c.most_common()[0]
    # this will result in card=5, max_occurrencies=2 (two fives)