24 game is an arithmetic game with a simple rule: Given 4 numbers and use + - * / to get 24.

  • A simple example is 1, 2, 3, 4, and you find 1*2*3*4=24
  • A more difficult one is 5, 5, 5, 1, the answer is 5*(5-(1/5))=24, which includes fractions.

24game project provides a powerful C++ solver for the 24 game. And you can play with the PyQt5 based graphical front end.

In [1]:
#! /usr/bin/env python3
# 求解24点的程序
def pmtd(x,y):
    "Plus minus times divide"
    if y==0:
        x,y=y,x
    if x==0:
        "0 can not be denominator"
        return [y,-y,0]
    return [x+y, x-y, y-x, x*y, x/y, y/x]
def contract(l,i,j):
    "Remove i j and add a space"
    return l[0:i]+l[i+1:j]+l[j+1:]+[0]
def arithn(numl,n=24):
    '''Give out an process to give the given arithmetic result such as 24'''
    l=len(numl)
    if l==1:
        if abs(numl[0]-n)<1e-6:
            return [[n]]
        else:
            return False
    for i in range(l-1):
        for j in range(i+1,l):
            lis=pmtd(numl[i],numl[j])
            sl=contract(numl,i,j)
            for k in lis:
                sl[-1]=k
                res=arithn(sl,n)
                if res:
                    res.append(numl)
                    return res
    return False
if __name__=="__main__":
    print("-"*15+"求解24点"+"-"*15)
    help="输入一串数字,空格隔开,例如: 2 3 5 6,输入q退出"
    print(help)
    while True:
        s=input(">>> ")
        if s == "q":
            break
        s=s.replace(" ",",")
        s='['+s+']'
        try:
            numl=eval(s)
        except:
            print(help)
            continue
        t=arithn(numl)
        if t:
            for i in t[::-1]:
                print(i)
---------------求解24点---------------
输入一串数字,空格隔开,例如: 2 3 5 6,输入q退出
>>> 5 5 5 1
[5, 5, 5, 1]
[5, 5, 0.2]
[5, 4.8]
[24]
>>> q

24game project also provides more readable output.


Comments

comments powered by Disqus