Preword
Because I am going to teach at a coding summer camp to middle school kids in Changsha very soon. I have been searching for interesting projects for them to build so they can learn better. And this idea of building a solver for the 24 Game cross my mind. It is rather interesting and takes me actually a lot longer than I expect to finish it. Probably won’t give this to them; maybe as a optional challenge.
What is the 24 Game?
It is basically a Card game. It originates in China sometime last century.
This Chinese game requires skill at mental arithmetic. It has been played in Shanghai at least since the 1960’s and may have originated there, and it is also known in some other cities, for example in Qingdao and Guangzhou. Since the end of the 20th century it has also spread to some places in North America. The basic game for two players will be described first, followed by variations for a larger number of players and extra options.
Basically you are given a deck of poker cards and the Jokers are removed. You treat A~10 as 1~10 and J~K as 11~13, (in early versions only A~10 is included) and you have to do some calculations to the four card so the result equals 24. Only basic arithmetics are allowed (+
, 
, *
, /
and ( )
) and each number can only be used once. For example if the four cards were 2, 3, 6, 9 then possible solutions would be (9+63)×2=24
, (93)×(62)=24
or (9×3)(6÷2)=24
. Whoever can tell a correct equation first wins the round.
The Algorithm
Was thinking of a iterative approach but code will be too ugly to read. Decide to do a recursive approach. Basically the thinking is to reduce the amount of numbers to calculate to two, so if the output equals 24 it is valid. Take 2 numbers each time and do the 4 operations to reduce to one number and eventually there will be only 2 numbers remaining. Theoretically, this should apply to any amount of numbers and any output to be calculated.
For example:
 There are 4 numbers, take 2 of them and do some calculations so there will be 3 numbers remaining.
 Now there are 3 numbers, do whatever operations so there will be only 2 numbers remaining.
 If the 2 can get the output of 24, it is a valid equation; otherwise it is false.
The Implementation


Sample Output
4 Numbers
123456$python3 24Game.pyenter the numbers you want to solveNote: each number has to be separated by A SPACEyou can enter any numbers you like and any amount of it5 5 5 1The answer is: ((5(1/5))*5) = 24More than 4 Numbers
123456$python3 24Game.pyenter the numbers you want to solveNote: each number has to be separated by A SPACEyou can enter any numbers you like and any amount of it9 9 9 9 7 7 7 7 3 2 5 6 1 3 8The answer is: (((((((((((9+9)+8)+3)+1)+6)+5)+2)+3)+7)+7)/((9/(79))+7)) = 24