분류 전체보기

    [백준]1427번 소트인사이드 - 정렬

    a = input() print(''.join(sorted(a, reverse=True))) 코드 설명 문자열로 입력을 받은 후 내장 정렬 함수인 sort를 통하여 내림차순으로 정렬한다. 리스트로 결과가 반환되기 때문에, join 함수를 통하여 하나의 문자열로 만들어서 출력하여준다. Point : 문자열도 내장정렬 함수로 정렬이 가능하고, 리스트의 형태를 다시 join 함수를 이용해 바꿔주는 것이 중요하다.

    [백준]2108번 통계학 - 정렬

    import sys from collections import Counter n = int(sys.stdin.readline()) a = [] for i in range(n): a.append(int(sys.stdin.readline())) a.sort() def avg(): print(round(sum(a)/len(a))) def center(): print(a[(len(a)//2)]) def max(): result = Counter(a) result_ = result.most_common() if len(a) > 1: if result_[0][1] == result_[1][1]: print(result_[1][0]) else: print(result_[0][0]) else: print(result_..

    [백준]10989번 수 정렬하기 3 - 정렬

    import sys n = int(sys.stdin.readline()) a = [0]*10001 for i in range(n): index = int(sys.stdin.readline()) a[index] += 1 for j in range(10001): if a[j] != 0: for x in range(a[j]): print(j) 코드 설명 input() 함수 대신 sys.stdin.readline() 함수를 이용함으로써 입력 받는 속도를 빠르게 처리할 수 있다. 먼저 수의 한계가 10000이므로 10001 크기의 리스트를 0으로 초기화 하여 준다. 반복문을 돌면서 입력받는 수를 인덱스로 하여 1씩 증가시켜 해당 수가 몇번 등장했는지 세준다. 그 후 배열을 돌면서 0번 등장한 수는 제외하고 나머지..

    [백준]2750번, 2751번 수 정렬하기 1, 2 - 정렬

    n = int(input()) a = [] for i in range(n): a.append(int(input())) a.sort() for j in range(len(a)): print(a[j]) n = int(input()) a = [] for i in range(n): a.append(int(input())) a.sort() for j in range(len(a)): print(a[j]) Point : 위 두문제의 경우 파이썬의 내장 정렬 함수인 sort()를 사용하면 쉽게 풀 수 있다.

    [프로그래머스]다리를 지나는 트럭-스택/큐

    def solution(bridge_length, weight, truck_weights): queue = [0] * bridge_length cnt = 0 while queue: cnt += 1 queue.pop(0) if truck_weights: if sum(queue) + truck_weights[0]

    [프로그래머스]기능 개발-스택/큐

    import math def solution(progresses, speeds): answer = [] while progresses: for i in range(len(progresses)): progresses[i] += speeds[i] cnt = 0 while progresses and progresses[0] >= 100 : progresses.pop(0) speeds.pop(0) cnt += 1 if cnt > 0 : answer.append(cnt) return answer 코드 설명 progresses 리스트에 값이 있는 동안 반복문을 수행한다. 먼저 progresses 리스트와 speeds 리스트를 더해서 1일이 지난 후의 작업량을 구해준다. 그 후 progresses 리스트에 값이 존재..

    [프로그래머스]주식가격-스택/큐

    def solution(prices): answer = [] for i in range(len(prices)): cnt = 0 for j in range(i+1, len(prices)): cnt += 1 if prices[i] > prices[j]: # 가격이 떨어짐을 의미 break answer.append(cnt) return answer 코드 설명 첫번째 반복문에서는 prices 리스트의 길이만큼 반복한다. 카운트를 위한 변수를 0으로 초기화 한다. 다음 반복문은 i+1 부터 시작하여 prices 리스트의 길이만큼 반복한다. 만약 prices[i] > prices[j] (즉, 가격이 떨어졌다면) break를 통해 두번째 반복문을 탈출한다. 그렇지 않다면 (즉, 가격이 떨어진 적이 없다면) 반복문을 ..

    [프로그래머스]H-Index-정렬

    def solution(citations): citations.sort() for i in range(len(citations)): if citations[i] >= len(citations)-i: return len(citations)-i return 0 코드 설명 먼저 citations 리스트를 정렬을 해줌으로써 인용된 횟수를 오름차순으로 정렬합니다. 그 후 citations 리스트의 길이만큼 반복문을 수행하고 만약 논문에 인용된 횟수가 논문의 수 - i 라면 논문의수 - i 를 return 합니다. 만족하지 못한다면 0을 리턴하여 줍니다. Point : 오름차순 정렬을 통하여 가장 적은 인용 횟수를 맨 앞으로 배치하여 줍니다. 이를 통하여 불필요한 반복문을 없앨 수 있습니다. 이 문제에서 가장 중요..

    [프로그래머스]가장 큰 수-정렬

    def solution(numbers): numbers = list(map(str, numbers)) # x*3을 기준으로 하여 정렬한다. # 기준을 삼는 것이기 때문에 실제로 정렬되는 데이터는 *3이 된 것이 아니다. numbers.sort(key = lambda x: x*3, reverse=True) return str(int(''.join(numbers))) 코드 설명 먼저 입력받은 numbers 리스트를 map() 함수를 통하여 전부 str 형으로 바꿔준다. map object가 되기 때문에 list() 함수를 통하여 리스트 형으로 다시 변환시켜준다. sort() 함수의 key 인자 값을 활용(key 를 기준으로 하여 리스트로 정렬함)하여 내림차순 정렬을 해준다. join 함수를 활용하여 리스트를..

    [프로그래머스]K번째수-정렬

    def solution(array, commands): answer = [] for i in commands: temp = array[i[0]-1:i[1]] temp.sort() answer.append(temp[i[2]-1]) return answer 코드 설명 commands 리스트 안에서 for 반복문을 돌려 commands[i][0:2] 에 해당하는 원소들을 리스트로서 접근하여 temp 리스트에 (i ~ j 번째를 자른 결과) 넣어준다. 그 후 정렬을 하고 정렬된 리스트의 i[2]-1 인덱스(k를 의미함)에 접근하여 answer 리스트에 원소를 추가하여 준다. Point : 파이썬에는 내장 정렬 함수인 sort(), sorted()가 존재하기에 이를 활용하면 정렬을 위한 코드를 작성하지 않아도 된..