Skip to content

Instantly share code, notes, and snippets.

@retarfi
Last active February 19, 2018 16:29
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save retarfi/0994e1813904a90a8b26097ba8bec8e2 to your computer and use it in GitHub Desktop.
1,2,3,4,5,6,7,8,9の間に+,-,xのうちどれかを入れて結果が1となるようなものを抽出
for i in range(6561): #6561=3^8
numli = [1,2,3,4,5,6,7,8,9] #計算式に出てくる数字
calcli = [] #+を0,-を1,xを2として3進法8桁で演算子を表す
while i != 0:
calcli.append(int(i%3))
i = int(i/3)
if(len(calcli)<8): #8桁に足りない部分は全部0にする
for j in range(8-len(calcli)):
calcli.append(0)
calcli.reverse() #全通り試すのでなくてもいい
calcli_dumy = [] #calcliをコピー
for j in range(len(calcli)):
calcli_dumy.append(calcli[j])
#乗算は先に処理
for j in range(8):
if calcli[j] == 2:
numli[j+1] *= numli[j]
numli[j] = -1 #乗算をした数字は使わない
calcli[j] = -1 #乗算をした演算子は使わない
while -1 in numli:
numli.remove(-1)
calcli.remove(-1)
result = numli[0]
#以下加算と減算
for j in range(len(calcli)):
if calcli[j] == 0:
result += numli[j+1]
elif calcli[j] == 1:
result -= numli[j+1]
#結果が1なら合致なのでその計算を文字列で取り出す
if result == 1:
string = "1"
for j in range(8):
if calcli_dumy[j]==0:
string += "+" + str(j+2)
elif calcli_dumy[j]==1:
string += "-" + str(j+2)
elif calcli_dumy[j]==2:
string += "x" + str(j+2)
string += "=1"
print(string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment