范文健康探索娱乐情感热点
投稿投诉
热点动态
科技财经
情感日志
励志美文
娱乐时尚
游戏搞笑
探索旅游
历史星座
健康养生
美丽育儿
范文作文
教案论文
国学影视

Python算法之24点游戏

  问题:输入任意的四个数字,这四个数字的取值范围:1~13,这个四个数经过任意的加、减、乘、除四则运算的结果是24,并输出这四个数所有的运算结果为24的可能计算方式组合。
  例如,输入1,2,6,4
  输出:4*6/(2-1)=26
  (2-1)*4*6=24
  (2+6)*(4-1)=24
  ((2-1)*6)*4=24
  代码:from itertools import combinations import re from numpy import random  class Solver:     # 目标值     target = 24     # 四则运算符     ops = ["+", "-", "*", "/", "--", "//"]      def __init__(self, precise_mode=False):         self.preprecise_mode = precise_mode      def solution(self, nums):         result = []         groups = self.dimensionality_reduction(self.format(nums))         for group in groups:             for op in self.ops:                 exp = self.assemble(group[0], group[1], op)["exp"]                 if self.check(exp, self.target) and exp not in result:                     result.append(exp)         return [exp + "=" + str(self.target) for exp in result]      # 降维     def dimensionality_reduction(self, nums):         result = []         if len(nums) > 2:             for group in self.group(nums, 2):                 for op in self.ops:                     new_group = [self.assemble(group[0][0], group[0][1], op)] + group[1]                     result += self.dimensionality_reduction(new_group)         else:             result = [nums]         return result      # 将两个表达式组合成一个     def assemble(self, exp1, exp2, op):         if op == "--" or op == "//":             return self.assemble(exp2, exp1, op[0])         if op in r"*/":             exp1 = self.add_parenthesis(exp1)             exp2 = self.add_parenthesis(exp2)         if self.preprecise_mode:             if op == "-":                 exp2 = self.add_parenthesis(exp2)             elif op == "/":                 exp2 = self.add_parenthesis(exp2, True)         exp = self.convert(exp1["exp"] + op + exp2["exp"], op)         return {"op": op, "exp": exp}      # 根据需要为表达式添加相应的括号     @staticmethod     def add_parenthesis(exp, is_necessary=False):         if (is_necessary and not exp["exp"].isdigit()) or exp["op"] in r"+-":             result = {                 "exp": "(" + exp["exp"] + ")",                 "op": exp["op"]             }         else:             result = exp         return result      @staticmethod     def check(exp, target, precision=0.0001):         try:             return abs(eval(exp) - target) < precision         except ZeroDivisionError:             return False     #将表达式各项重新排序为等价的表达式     @staticmethod     def convert(exp, op):         if op in r"+-":             pattern = r"([+-](((.+)|d+)[*/]((.+)|d+)|d+))"             exp = "+" + exp         else:             pattern = r"([*/]((.+?)|d+))"             exp="*"+exp         result = "".join(sorted(i[0] for i in re.findall(pattern, exp)))         if len(result) != len(exp):             result = exp         return result[1:]      # 将输入的数字格式化为字典     @staticmethod     def format(nums):         return [{"op": " ", "exp": str(num)} for num in nums]      @staticmethod     def group(exp_list, counter):         # 生成以下标号为元素的列表         index_list = [i for i in range(len(exp_list))]         # 以下标号列表取出不重复的组合         combination = list(combinations(index_list, counter))          for group1 in combination:             group2 = list(set(index_list) - set(group1))             yield [                 [exp_list[g1] for g1 in group1],                 [exp_list[g2] for g2 in group2]             ]   if __name__ == "__main__":     auto_input = False     if auto_input:         customer_input = random.randint(1, 20, size=4)     else:         customer_input = list()         customer_input.append(input("请输入第一个数字:"))         customer_input.append(input("请输入第二个数字:"))         customer_input.append(input("请输入第三个数字:"))         customer_input.append(input("请输入第四个数字:"))     task = Solver()     answer = task.solution(customer_input)     if len(answer) == 0:         print("No solutions")     else:         for a in answer:             print(a)

大家觉得苹果设计的药丸屏。好看吗?为什么?仁者见仁吧个人觉得比刘海好看点。显示空间能提高一点点有人就觉得好,但肯定也有人觉得不好,正所谓没有比较就没有伤害。安卓手机在很多方面其实已经走在了前面,只不过苹果有其独到的粘性。还我收集的DockerImagesdockerrun增加如下参数,限制生成的json。log单个文件大小和保留文件个数logdriverjsonfilelogoptmaxsize10mlogoptmaxsize10OnePlusBudsPro评论设计OnePlusBudsPro长时间佩戴舒适。(图片来源SrivatsaRamesh)OnePlusBudsPro有两种颜色可供选择哑光黑和亮白。这两个选项的茎都是银色的,具有双RustVSPython为什么越来越流行,取代榜一Python?2021年,Python又获得了TIOBE年度编程语言,排名已经是第一。而Rust依然在20名以外。但依然有人认为,Rust甚至可能取代Python。不过这不重要,认清两者的优缺点虚拟数字人概念火爆大规模应用潮能否开启?当前,元宇宙板块进入风口,加上虚拟数字人在主流跨年晚会频繁亮相,进一步打开了市场空间和想象力。为此,虚拟数字人板块及相关概念股曾大涨,1月11日,虚拟数字人板块大挫,1月12日早盘python编程装饰器装饰器importdatetimedeff1()print(thisisafnction)定义是打印一句话deff1()print(fdatetime。datetime。today自带ECC纠错很强大!上手威刚DDR5内存前言不知道大家对ECC内存是什么看法,家里那台工作PC每天要运行12个小时以上,长时间在高负载下进行剪辑工作,一次蓝屏死机可能就要丢失不少关键数据。这里给不了解真相的朋友介绍一下E心心念念极米NEWZ8X到手,美美看雪刀了试问天上仙人,谁敢来此人间。作为忠实书粉,我在雪中悍刀行开播前就看了不少路透,现在开播更是每次更新都要第一时间跟着看!除了打怪升级的爽文Buff之外,我的追剧利器也是陪伴我一直追剧PC端电脑硬件市场已死?(前篇)移动通信的发展,促进了手机的更新迭代。特别是现在5G环境下运行的智能手机,不仅是娱乐工具,也是办公工具。一代一代的发展过来,到现在的智能手机,取代了曾经的音频播放器(MP3MP4)Xiaomi12玩了有一星期,你要问我体验如何,我只能说玩腻了新年第一个月做的最错误的决定就是买了xiaomi12,做的最正确的一个决定也是买了xiaomi12。为什么说买xiaomi12是个错误的决定呢,因为我最近几天在测试xiaomi12荣耀推出首个高端折叠屏手机,京东方沃特股份亮明合作关系21世纪经济报道记者雷晨北京报道1月11日晚间,距荣耀发布折叠屏手机仅一天时间,就有超过3万人在京东平台上预约抢购。此前1月10日晚,荣耀发布了其首款高端折叠屏手机荣耀MagicV