玩蛇网提供最新Python编程技术信息以及Python资源下载!

Python math方法算24点代码详解

python 培训

计算24点的方法有很多,今天是用python编程语言的python math方法来算24点,代码如下(供参考):

import math

PRECISION = 1E-6
COUNT_OF_NUMBER = 4
NUMBER_TO_BE_CAL = 24

g_number = [4, 4, 7, 7]
g_expression = ['', '', '', '']
for i in range(0, 4):
    g_expression[i] = "%d" % g_number[i]
print(g_expression)


def solve(n):
    if(1 == n):
        if(math.fabs(NUMBER_TO_BE_CAL - g_number[0]) < PRECISION):
            print(g_expression[0])
            return True
        else:
            return False
    else:
        for i in range(0, n):
            for j in range(i+1, n):
                a = g_number[i]
                b = g_number[j]
                #**********************************
                #   将剩下的有效数字往前挪,
                #   由于两数计算结果保存在number[i]中,
                #   所以将数组末元素覆盖number[j]即可
                #www.iplaypython.com
                #**********************************
                g_number[j] = g_number[n - 1]
                expa = g_expression[i]
                expb = g_expression[j]
                g_expression[j] = g_expression[n - 1]
                # 计算a+b
                g_expression[i] = '(' + expa + '+' + expb + ')'
                g_number[i] = a + b
                if ( solve(n - 1) ) :
                    return True;

                # 计算a-b
                g_expression[i] = '(' + expa + '-' + expb + ')'
                g_number[i] = a - b
                if ( solve(n - 1) ) :
                    return True

                # 计算b-a
                g_expression[i] = '(' + expb + '-' + expa + ')'
                g_number[i] = b - a
                if ( solve(n - 1) ):
                    return True

                # 计算(a*b)
                g_expression[i] = '(' + expa + '*' + expb + ')'
                g_number[i] = a * b
                if ( solve(n - 1) ):
                    return True;

                # 计算(a/b)
                if (b != 0) :
                    g_expression[i] = '(' + expa + '/' + expb + ')'
                    g_number[i] = a / b
                    if ( solve(n - 1) ) :
                        return True

                # 计算(b/a)
                    if (a != 0) :
                        g_expression[i] = '(' + expb + '/' + expa + ')'
                        g_number[i] = b / a
                        if ( solve(n - 1) ):
                            return True

                 # 恢复现场
                g_number[i] = a
                g_number[j] = b
                g_expression[i] = expa
                g_expression[j] = expb
        return False

if(not solve(COUNT_OF_NUMBER)):
    print('no solution')

玩蛇网原创,转载请注明文章出处和来源网址:http://www.iplaypython.com/code/algorithm/a2511.html



微信公众号搜索"玩蛇网Python之家"加关注,每日最新的Python资讯、图文视频教程可以让你一手全掌握。强烈推荐关注!

微信扫描下图可直接关注

玩蛇网Python新手QQ群,欢迎加入: ① 240764603 玩蛇网Python新手群
文章发布日期:2016-03-23 15:17 玩蛇网 www.iplaypython.com

评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
相关文章推荐
别人正在看
特别推荐
去顶部去底部