๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
4๏ธโƒฃ Python/Python ์ •๋ฆฌ

[Python] ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ ํ’€์ด ์‹œ ํ•„์š”ํ•œ ์ฃผ์š” ํŒ (sys.setrecursionlimit(), sys.stdin.readline())

by seolhee2750 2022. 1. 30.

๋ฌธ์ œ๋ฅผ ๋งŽ์ด ํ’€์–ด๋ณด๋ฉด์„œ ๋ชฐ๋ž๋˜,,! ์‰ฝ์ง€๋งŒ ์ค‘์š”ํ•œ ํŒ๋“ค์„ ๊ฐ„๋‹จํžˆ ์ •๋ฆฌํ•ด๋ณด๊ณ  ์žˆ๋‹ค.

 

๐Ÿ“ ์žฌ๊ท€ ๊นŠ์ด ์ œํ•œ - sys.setrecursionlimit()

ํŒŒ์ด์ฌ์€ ๊ธฐ๋ณธ์œผ๋กœ ์žฌ๊ท€ ๊นŠ์ด๋ฅผ 1000์œผ๋กœ ์ œํ•œํ•œ๋‹ค.

๋”ฐ๋ผ์„œ ์žฌ๊ท€๋ฅผ ๋” ๊นŠ๊ฒŒ ๋Œ๋ฆฌ๊ธฐ ์œ„ํ•ด์„œ๋Š” ์ด ์ œํ•œ์„ ํ’€์–ด์ค˜์•ผ ํ•œ๋‹ค.

 

ํ‘ธ๋Š” ๋ฐฉ๋ฒ•์€ ๊ฐ„๋‹จํ•˜๋‹ค.

sys ๋ชจ๋“ˆ์„ importํ•˜๊ณ , setrecursionlimit ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

import sys
sys.setrecursionlimit(10000)

์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ๋ฅผ ํ’€ ๋•Œ ์ด์œ  ์—†์ด ๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ๊ฐ€ ๋‚œ๋‹ค๋ฉด ์ด๊ฒƒ์„ ์ƒ๊ฐํ•ด๋ด์•ผ ํ•  ๋“ฏ ํ•˜๋‹ค.


๐Ÿ“ ์ž…๋ ฅ - input() / sys.stdin.readline()

์ž…๋ ฅ ๋ฐ›์„ ๋‚ด์šฉ์ด ๋ณ„๋กœ ์—†๋‹ค๋ฉด input ํ•จ์ˆ˜๋กœ๋„ ์ถฉ๋ถ„ํ•˜์ง€๋งŒ,

์—ฌ๋Ÿฌ ์ค„์˜ ์ž…๋ ฅ์„ ๋งŽ์ด ๋ฐ›์•„์•ผ ํ•œ๋‹ค๋ฉด sys.stdin.readline์„ ์‚ฌ์šฉํ•ด์ฃผ๋Š” ๊ฒƒ์ด ์ข‹๋‹ค.

sys.stdin.readline์ด input๋ณด๋‹ค ์‹œ๊ฐ„๊ณผ ๋ฉ”๋ชจ๋ฆฌ ์ธก๋ฉด ๋ชจ๋‘์—์„œ ํšจ์œจ์ด ์ข‹๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

 

sys๋ฅผ importํ•˜๊ณ  ์‚ฌ์šฉํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

์•„๋ž˜์— sys.stdin.readline์˜ ์‚ฌ์šฉ ๋ฐฉ๋ฒ•์„ ์ •๋ฆฌํ–ˆ๋‹ค.

import sys

a = sys.stdin.readline()
print(a) # input: 1 / output: "1\n"

b = sys.stdin.readline().strip()
print(b) # input: 1 / output: "1"

c = int(sys.stdin.readline())
print(c) # input: 1 / output: 1

d, e = map(int, sys.stdin.readline().split())
print(d, e) # input: 1 2 / output: 1 2

f = [sys.stdin.readline().strip().split() for _ in range(2)]
print(f) # input: 1 2\n2 3 / output: [['1', '2'], ['2', '3']]

# (์•„๋ž˜์™€ ๊ฐ™์€ ํ‘œํ˜„) g = [list(map(lambda x: int(x), sys.stdin.readline().strip.split())) for _ in range(2)]
g = [list(map(int, sys.stdin.readline().split())) for _ in range(2)]
print(g) # input: 1 2\n2 3 / output: [[1, 2], [2, 3]]

๐Ÿ‘‰ [ ์ฃผ์˜ํ•  ์  ]

  • input์€ ํ•œ ์ค„์„ ์ž…๋ ฅ ๋ฐ›์€ ํ›„, ๋ฐœ์ƒํ•œ ๊ฐœํ–‰๋ฌธ์ž(\n)์„ ์ œ๊ฑฐํ•˜์—ฌ ๋ฌธ์ž์—ด๋กœ return ํ•˜๋Š” ๋ฐ˜๋ฉด,
    sys.stdin.readline์€ ๊ฐœํ–‰๋ฌธ์ž๋ฅผ ์ œ๊ฑฐํ•˜์ง€ ์•Š๊ณ  returnํ•œ๋‹ค๋Š” ํŠน์ง•์ด ์žˆ๋‹ค.
  • int๋กœ ๋ณ€ํ™˜ ์‹œ ๊ฐœํ–‰ ๋ฌธ์ž๋Š” ์ž๋™์œผ๋กœ ์‚ฌ๋ผ์ง€์ง€๋งŒ, ๊ทธ๋ ‡์ง€ ์•Š์„ ๊ฒฝ์šฐ์—๋Š” ์‹ ๊ฒฝ์จ์ค˜์•ผ ํ•˜๋Š”๋ฐ,
    strip ํ•จ์ˆ˜๋ฅผ readline ๋’ค์— ๋ถ™์—ฌ์ฃผ๋ฉด ์•ž ๋’ค์˜ ๊ฐœํ–‰ ๋ฌธ์ž๋ฅผ ์—†์• ์ค„ ์ˆ˜ ์žˆ๋‹ค.

์œ„์˜ ์ฃผ์˜ํ•  ์‚ฌํ•ญ ์™ธ์—๋Š” ๋ชจ๋‘ input ์ž๋ฆฌ์— ๋Œ€์‹  ์“ฐ๋ฉด ๋œ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋ฉด ์‰ฝ๋‹ค.

 

 

๋Œ“๊ธ€