Here you have to arrange the order in ASCII order. So the order in which you display your answer matter or else it is wrong. I nonchalantly did + -> - -> “ “ but you have to do “ “ -> + -> -.
Without eval(), when i wanted to explore the blank space option (“ “),i needed to see the sign of the latest number added to my expression. This is cuz of the pic below.
Wow and there was this eval() function that calculates the expression automatically for us. I didnt know that function so i was keeping a sum parameter to calculate the sum along the way. However, eval() cant process “ “ the blank spaces so we have to replace the blank spaces with empty space “” with Python’s replace() before invoking the eval() function.
from collections import defaultdict
def dfs(n, index, total, expression, lst):
global dic
if index == n:
if total == 0:
dic[n].append(expression[1:])
return
if expression[-2]=='+':
dfs(n, index + 1, total-int(expression[-1]) + int(expression[-1] + str(lst[index + 1])), expression + " " + str(lst[index + 1]), lst)
elif expression[-2]=='-':
dfs(n, index + 1, total+int(expression[-1]) - int(expression[-1] + str(lst[index + 1])), expression + " " + str(lst[index + 1]), lst)
dfs(n, index + 1, total + lst[index + 1], expression + "+" + str(lst[index + 1]), lst)
dfs(n, index + 1, total - lst[index + 1], expression + "-" + str(lst[index + 1]), lst)
t = int(input())
ans = []
for _ in range(t):
ans.append(int(input()))
dic = defaultdict(list)
n = 10
for i in range(3, 10):
lst = [i for i in range(0, n + 1)]
dfs(i, 1, 1, "+1", lst)
for i in ans:
for val in dic[i]:
print(val)
print()
import sys
input = sys.stdin.readline
def dfs(n, idx, rst):
if idx == N:
# eval 함수를 활용하여 문자열 상태에서 연산이 가능하도록
ans = eval(rst.replace(' ', ''))
# 연산 결과가 0이면 정답 리스트에 추가
if ans == 0:
ans_sik.append(rst)
return
else:
n_idx = idx + 1
# 공백인 경우 숫자를 이어붙이기
dfs(n, n_idx, rst + ' ' + str(n_idx))
# +인 경우 더하기
dfs(n, n_idx, rst + '+' + str(n_idx))
# -인 경우 빼기
dfs(n, n_idx, rst + '-' + str(n_idx))
T = int(input())
for _ in range(T):
N = int(input())
ans_sik = []
dfs(N, 1, '1')
for a in ans_sik:
print(a)
print()
i think it is 3^n time cuz there are 3 options
n space cuz it is just dict