Classic Fun 24-point game programming (Python)

Source: Internet
Author: User

First, Gameplay introduction:

24-point game is one of the main puzzle games played in childhood, play for: from a pair of poker 4 cards, 4 cards using any method in subtraction, so that the results of the calculation is 24. For example, 2,3,4,6, by (((4 + 6)-2) * 3) = 24, the quickest to figure out 24 remains.

Second, design ideas:

Since the expression was designed, it was natural to think about whether you could use an expression tree to design your program. This program does use expression trees, and is the most critical part of the program. A brief summary is that the possibility of all expressions is listed first, and then the expression tree is used to evaluate the value of an expression. The application of a large number of recursion, the recursive type is not very complex, we have patience to see, should be able to understand

An expression tree:

All leaf nodes of the expression tree are operands (operand) and the other nodes are operators (operator). Because this example is a two-dollar operation, the expression tree is a two-fork tree. is an expression tree.

  

Specific steps:

1. The possibility of traversing all expressions

Traversal is divided into two parts, one part traversing all possible operands, and then all possible of the operator. The idea of recursion is used in the whole permutation calculation.

# returns a list of fully arranged list collections def List_result (L):     if len (l) = = 1:        return  [l    ]= [    ]for in  Enumerate (L):        = List_result (L[0:index] + l[index+1:])        map (Lambda x:x.append (item), R)        All_result.extend (R)    return All_result

2. Constructs an expression tree based on the value of the passed-in expression

Due to the characteristics of the expression tree, all operands are leaf nodes, operators are non-leaf nodes, and an expression (e.g. (((6 + 4)-2) * 3) = 24) has only 3 operators, that is, an expression tree has only 3 non-leaf nodes. So the shape of the tree is only two possible, and it's written directly to death.

  

# tree Node class Node:     def __init__ (Self, val):         = val        = none        = None

defone_expression_tree (Operators, operands): Root_node=Node (operators[0]) Operator1= Node (operators[1]) Operator2= Node (operators[2]) operand0=Node (operands[0]) Operand1= Node (operands[1]) Operand2= Node (operands[2]) Operand3= Node (operands[3]) Root_node.left=Operator1 root_node.right=operand0 Operator1.left=Operator2 operator1.right=Operand1 Operator2.left=Operand2 operator2.right=Operand3returnRoot_nodedeftwo_expression_tree (Operators, operands): Root_node=Node (operators[0]) Operator1= Node (operators[1]) Operator2= Node (operators[2]) operand0=Node (operands[0]) Operand1= Node (operands[1]) Operand2= Node (operands[2]) Operand3= Node (operands[3]) Root_node.left=Operator1 root_node.right=Operator2 Operator1.left=operand0 operator1.right=Operand1 Operator2.left=Operand2 operator2.right=Operand3returnRoot_node

3. Calculate the value of an expression tree

Recursion is also used.

  

#calculates a value based on two numbers and a symboldefCal (A, B, operator):returnoperator = ='+'  andFloat (a) + float (b)oroperator = ='-'  andFloat (a)-float (b)oroperator = ='*'  andFloat (a) * Float (b)oroperator = ='÷'  andFloat (a)/float (b)defcal_tree (node):ifNode.left isNone:returnNode.valreturnCal (Cal_tree (Node.left), Cal_tree (node.right), Node.val)

4. Output all possible expressions

Or the use of recursion

defPrint_expression_tree (Root): Print_node (Root)Print '='defPrint_node (node):ifNode isNone:return    ifNode.left isNone andNode.right isNone:PrintNode.val,Else:        Print '(', Print_node (node.left)PrintNode.val, Print_node (node.right)Print ')',        #print ' (%s%s%s) '% (Print_node (node.left), Node.val, Print_node (node.right)),

5. Output results

Three, all the source code

  

#Coding:utf-8 from __future__ ImportDivision fromNodeImportNodedefCalculate (nums): Nums_possible=List_result (nums) operators_possible= List_result (['+','-','*','÷']) Goods_noods= []     forNumsinchnums_possible: forOpinchOperators_possible:node=one_expression_tree (OP, nums)ifCal_tree (node) = = 24: Goods_noods.append (node) node=two_expression_tree (OP, nums)ifCal_tree (node) = = 24: Goods_noods.append (node) map (Lambdanode:print_expression_tree (node), goods_noods)defcal_tree (node):ifNode.left isNone:returnNode.valreturnCal (Cal_tree (Node.left), Cal_tree (node.right), Node.val)#calculates a value based on two numbers and a symboldefCal (A, B, operator):returnoperator = ='+'  andFloat (a) + float (b)oroperator = ='-'  andFloat (a)-float (b)oroperator = ='*'  andFloat (a) * Float (b)oroperator = ='÷'  andFloat (a)/float (b)defone_expression_tree (Operators, operands): Root_node=Node (operators[0]) Operator1= Node (operators[1]) Operator2= Node (operators[2]) operand0=Node (operands[0]) Operand1= Node (operands[1]) Operand2= Node (operands[2]) Operand3= Node (operands[3]) Root_node.left=Operator1 root_node.right=operand0 Operator1.left=Operator2 operator1.right=Operand1 Operator2.left=Operand2 operator2.right=Operand3returnRoot_nodedeftwo_expression_tree (Operators, operands): Root_node=Node (operators[0]) Operator1= Node (operators[1]) Operator2= Node (operators[2]) operand0=Node (operands[0]) Operand1= Node (operands[1]) Operand2= Node (operands[2]) Operand3= Node (operands[3]) Root_node.left=Operator1 root_node.right=Operator2 Operator1.left=operand0 operator1.right=Operand1 Operator2.left=Operand2 operator2.right=Operand3returnRoot_node#returns a list of fully arranged list collectionsdefList_result (L):ifLen (L) = = 1:        return[l] All_result= []     forIndex,iteminchEnumerate (L): R= List_result (L[0:index] + l[index+1:]) Map (Lambdax:x.append (item), R) All_result.extend (r)returnAll_resultdefPrint_expression_tree (Root): Print_node (Root)Print '='defPrint_node (node):ifNode isNone:return    ifNode.left isNone andNode.right isNone:PrintNode.val,Else:        Print '(', Print_node (node.left)PrintNode.val, Print_node (node.right)Print ')',if __name__=='__main__': Calculate ([2,3,4,6])
View Code

Classic Fun 24-point game programming (Python)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.