새소식

Algorithm/파이썬 알고리즘 문제풀이 강의

[그리디]창고 정리(인프런)

  • -

 

 

L = int(input())
room = []
for i in range(L):
    room= list(map(int,input().split())) #100이하의 값으로, 상자가 쌓인다.

M = int(input()) #높이 조정 횟수

#room.sort(reverse=True) #리스트 원소를, 내림차순으로 분류
for i in range(M): #M회의 높이 조정 시작
    #room.sort(reverse=True) #리스트 원소를, 내림차순으로 분류
    # 리스트에서 최대/최소값을 가지는 인덱스를 반환하려면 -> list.index(min(list))
    min_index = room.index(min(room))
    max_index = room.index(max(room))
    room[max_index] -=1
    room[min_index] +=1

value=room[max_index] - room[min_index]
print(value)

위에서, 

room[max_index] -=1
room[min_index] +=1 이후,  value가 실행이 안되었다. 그 이유는,,

value=room[max_index] - room[min_index]으로 코드를 변경하면, max_index와 min_index 변수가 정의되지 않았다는 오류가 발생합니다. 이는 max_index와 min_index 변수가 이전에 for 루프에서만 정의되었기 때문입니다.

즉, 전역변수가 아니기 때문에, for문 밖에서 저 값을 가져오려니까 실행이 안된 것.

 

따라서, max_index와 min_index 변수를 for 루프 안에서 정의한 후, value 변수를 루프 안에서 계산해주어야 합니다. 예를 들어, 다음과 같이 코드를 수정할 수 있습니다:

"""L = int(input())
room = []

for i in range(L):
    room= list(map(int,input().split())) #100이하의 값으로, 상자가 쌓인다.

M = int(input()) #높이 조정 횟수 

#room.sort(reverse=True) #리스트 원소를, 내림차순으로 분류
for i in range(M): #M회의 높이 조정 시작
    #room.sort(reverse=True) #리스트 원소를, 내림차순으로 분류
    # 리스트에서 최대/최소값을 가지는 인덱스를 반환하려면 -> list.index(min(list))
    min_index = room.index(min(room))
    max_index = room.index(max(room))
    room[max_index] -=1
    room[min_index] +=1
    value=max(room)-min(room) 
    
   

print(value)"""

 

 

<답>

1)

import sys
sys.stdin=open("input.txt","r")
L = int(input())
#room = []

room= list(map(int,input().split())) #100이하의 값으로, 상자가 쌓인다.

M = int(input()) #높이 조정 횟수 

for i in range(M):
    room.sort(reverse=True) #리스트 원소를, 내림차순으로 분류
    room[0] -=1
    room[L-1] +=1

value = max(room) - min(room)
print(value)

2)

import sys
sys.stdin=open("input.txt","r")
L = int(input())
#room = []

room= list(map(int,input().split())) #100이하의 값으로, 상자가 쌓인다.

M = int(input()) #높이 조정 횟수 
room.sort() #리스트 원소를, 내림차순으로 분류
for i in range(M):
   
    room[0] +=1
    room[L-1] -=1
    room.sort()


print(room[L-1]-room[0])
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.