Skip to content

Instantly share code, notes, and snippets.

@catupper
Created May 14, 2011 17:31
Show Gist options
  • Save catupper/972416 to your computer and use it in GitHub Desktop.
Save catupper/972416 to your computer and use it in GitHub Desktop.
sisoku
#coding:utf-8
from __future__ import division #整数割り算時の切り捨て解除
#演算子と文字列(出力用)のリスト
funcs=[lambda x,y:x+y,lambda x,y:x-y,lambda x,y:y-x,lambda x,y:x*y,lambda x,y:x/y,lambda x,y:y/x]
sikifuncs=[lambda x,y:"("+x+"+"+y+")",lambda x,y:"("+x+"-"+y+")",lambda x,y:"("+y+"-"+x+")",lambda x,y:"("+x+"*"+y+")",lambda x,y:"("+x+"/"+y+")",lambda x,y:"("+y+"/"+x+")"]
def make(numlist,ans,siki):
L=len(numlist)
if L==1:
if abs(numlist[0]-ans)<1/100000.0:
return siki
else:return False
else:
for i in range(6):
for j in range(L-1):
n=numlist[:]
s=siki[:]
try:
n.insert(j,funcs[i](n.pop(j),n.pop(j)))
s.insert(j,sikifuncs[i](s.pop(j),s.pop(j)))
except ZeroDivisionError:
continue
res=make(n,ans,s)
if res: return res
return False
#並び替え関数
def conb(numlist,x):
if x==0: return [[]]
else: return [[a]+b for i,a in enumerate(numlist) for b in conb(numlist[:i]+numlist[i+1:],x-1)]
#重複
def setlist(list):
res=[]
while len(list):
if not res.count(list[0]):res.append(list.pop(0))
list.pop(0)
return res
def solve(numlist,ans):
numlists=conb(numlist,len(numlist))
numlists=setlist(numlists)
for list in numlists:
siki=map(str,list)
res=make(list,ans,siki)
if res:yield res[0]
yield False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment