RuntimeError

1. RuntimeError: dictionary changed size during iteration

๋ฐ˜๋ชฉ๋ฌธ์•ˆ์—์„œ dic๋‚˜ set์˜ ์‚ฌ์ด์ฆˆ๊ฐ€ ๋ฐ”๋€Œ๋ฉด ๋ฐœ์ƒํ•˜๋Š” ์—๋Ÿฌ์ด๋‹ค.

๋‹ค๋งŒ, break ํ•˜์—ฌ for๋ฌธ์—์„œ ๋‚˜๊ฐˆ ๊ฒฝ์šฐ๋Š” ๋ฐœ์ƒํ•˜์ง€ ์•Š๋Š”๋‹ค.

def solution(number, k):
    n = len(number)- k
    answer = ''
    limit = -1
    dic = {}
    for i, j in enumerate(number):
        dic[i] = int(j)

    dic = dict(sorted(dic.items(), key=lambda x:x[1], reverse=True))

    while n != 0:
        for key, value in dic.items():
            if key < limit:
                del dic[key]        # ์—๋Ÿฌ ๋ฐœ์ƒ
                continue
                
            if (len(number)-key >= n):
                answer += str(value)
                limit = key
                n -= 1
                
                del dic[key]        # ์—๋Ÿฌ ๋ฐœ์ƒํ•˜์ง€ ์•Š์Œ
                break
                
    return answer

Categories:

Updated:

Leave a comment