본문 바로가기

Python

백준 7490 0 만들기

 

* itertools의 product 이용

from itertools import*
_,*l=map(int,open(0))
o=' +-' # 결합 및 +-연산자

while l:
 n,*l=l
 t=set() # 결과값을 저장해 둘 set(동일 값이 여러개 나올 수 있음으로)
 
 for e in product(o,repeat=n): # n길이의 데카르트 곱(cartesian product)
  s='1'
  for i in range(1,n):
   s+=e[i]+str(i+1) # 연산자 + 숫자
  if eval(s.replace(' ',''))==0:
   t.add(s) # 공백을 없애고 평가한 값이 0이 될 경우 결과에 추가
 
 print(*sorted(t),sep='\n') # 정렬 후 출력
 print()

 

* 브루트포스

def f(x,v):
 if x==int(n):
  if eval(v.replace(' ',''))==0and v not in t:
   print(v);t.add(v)
  return
 
 for e in' +-':
  f(x+1,v+e+str(x+1))

_,*l=open(0)
while l:
 n,*l=l
 t={0}
 f(1,'1')
 print()

 

https://www.acmicpc.net/problem/7490

'Python' 카테고리의 다른 글

bisect  (0) 2024.04.21
파이썬 리스트  (0) 2021.07.08
Python 승수 연산의 속도 (**연산자, *반복사용, pow()함수)  (0) 2021.07.04
:= 바다코끼리 연산자(the walrus operator)  (0) 2021.07.04
Asterisks (* **) in Python  (0) 2021.06.26