์ตœ๊ทผ ํŒŒ์ด์ฌ PS ํ•˜๋ฉด์„œ ๋ฐฐ์šด ๊ฒƒ

2022. 5. 5. 22:52ใ†Backend/๐Ÿ Python

dict ์˜ fromkeys() ๋ฉ”์„œ๋“œ

- ๋”•์…”๋„ˆ๋ฆฌ ์ƒ์„ฑ ์‹œ, ์ด๋ฏธ key ๊ฐ’์ด ์ •ํ•ด์ง„ ๊ฒฝ์šฐ ํŽธ๋ฆฌํ•˜๊ฒŒ ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.

- seq : ๋”•์…”๋„ˆ๋ฆฌ์˜ key ๊ฐ’์ด ๋  iterable ๋กœ, ์ฆ‰ dictionary ์˜ key ๋ชฉ๋ก์ด๋‹ค.

- value : seq ์˜ ๊ฐ key ์— ํ• ๋‹น๋  value (๊ฐ’) ์˜๋ฏธ

# ์ •์˜
@staticmethod # known case
def fromkeys(*args, **kwargs): # real signature unknown
    """ Create a new dictionary with keys from iterable and values set to value. """
    pass
    
    
# ์‚ฌ์šฉ๋ฒ•    
value = 0
seq = [1, 2, 3]

dictionary = dict.fromkeys(seq, value)
>>> {1 : 0, 2 : 0, 3 : 0}

- ๋ฐฑ์ค€์˜ ๊ฒฝ์šฐ input ๊ฐ’์œผ๋กœ ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ๋งŒ๋“ค ๋•Œ๊ฐ€ ์žˆ๋Š”๋ฐ, ์ด๋Ÿด ๊ฒฝ์šฐ seq ์ž๋ฆฌ์— input() ์„ ๋„ฃ์–ด์ฃผ๋ฉด ์†์‰ฝ๊ฒŒ ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.

 

bisect.bisect_left(), bisect_right()

// ์ •์˜
bisect_left(a, x, lo=0, hi=len(a), *, key=None)


// ์‚ฌ์šฉ์‹œ
find = bisect_left(list, value)

list ๋ผ๋Š” ์ •๋ ฌ๋œ ๋ฐฐ์—ด์—, ์ด๋ถ„ํƒ์ƒ‰์œผ๋กœ value ๋ฅผ ์‚ฝ์ž…ํ•  ์ธ๋ฑ์Šค๋ฅผ ๋ฐ˜ํ™˜(= find)ํ•œ๋‹ค.

left ๊ฐ€ ์ ‘๋ฏธ์‚ฌ๋กœ ๋ถ™์€ ์ด์œ ๋Š” ์™ผ์ชฝ ์ธ๋ฑ์Šค๋ฅผ ๊ตฌํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

from bisect import bisect_left, bisect_right

arr = [0, 1, 2, 3, 4]
value = 2

left = bisect_left(arr, value)
right = bisect_right(arr, value)

"""

left : 2
right : 3

"""

์ด๋ถ„ํƒ์ƒ‰์œผ๋กœ arr ์—์„œ 2 ๋ฅผ ์ฐพ์œผ๋ฉด, 2๋ฒˆ์งธ ์ธ๋ฑ์Šค์—์„œ ์ฐพ์„ ์ˆ˜ ์žˆ๋‹ค. 

bisect_left : ํ•ด๋‹น ๊ฐ’(=2) ์ด ์ด๋ฏธ arr ์— ์žˆ๋Š” ๊ฒฝ์šฐ, value ์˜ ์‚ฝ์ž… ์œ„์น˜๋Š” ๊ธฐ์กด ํ•ญ๋ชฉ์˜ ์™ผ์ชฝ์ด ๋œ๋‹ค.

bisect_right : ํ•ด๋‹น ๊ฐ’์˜ ์˜ค๋ฅธ์ชฝ ์ธ๋ฑ์Šค์— ์‚ฝ์ž…ํ•˜๋ฏ€๋กœ, 3๋ฒˆ์งธ ์ธ๋ฑ์Šค๊ฐ€ find ๋กœ ๋ฐ˜ํ™˜ ๋œ๋‹ค.