[Python] 프로그래머스 / 알고리즘 고득점 Kit / hash 정리 / items()

2024. 3. 20. 08:44Coding Test/Python

https://youtu.be/zFL29ydL9D8?si=jZqGGUM1UbGhSCCk

 

 

Hash를 써야하는 이유와 간단히 잘 설명해준 동영상!

 

String을 기준으로 정보를 기록하고 관리하려면 단순배열을 사용할 수 없으니 hash를 활용해야 한다.

 

1. hash는 전화번호부와 같다.

ex) "김철수" : 01012345678

2. 대부분 그 key가 string이다

3. put / get / getOrDefault  -> 이 3가지 함수를 알면 hash 문제는 대부분 풀 수 있다고 함.

 

프로그래머스 hash 문제들 : 


https://school.programmers.co.kr/learn/courses/30/lessons/1845

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

def solution(nums):
    data = dict.fromkeys(set(nums), 0)
    for num in nums:
        data[num] += 1
        
    answer = min(len(data), len(nums)//2)
       
    return answer

 


https://school.programmers.co.kr/learn/courses/30/lessons/42576

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

def solution(participant, completion):
    name_part = dict.fromkeys(set(participant), 0)
    for name in participant:
        name_part[name] += 1
        
    for name in completion:
        name_part[name] -= 1
        
    for name, count in name_part.items():
        if count>0:
            return name

 

 


 

https://school.programmers.co.kr/learn/courses/30/lessons/42577

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

def solution(phone_book):
    answer = True
    phone_book.sort()
    phone_num = dict.fromkeys(phone_book, 1)
    
    for numbers in phone_num:
        num = ""
        for number in numbers:
            num += number
            if num in phone_num and num != numbers:
                return False
    return True

 

코드에서 num에 "119"가 들어갔을 때, phone_num에도 "119"가 존재하고, 현재 전화번호인 "1195524421"과 다르기 때문에 False를 반환. 이는 "1195524421"이 "119"의 접두사이기 때문.

 


https://school.programmers.co.kr/learn/courses/30/lessons/42578

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

def solution(clothes):
    answer = 1
    wear = {}
    
    for item in clothes:
        kind = item[1]
        
        if kind in wear:
            wear[kind] += 1
        else:
            wear[kind] = 1
    
    for kind, count in wear.items():
        answer *= (count+1)
    
    return answer-1

 


https://school.programmers.co.kr/learn/courses/30/lessons/42579

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

def solution(genres, plays):
    answer = []
    album = {}
    
    #{"clssic":{"3":800, "0":500, "2":150}}
    for i in range(len(genres)):
        if genres[i] in album:
            if i in album[genres[i]]:
                album[genres[i]][i] += plays[i]
            else:
                album[genres[i]][i] = plays[i]
        else:
            album[genres[i]] = {i:plays[i]}
        
    
    return album

 

쓰일 줄 알았지만 안 쓰이는 코드...하지만 필요할지도 몰라서 

 

def solution(genres, plays):
    answer = []
    dic1 = {}
    dic2 = {}
    
    for idx, (genre, play) in enumerate(zip(genres, plays)):
        if genre in dic1:
            dic1[genre].append((idx, play))
        else:
            dic1[genre] = [(idx, play)]
            
        if genre in dic2:
            dic2[genre] += play
        else:
            dic2[genre] = play
    
    for (kind, volume) in sorted(dic2.items(), key=lambda x:x[1], reverse=True):
        for (idx, play) in sorted(dic1[kind], key=lambda x:x[1], reverse=True)[:2]:
            answer.append(idx)
    
    return answer

 


프로그래머스의 알고리즘 고득점 Kit의 hash문제 말고도 hash문제로 풀 수 있는/풀어야 하는 문제들:

 

https://school.programmers.co.kr/learn/courses/30/lessons/92334

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

def solution(id_list, report, k):
    answer = []
    notify_id = {} 
    notified_id = {} 
    
    for idx in report:
        notify = idx.split()[0]
        notified = idx.split()[1]
        
        if notify in notify_id:
            notify_id[notify] += 1
        else:
            notify_id[notify] = 1
            
        if notified in notified_id:
            notified_id[notified] += 1
        else:
            notified_id[notified] = 1
            
    for user in id_list:
        stop_id = dict.fromkeys(id_list, 0)
        
    if notified_id[notified]>=k:
        stop_id[notified] += 1
    if notify_id[notify]
    
    return stop_id

 

첫번째 시도....

 

def solution(id_list, report, k):
    answer = []
    
    notify_id = {}
    notified_id = {}
    
    report = list(set(report))
    
    for user in report:
        notify, notified = user.split()
        if notify in notify_id:
            notify_id[notify] +=1
        else:
            notify_id[notify] = 1
        if notified in notified_id:
            notified_id[notified] +=1
        else:
            notified_id[notified] = 1
            
    result = {"dict1": notify_id, "dict2":notified_id}
    
    for _ in id_list:
        mail = dict.fromkeys(id_list, 0)
    
    for notified, count in notified_id.items():
        if count >= k:
            for notify, report_count in notify_id.items():
                if notify + " " + notified in report:
                    mail[notify] += 1
            
    return list(mail.values())

 

시간초과로 실패....

 


https://school.programmers.co.kr/learn/courses/30/lessons/176963?language=python3

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

def solution(name, yearning, photo):
    answer = []
    scores = {}
    result = 0
    
    for i, j in zip(name, yearning):
        scores[i] = j
        
    for photos in photo:
        result = 0
        for p in range(len(photos)):
            for k, score in scores.items():
                if k==photos[p]:
                    result += score
        answer.append(result)
    return answer