[백준] 4779: 칸토어 집합 - 파이썬[python]

다인·2024년 10월 21일

백준

목록 보기
85/112
post-thumbnail

풀이

  • 예시를 보자마자 N일 때는 N-1일 때의 칸토어 집합의 근사에 공백을 붙이고, N-1일 때의 칸토어 집합의 근사를 붙이면 되는 것을 알았다. 그래서 재귀함수로 풀면 되겠다고 생각했다.
  • 공백은 0, 1=3^0, 3=3^2/3=3^1, 9=3^3/3=3^2, 27=3^4/2=3^3 .. 이렇게 달라졌다. 그래서 N=0일 때를 제외하고 공백은 3^(N-1)임을 알 수 있다. N=0일 때는 '-'를 반환하면 되겠다.

코드

  • 파일의 끝까지 입력받는 방법을 2가지 방법으로 풀었다. contor 함수는 똑같다.

1. readlines() 이용

import sys

def cantor(n):
    if n==0:
        return '-'
    else:
        return cantor(n-1) + ' '*(3**(n-1)) + cantor(n-1)
    
lines = sys.stdin.readlines()
for N in lines:
    print(cantor(int(N)))

2. try except 이용

import sys
input = sys.stdin.readline 

def cantor(n):
    if n==0:
        return '-'
    else:
        return cantor(n-1) + ' '*(3**(n-1)) + cantor(n-1)
    
while True:
    try:
        N = int(input())
        print(cantor(N))
    except:
        break

결과

위에가 1, 아래가 2인데 걍 똑같다.

0개의 댓글