프로그래머스/알고리즘 고득점 Kit 11

[프로그래머스] [스택/큐] Lv.2 /주식가격 (파이썬/Python)

1. 문제 설명2. 코드 def solution(prices):     answer = []     for i in range(len(prices)):         count = 0         for j in range(i+1,len(prices)):             if prices[i]                 count += 1             else:                 count += 1                 break         answer.append(count)     return answer3. 풀이 과정초 단위를 기록할 answer를 빈 리스트로 초기화한다.prices의 길이의 범위를 i로 받아서 반복한다.횟수 count를 0으로 초기화한다.이후..

[프로그래머스] [스택/큐] Lv.2 /다리를 지나는 트럭 (파이썬/Python)

1. 문제 설명2. 코드 from collections import dequedef solution(priorities, location):    queue = deque([(p, idx) for idx, p in enumerate(priorities)])    count = 0        while queue:        current = queue.popleft()        if any(x[0] > current[0] for x in queue):            queue.append(current)        else:            count += 1            if current[1] == location:                return count3. 풀이 ..

[프로그래머스] [스택/큐] Lv.2 /프로세스 (파이썬/Python)

1. 문제 설명2. 코드 from collections import deque def solution(priorities, location):     queue = deque([(p, idx) for idx, p in enumerate(priorities)])     count = 0          while queue:         current = queue.popleft()         if any(x[0] > current[0] for x in queue):             queue.append(current)         else:             count += 1             if current[1] == location:                 return..

[프로그래머스] [스택/큐] Lv.2 /올바른 괄호 (파이썬/Python)

1. 문제 설명2. 코드 def solution(s):     stack=[]     for char in s:         if char == '(':             stack.append(char)         elif char == ')':             if not stack:                 return False             stack.pop()     return len(stack) == 03. 풀이 과정stack을 빈 리스트로 초기화한다.s의 문자를 char로 받는다.char이 '('이면 append()로 char를 stack에 추가한다.char이 ')'일 때 stack이 비어 있으면 False를 반환하고 아니면 pop()으로 stack 안에 있는 '..

[프로그래머스] [스택/큐] Lv.2 /기능개발 (파이썬/Python)

1. 문제 설명2. 코드 def solution(progresses, speeds):     answer = []     days_left = []          for p, s in zip(progresses, speeds):         import math         days = math.ceil((100 - p) / s)         days_left.append(days)          count = 1     max_days = days_left[0]           for i in range(1, len(days_left)):         if days_left[i] > max_days:             answer.append(count)              coun..

[프로그래머스] [스택/큐] Lv.1 /같은 숫자는 싫어 (파이썬/Python)

1. 문제 설명2. 풀이 과정 answer를 arr의 첫 문자를 저장한 리스트로 선언한다.인덱스의 범위를 1부터 arr의 길이로 하여 받는다.arr의 바로 전 문자랑 같지 않으면 answer에 append()로 추가한다.for문을 빠져 나오면 answer를 반환한다. 3. 코드def solution(arr):     answer=[arr[0]]     for i in range(1, len(arr)):         if arr[i] != arr[i-1]:             answer.append(arr[i])    return answer4. 추천 코드def solution(arr):     stack = []          for num in arr:        if not stack or ..

[프로그래머스] [해시] Lv.3 /베스트앨범 (파이썬/Python)

1. 문제 설명2. 풀이 과정 장르별로 노래 정보를 저장하기 위해 genre_dict을 딕셔너리로 초기화하고 genres와 plays를 zip()으로 묶어 enumerate()하면 i와 genre,play를 같이 저장할 수 있다.genre가 genre_dict에 없으면 빈 리스트 []를 만들고 genre_dict[genre]에 i와 play를 저장한다.장르별 노래 정보를 저장했으므로 총 재생 횟수를 계산해야 한다.genre_dict의 genre와 songs를 items()로 불러와 songs에서 (고유번호, 재생횟수)형태로 무시 변수 _와 함께 play을 불러와 play의 합 sum()을 구한다.genre_total 변수에 {genre: 총재생횟수}를 저장한다.장르별로 총 재생횟수를 내림차순 정렬을 해야..

[프로그래머스] [해시] Lv.2 /의상 (파이썬/Python)

1. 문제 설명2. 풀이 과정 의상 종류별로 이름을 저장하는 딕셔너리 clothes_dict을 생성한다.각 의상 종류별로 이름을 저장하기 위해 for문으로 clothes의 각 리스트를 불러와 값을 name, kind에 저장한다.if문으로 clothes_dict에 kind 값이 없을 때 clothes_dict[kind] = [name]으로 종류와 이름을 저장한다.kind 값이 있으면 appned() 매서드로 kind에 name을 추가한다.조합 종합을 저장할 total_combinations를 1로 초기화한다.for문으로 clothes_dictd의 값values()를 count로 불러온다. (리스트 형태로 불러오게 된다.)total_combinations에 각 value의 개수를 len(count)로 구해서..

[프로그래머스] [해시] Lv.2 /전화번호 목록 (파이썬/Python)

1. 문제 설명2. 풀이 과정 phone_book을 sort()로 정렬한다.phone_book의 길이를 1을 빼서 접두사로 처음에 비교할 값을 뺀 길이를 구한다.for문으로 인덱스를 반복해서 phone_book[i+1]로 비교할 대상 다음 것부터 startswith()으로 phone_book[i]와 앞부분에서부터 비교해 같으면 False를 반환하고, 다르면 True를 반환한다.3. 코드def solution(phone_book):     phone_book.sort()     for i in range(len(phone_book)-1):         if phone_book[i+1].startswith(phone_book[i]):             return False     return True..

[프로그래머스] [해시] Lv.1 /완주하지 못한 선수(파이썬/Python)

1. 문제 설명2. 풀이 과정 collections 모듈에서 Counter 클래스를 임포트한다.Counter는 데이터의 개수를 세는 클래스다. participant의 개수와 completion의 개수를 Counter()로 participant_count와 completion_count에 각각 넣는다.name,count를 participant_count.items()로 반복해서 받은 후count가 completion_count.get(name,0)로 완주자 이름 중 해당 이름 카운트보다 participant_count가 클 때(동명이인)는 조건을 만족하고  completion_count와 participant_count가 같은 경우는 completion_count가 0이 되므로 조건을 만족한다. Count..