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. 如何加入乘方与开方以及阶乘运算.

你可能感兴趣的:(24点python算法实现)