首页 > 其他 > 详细

算24程序设计题

时间:2020-04-16 12:14:18      阅读:58      评论:0      收藏:0      [点我收藏+]

使用加、减、乘、除4种运算以及括号把给出的4 个小于10的正整数连接起来得到一个表达式,并且使得所得的这个表达式的结果等于24

这里加、减、乘、除4种运算以及括号的运算结果与运算优先级跟平常定义一致

number = [0] * 4
result = [‘‘] * 4
def PointsGame(n):
    if n == 1:
        return abs(number[0] - 24) < 1e-6
    
    for i in range(n):
        for j in range(i+1,n):
            a, b = number[i], number[j]
            number[j] = number[n-1]
            
            charA, charB = result[i],result[j]
            result[j] = result[n-1]
            
            result[i] = ‘(‘ + charA + ‘+‘ + charB + ‘)‘
            number[i] = a + b
            if PointsGame(n-1):
                return True
            
            result[i] = ‘(‘ + charA + ‘-‘ + charB + ‘)‘
            number[i] = a - b
            if PointsGame(n-1):
                return True
            
            result[i] = ‘(‘ + charA + ‘*‘ + charB + ‘)‘
            number[i] = a * b
            if PointsGame(n-1):
                return True
            
            if b != 0:
                result[i] = ‘(‘ + charA + ‘/‘ + charB + ‘)‘
                number[i] = a / b
                if PointsGame(n-1):
                    return True
                
            if a != 0:
                result[i] = ‘(‘ + charB + ‘/‘ + charA + ‘)‘
                number[i] = b / a
                if PointsGame(n-1):
                    return True
            
            number[i], number[j] = a, b
            result[i], result[j] = charA ,charB
    return False

if __name__ == ‘__main__‘:
    for i in range(4):
        x = input()
        number[i] = int(x)
        result[i] = x
    if PointsGame(4):
        print(‘YES‘)
        print(result[0])
    else:
        print(‘NO‘)

  

算24程序设计题

原文:https://www.cnblogs.com/cnn-ljc/p/12711771.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!