Project Euler:Problem 93 Arithmetic expressions

By using each of the digits from the set, {1, 2, 3, 4}, exactly once, and making use of the four arithmetic operations (+, , *, /) and brackets/parentheses, it is possible to form different positive integer targets.

For example,

8 = (4 * (1 + 3)) / 214 = 4 * (3 + 1 / 2)19 = 4 * (2 + 3) 136 = 3 * 4 * (2 + 1)

Note that concatenations of the digits, like 12 + 34, are not allowed.

Using the set, {1, 2, 3, 4}, it is possible to obtain thirty-one different target numbers of which 36 is the maximum, and each of the numbers 1 to 28 can be obtained before encountering the first non-expressible number.

Find the set of four distinct digits,a<b<c<d, for which the longest set of consecutive positive integers, 1 ton, can be obtained, giving your answer as a string:abcd.

先求出10选4的所有组合情况,保存为list

对于每一种组合都有24种排列情况

每一个排列情况其运算顺序都有5种

关于四个数的运算涉及到3个操作符,,而且每个操作符理论上有四种选择:加减乘除。并将得出的整数运算结果标记出来。

最终是要比较每一种组合的标记出来的结果,从1到n都有标记的最大的那个n

def xcombination(seq,length):if not length:yield []else:for i in range(len(seq)):for result in xcombination(seq[i+1:],length-1):yield [seq[i]]+resultdef nextPermutation(self, num):if len(num) < 2:return numpartition = -1for i in range(len(num) – 2, -1, -1):if num[i] < num[i + 1]:partition = ibreakif partition == -1:return num[::-1]for i in range(len(num) – 1, partition, -1):if num[i] > num[partition]:num[i], num[partition] = num[partition], num[i]breaknum[partition + 1:] = num[partition + 1:][::-1]return numdef ope(a,b,num):if a==None or b==None:return Noneif num == 1:return a+bif num == 2:return a-bif num == 3:return a*bif num == 4:if b == 0:return Noneelse:return a/bcomb=xcombination([i for i in range(10)],4)comb_list=list(comb)bestprem=[0 for i in range(4)]bestres=0for prem in comb_list:tmp=premflag=1num_list=[0]*(9*8*7*6)while tmp != prem or flag==1:flag=0for i in range(1,5):for j in range(1,5):for k in range(1,5):num=ope(ope(ope(prem[0],prem[1],i),prem[2],j),prem[3],k)if num!=None and num==int(num) and num > 0 and num < len(num_list):num_list[int(num)]=Truenum=ope(ope(prem[0],ope(prem[1],prem[2],j),i),prem[3],k)if num!=None and num==int(num) and num > 0 and num < len(num_list):num_list[int(num)]=Truenum=ope(prem[0],ope(ope(prem[1],prem[2],j),prem[3],k),i)if num!=None and num==int(num) and num > 0 and num < len(num_list):num_list[int(num)]=Truenum=ope(prem[0],ope(prem[1],ope(prem[2],prem[3],k),j),i)if num!=None and num==int(num) and num > 0 and num < len(num_list):num_list[int(num)]=Truenum=ope(ope(prem[0],prem[1],i),ope(prem[2],prem[3],k),j)if num!=None and num==int(num) and num > 0 and num < len(num_list):num_list[int(num)]=Truecount=1while num_list[count]==True:count=count+1if count > bestres:bestres=countbestprem=premprem=nextPermutation((),[prem[i] for i in range(4)])print(bestres,' ',bestprem)

版权声明:本文为博主原创文章,未经博主允许不得转载。

经验是由痛苦中粹取出来的

Project Euler:Problem 93 Arithmetic expressions

相关文章:

你感兴趣的文章:

标签云: