X of a Kind in a Deck of Cards
In this problem, we need to partition the cards into groups where each group contains cards with the same number and the size of each group is greater than 1.
One way to solve this problem is by using a dictionary to count the occurrences of each number in the deck and then checking if there is a common divisor greater than 1 for all the counts.
Python solution:


In this code:
We import the necessary modules.
Counter
fromcollections
is used to count the occurrences of each number in the deck,gcd
frommath
is used to calculate the greatest common divisor, andreduce
fromfunctools
is used to apply the gcd function to all values in the count dictionary.We define a method
hasGroupsSizeX
which takes a listdeck
as input and returns a boolean value.We create a
Counter
object fordeck
, which is a dictionary where the keys are the elements indeck
and the values are the counts of their occurrences.We use the
reduce
function to apply thegcd
function to all values incount
. Thereduce
function applies a function of two arguments cumulatively to the items of an iterable, in this casecount.values()
, so as to reduce the iterable to a single output.We check if the greatest common divisor of all counts is greater than or equal to 2. If it is, we return
True
, indicating that it’s possible to partition the deck into groups where each group contains cards with the same number and the size of each group is greater than 1. If it’s not, we returnFalse
.