๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์‹คํŒจ์œจ (Python)

1. ๋ฌธ์ œ ์„ค๋ช…

๋ฌธ์ œ ๋งํฌ

  • ์ž…๋ ฅ : 5, [2, 1, 2, 6, 2, 4, 3, 3]
  • ์ถœ๋ ฅ : [3,4,2,1,5] ์‹คํŒจ์œจ์ด ๋†’์€ ์Šคํ…Œ์ด์ง€์ˆœ์œผ๋กœ ์ถœ๋ ฅ

2. ์ฝ”๋“œ

solution1.py

def fail_percent(target_stage, stages):
    check = 0 #์ฒ˜์Œ ๋“ฑ์žฅํ•˜๋Š”์ง€ ํ™•์ธ
    denominator = 0 #๋ถ„๋ชจ๊ฐ’
    numerator = 0 #๋ถ„์ž๊ฐ’
    for i,number in enumerate(stages):
        if number == target_stage: #ํƒ€๊ฒŸ ์Šคํ…Œ์ด์ง€์˜ ๊ฐ’๊ณผ ๊ฐ™์€ ๊ฐ’์ด ๋‚˜์˜ค๊ณ 
            if check==0: #์ด์ „์— ๋‚˜์˜จ์ ์ด ์—†๋‹ค๋ฉด
                denominator = len(stages[i:]) #ํ•ด๋‹น ๊ฐ’ ์ดํ›„๋กœ ๋ช‡ ๊ฐœ๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธ
                check+=1
                numerator+=1
            else:
                numerator+=1

    if denominator !=0:
        return count / denominator
    else:
        return 0

def solution(N, stages):
    answer = []
    stages.sort() #์Šคํ…Œ์ด์ง€๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ
    storage = {} #๊ฐ ์Šคํ…Œ์ด์ง€๋ณ„ ์‹คํŒจ์œจ์„ ์ €์žฅํ•  ๋”•์…”๋„ˆ๋ฆฌ
    for i in range(N):
        #์Šคํ…Œ์ด์ง€(key)๋ณ„ ์‹คํŒจ์œจ(value)์„ ์ €์žฅ
        storage[i+1] = fail_percent(i+1,stages)

    #value ๊ธฐ์ค€์œผ๋กœ key๋ฅผ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ
    answer = sorted(storage, key= lambda x : storage[x], reverse=True)
    return answer

3. ํšŒ๊ณ 

  • value ๊ธฐ์ค€์œผ๋กœ key๋ฅผ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ์ฐพ์•„๋ดค๋‹ค.
  • ๋ฐ”๋กœ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ์–ด ๋‚˜์ค‘์—๋„ ์‚ฌ์šฉํ•˜๊ธฐ ์œ ์šฉํ•  ๊ฒƒ ๊ฐ™๋‹ค.