24点python算法实现

#!/usr/bin/python3
# -*- coding:utf-8 -*-
'''
 ____  _  _     ____       _       _       
|___ \| || |   |  _ \ ___ (_)_ __ | |_ ___ 
  __) | || |_  | |_) / _ \| | '_ \| __/ __|
 / __/|__   _| |  __/ (_) | | | | | |_\__ \\
|_____|  |_|   |_|   \___/|_|_| |_|\__|___/

 Given any four number in the range 1 to 10, which may have repetitions,
 Using just the +, -, *, / operators; and the possible use of
 brackets, (), show how to make an answer of 24.

 An answer of "!" will generate a new set of four numbers (if your stuck).
 Otherwise you are repeatedly asked for an expression until it evaluates to 24

 Note: you cannot form multiple digit numbers from the supplied numbers,
 so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.

'''

from operator import mul, sub, add
import random
import sys
while True:
    def choose4():
        'four random digits >0 as characters'
        return [random.randint(1,10) for i in range(4)]
    def welcome():
        print (__doc__)
        print ('Try to input four numbers:\n e.g. 1 2 3 4\n\t')
        nums=list(map(int, input().split(' ')))
        print ("Your four number: " + " ".join(str(nums)))
        return nums
    def div(a,b):
        if b==0:
            return 999999.0
        return a/b
    def solve24(num, how,target):
        global counts
        ops ={mul:'*', div:'/', sub:'-', add:'+'} 
        if len(num)==1:
            if round(num[0],5) ==round(target,5):
                yield str(how[0]).replace(',', '').replace("'", '')
        else:
            for i, n1 in enumerate(num):
                for j, n2 in enumerate(num):
                    if i!=j:
                        for op in ops:
                            new_num=[ n for k, n in enumerate(num) if k!=i and k!=j ] +[op(n1,n2)]
                            new_how=[h for k, h in enumerate(how) if k!=i and k!=j]+[(how[i], ops[op], how[j])]
                            counts+=1
                            print ("i= ", i, "; j= ", j, "; n1= ", n1, "; n2= ", n2, "\n new_num= ", new_num, "\tnew_how= ", new_how)
                            yield from solve24(new_num, new_how, target)

    counts=0
    nums = welcome()
    if len(nums)!=4:
        nums = choose4() 
    try:
        print(next(solve24(nums, nums, 24)))
        print('Total trys: ', counts)
        break
    except StopIteration:
        print("!No solution found.")
        print('Total trys: ', counts)

主要参考的https://rosettacode.org/wiki/24_game/Solve
对算法本身不是非常理解:

  1. 似乎没有考虑顺序问题, 即为什么[1,2,3,4]和[3,4,2,1]这样同样的数组上述算法一定能找到解;
  2. 如何加入乘方与开方以及阶乘运算.
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文内容:1、什么是算法?2、算法分析基础?3、文集列表 建议数据结构和算法分开来学,这里只有算法,没有什么是数据...
    半纸渊阅读 770评论 0 5
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,009评论 19 139
  • 原文地址:http://theory.stanford.edu/~amitp/GameProgramming/ 1...
    达微阅读 19,674评论 0 28
  • 很多年以前《哈佛商业评论》上有一篇广为引用的文章曾提出问题:“中层管理过时了吗?”它给出了一个极为肯定的答案。但放...
    管理顾问王荣增阅读 675评论 0 3
  • 甲方(以下简称甲方):广州健华玻璃制品加工有限公司 乙方(以下简称乙方): 诚信合作...
    胡家国阅读 1,389评论 0 0