Python implementation of algorithm 24

Source: Internet
Author: User

1. Introduction

  Given 4 integers, the number range is between 1-13, any use of +-*/(), constructs an expression, makes the final result is 24, this is the common 24 game. This article describes two methods that are implemented in the Python language.
2. Realization of Ideas

Implements the arrangement of 4 numbers, which equals the function of parentheses, and then uses +-*/for combination calculation.
The first way to use shorthand is better than the second.
The second, according to the general idea of implementation, annotated, easier to read.

3. Code implementation

3.1 First, use the slice operation of the list to implement the permutation combination and use the exception for the next loop.

#Encoding=utf-8a = Int (input ("Please enter a 1th number:")) b= Int (Input ("Please enter a 2nd number:")) C= Int (Input ("Please enter a 3rd number:")) d= Int (Input ("Please enter a 4th number:")) List1=[A, B, C, D]list2=[]list3=[]symbols= ["+","-","*","/"]classfindexception (Exception):PassTry:     forIinchRange (4): One=List1[i] List2= List1[0:i] + list1[i + 1:]         forJinchRange (3): both=List2[j] List3= List2[0:j] + list2[j + 1:]             forKinchRange (2): Three=List3[k] Four= (List3[0:k] + list3[k + 1:]) [0] forS1inchSymbols: forS2inchSymbols: forS3inchsymbols:express="((one {0}) {1} three) {2} four". Format (S1, S2, S3)ifeval (Express) = = 24:                                Print("(({0} {1} {2}) {3} {4}) {5} { 6} =". Format (one, S1, S2, three, S3, four))RaisefindexceptionPrint("can't figure out")exceptfindexception:Pass

3.2 Second, using the Itertools module to arrange the combination, using variables such as variable VAL1,VAL2 to store intermediate variables to achieve the effect of the next cycle.

#Encoding=utf-8#use your familiar programming language to implement the 24 algorithm#known 4 integers, the number range is between 1-13, the calculation method (limited subtraction, can be enclosed in parentheses), you can calculate theImportItertoolsImportCopya= Int (Input ("Please enter a 1th number:")) b= Int (Input ("Please enter a 2nd number:")) C= Int (Input ("Please enter a 3rd number:")) d= Int (Input ("Please enter a 4th number:")) Inputlist=[A, B, C, D]listall= []#The permutation combination used to store this list number [[],[],[],[] ...]Listsignindex = []#the order of operation symbols used to store the output is the following table 0,1,2,3 corresponding +-*/Listsign = []#the operation symbol used to store the OUTPUT +-*/Listset = List (Itertools.permutations (Inputlist, 4))#unordered permutation combinations forIinchlistSet:listAll.append (List (i))#convert tuples to lists with list ()#convert the following table of operational symbols into corresponding symbolsdefchangeindextosign (): forIinchListsignindex:ifi = =0:listsign.append ("+")            elifi = = 1: Listsign.append ("-")        elifi = = 2: Listsign.append ("*")        elifi = = 3: Listsign.append ("/") Last= []       defstart ():Global Last while1:         forList1inchListall:val=List1[0] last=copy.deepcopy (List1) forIinchRange (4):                ifi = =0:val+ = List1[1]                elifi = = 1: Val-= List1[1]                elifi = = 2: Val*= list1[1]                elifi = = 3: Val/= list1[1] Val2= Val#saves the value of the current Val value, or list1[0] list1[1] Operation                 forJinchRange (4):                    ifj = =0:val+ = List1[2]                    elifj = = 1: Val-= List1[2]                    elifj = = 2: Val*= list1[2]                    elifj = = 3: Val/= list1[2] Val1= Val#saves the value of the current Val value, which is list1[0] list1[1] list[2] Operation                     forKinchRange (4):                        ifK = =0:val+ = List1[3]                        elifK = = 1: Val-= List1[3]                        elifK = = 2: Val*= list1[3]                        elifK = = 3: Val/= list1[3]                        ifval = = 24: Listsignindex.append (i) Listsignindex.append (j) Listsignindex.append (k) changeindextosign ()return                         Else: Val= Val1#If this cycle does not work, then set Val to List1[0] list1[1] list[2] The value of the Operationval = val2#if the 3rd value is not finished, then Val is also set to the value of the list1[0] list1[1] operation.val = list1[0]#if 3rd, the 4th value is not finished, the Val is also set to list1[0] valuestart () listsign.append (""); Laststr="((" forIinchRange (4):    ifi = = 1ori = = 2: Laststr+ = str (last[i]) +")"+Listsign[i]Else: Laststr+ = str (last[i]) +Listsign[i]Print(LASTSTR)

Original blog post, if reproduced, please note the source Kazakhstan.

Python implementation of algorithm 24

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.