LoginSignup
1
0

More than 1 year has passed since last update.

ABC79 C - Train Ticket が解けた

Last updated at Posted at 2021-09-25

abc79_1.png
abc79_2.png
abc79_3.png

op は 2 種類しかないうえに、
op は 3 つしかない。2^3 だから全探索で余裕だ

TrainTicket.py
ABCD = input()
lisST = list(ABCD)
lisINT = list(map(lambda x:int(x),lisST))
OP =["+","-"]
#print(lisST,lisINT)
ans = ""
from itertools import product
for op1,op2,op3 in product(["+","-"],repeat=3):
    #print(op1,op2,op3)
    if op1 == "+":
        num1=lisINT[0]+lisINT[1]
        ans += lisST[0]+"+"+lisST[1]
    else:
        num1=lisINT[0]-lisINT[1]
        ans += lisST[0]+"-"+lisST[1]

    if op2 == "+":
        num2=num1+lisINT[2]
        ans += "+"+lisST[2]
    else:
        num2=num1-lisINT[2]
        ans += "-"+lisST[2]

    if op3 == "+":
        num3=num2+lisINT[3]
        ans += "+"+lisST[3]
    else:
        num3=num2-lisINT[3]
        ans += "-"+lisST[3]

    if num3 == 7:
        print(ans+"=7")
        break
    else:
        ans = ""

全部列挙は苦痛だったので、
文字をそのまま計算できる eval() を使った。

abc79c.py
S = list(input())

from itertools import product
for op in product(["+","-"],repeat=3):
    op = list(op)
    num = ""
    for i in range(3):
        num += S[i]+op[i]
    num += S[3]
    if eval(num)==7:
        print(num+"=7")
        exit()
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0