Light Blue Pointer
본문 바로가기
Coding Test

[프로그래머스][Lv.1]추억 점수

by Craft Fiend 2023. 10. 23.

문제 주소

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

 

프로그래머스

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

programmers.co.kr

문제 설명

문제 설명

사진들을 보며 추억에 젖어 있던 루는 사진별로 추억 점수를 매길려고 합니다.

사진 속에 나오는 인물의 그리움 점수를 모두 합산한 값이 해당 사진의 추억 점수가 됩니다.

예를 들어 사진 속 인물의 이름이 ["may", "kein", "kain"]이고 각 인물의 그리움 점수가 [5점, 10점, 1점]일 때 해당 사진의 추억 점수는 16(5 + 10 + 1)점이 됩니다.

다른 사진 속 인물의 이름이 ["kali", "mari", "don", "tony"]이고 ["kali", "mari", "don"]의 그리움 점수가 각각 [11점, 1점, 55점]]이고, "tony"는 그리움 점수가 없을 때, 이 사진의 추억 점수는 3명의 그리움 점수를 합한 67(11 + 1 + 55)점입니다.

그리워하는 사람의 이름을 담은 문자열 배열 name,

각 사람별 그리움 점수를 담은 정수 배열 yearning,

각 사진에 찍힌 인물의 이름을 담은 이차원 문자열 배열 photo가 매개변수로 주어질 때,

사진들의 추억 점수를 photo에 주어진 순서대로 배열에 담아 return하는 solution 함수를 완성해주세요.


제한사항

  • 3 ≤ name의 길이 = yearning의 길이≤ 100
    • 3 ≤ name의 원소의 길이 ≤ 7
    • name의 원소들은 알파벳 소문자로만 이루어져 있습니다.
    • name에는 중복된 값이 들어가지 않습니다.
    • 1 ≤ yearning[i] ≤ 100
    • yearning[i]는 i번째 사람의 그리움 점수입니다.
  • 3 ≤ photo의 길이 ≤ 100
    • 1 ≤ photo[i]의 길이 ≤ 100
    • 3 ≤ photo[i]의 원소(문자열)의 길이 ≤ 7
    • photo[i]의 원소들은 알파벳 소문자로만 이루어져 있습니다.
    • photo[i]의 원소들은 중복된 값이 들어가지 않습니다.

입출력 예

name yearning photo result

["may", "kein", "kain", "radi"] [5, 10, 1, 3] [["may", "kein", "kain", "radi"],["may", "kein", "brin", "deny"], ["kon", "kain", "may", "coni"]] [19, 15, 6]
["kali", "mari", "don"] [11, 1, 55] [["kali", "mari", "don"], ["pony", "tom", "teddy"], ["con", "mona", "don"]] [67, 0, 55]
["may", "kein", "kain", "radi"] [5, 10, 1, 3] [["may"],["kein", "deny", "may"], ["kon", "coni"]] [5, 15, 0]

입출력 예 설명

입출력 예 #1

첫 번째 사진 속 "may", "kein", "kain", "radi"의 그리움 점수를 합치면 19(5 + 10 + 1 + 3)점 입니다.

두 번째 사진 속 그리워하는 사람들인 "may"와 "kein"의 그리움 점수를 합치면 15(5 + 10)점입니다.

세 번째 사진의 경우 "kain"과 "may"만 그리워하므로 둘의 그리움 점수를 합한 6(1 + 5)점이 사진의 추억 점수입니다.

따라서 [19, 15, 6]을 반환합니다.

입출력 예 #2

첫 번째 사진 속 그리워하는 사람들인 "kali", "mari", "don"의 그리움 점수를 합치면 67(11 + 1 + 55)점입니다. 두 번째 사진 속엔 그리워하는 인물이 없으므로 0점입니다. 세 번째 사진 속 그리워하는 사람은 "don"만 있으므로 55점입니다. 따라서 [67, 0, 55]를 반환합니다.

입출력 예 #3

설명 생략

제출 코드

1. Python

def solution(name, yearning, photo):
    
    
    thisdict = {}
    for i in range(len(name)) :
        thisdict[name[i]] = yearning[i]
        
        
    answer = []
    
    for x in photo:
        total = 0;
        for y in x:
            if y in thisdict:
                total = total + thisdict[y]
        answer.append(total)

    return answer

2. Java

import java.util.Map;
import java.util.HashMap;
class Solution {
    public int[] solution(String[] name, int[] yearning, String[][] photo) {
        
        Map<String, Integer> nameToYearning = new HashMap<>();
        
        for(int i = 0; i< name.length; i++){
            nameToYearning.put(name[i],yearning[i]);
        }
        
        int[] answer = new int[photo.length];
        
        for(int i = 0; i<photo.length; i++){
            int total = 0;
            for(int j = 0; j<photo[i].length;j++){
                if(null != nameToYearning.get(photo[i][j])){
                    total = total + nameToYearning.get(photo[i][j]);
                }
            answer[i]=total;
            }
        }
        return answer;
    }
}

 

Python 풀이 과정

저번에 딕셔너리 썼던게 생각나서 또 딕셔너리 쓰기로 함

⭐(복습)파이썬 배열 초기화

arr = [0 for i in range(rows)]

⭐파이썬 배열(리스트) 원소 추가

⚠️ index를 모르는 상태로 for문 돌리면서(i,j 말고 x,y로) answer에 저장하려니 append써야 했음

arr.append(value)
arr.insert(index,value)
def solution(name, yearning, photo):
    
    
    thisdict = {}
    for i in range(len(name)) :
        thisdict[name[i]] = yearning[i]
        
        
    answer = [0 for i in range(len(photo))]
    
    for x in photo:
        total = 0;
        for y in x:
            total = total + thisdict[x]
        answer.append(total)

    return answer

TypeError: unhashable type: 'list'

귀찮아서 if y in thisdict: 안 해줘서 저런 에러가 났는데 key관련 에러가 안 떠서 이유가 그거인지 모르고 그냥 인덱스로 다시 해봄

def solution(name, yearning, photo):
    
    
    thisdict = {}
    for i in range(len(name)) :
        thisdict[name[i]] = yearning[i]
        
        
    answer = []
    
    for x in photo:
        total = 0;
        for y in x:
            if y in thisdict:
                total = total + thisdict[y]
        answer.append(total)

    return answer

KeyError: 'pony'

Q. if y in thisdict: 안 해줘서 저런 에러가 났는데 x,y로 풀 때랑 i,j로 풀 때랑 에러가 다름 왜지?

⭐(복습) 키값이 존재하는지 보기

if "model" in thisdict:
  print("Yes, 'model' is one of the keys in the thisdict dictionary")
def solution(name, yearning, photo):
    
    
    thisdict = {}
    for i in range(len(name)) :
        thisdict[name[i]] = yearning[i]
        
        
    answer = []
    
    for x in photo:
        total = 0;
        for y in x:
            if y in thisdict:
                total = total + thisdict[y]
        answer.append(total)

    return answer

Python 다른사람의 코드

def solution(name, yearning, photo):
    dictionary = dict(zip(name,yearning))
    scores = []
    for pt in photo:
        score = 0
        for p in pt:
            if p in dictionary:
                score += dictionary[p]
        scores.append(score)
    return scores

내가 처음에 했던 거랑 비슷한데 dictionary 안에 있는지 체크를 안 해서 저 에러가 떴었나보다

⭐그리고 딕셔너리를 획기적인 방법으로 넣어버림

dictionary = dict(zip(name,yearning))

다른 사람들 풀이도 다 비슷하게 딕셔너리로 하는 거 같다

 

Java 풀이과정

⭐Java Map에서 get()을 호출해서 찾을때 Map에 키가 없는 경우에 null을 return한다

class Solution {
    public int[] solution(String[] name, int[] yearning, String[][] photo) {
        
        Map<String, Integer> nameToYearning = new HashMap<>();
        
        for(int i = 0; i< name.length; i++){
            nameToYearning.put(name[i],yearning[i]);
        }
        
        int[] answer = {};
        
        for(int i = 0; i<photo.length; i++){
            int total = 0;
            for(int j = 0; j<photo[i].length;j++){
                if(null != nameToYearning.get(photo[i][j])){
                    total = total + nameToYearning.get(photo[i][j]);
                }
            answer[i]=total;
            }
        }
        return answer;
    }
}

/Solution.java:4: error: cannot find symbol

Map<String, Integer> nameToYearning = new HashMap<>();

^

symbol: class Map

location: class Solution

/Solution.java:4: error: cannot find symbol

import를 안 해줘서 저러나 싶어서 import를 해줌

import java.util.Map;
class Solution {
    public int[] solution(String[] name, int[] yearning, String[][] photo) {
        
        Map<String, Integer> nameToYearning = new HashMap<>();
        
        for(int i = 0; i< name.length; i++){
            nameToYearning.put(name[i],yearning[i]);
        }
        
        int[] answer = {};
        
        for(int i = 0; i<photo.length; i++){
            int total = 0;
            for(int j = 0; j<photo[i].length;j++){
                if(null != nameToYearning.get(photo[i][j])){
                    total = total + nameToYearning.get(photo[i][j]);
                }
            answer[i]=total;
            }
        }
        return answer;
    }
}

/Solution.java:5: error: cannot find symbol

Map<String, Integer> nameToYearning = new HashMap<>();

                                                                         **^**

symbol: class HashMap

location: class Solution

1 error

그건 해결되었고 다른 import 문제가 발생

또 import해오니 해결되었고 다른 문제가 발생

import java.util.Map;
import java.util.HashMap;
class Solution {
    public int[] solution(String[] name, int[] yearning, String[][] photo) {
        
        Map<String, Integer> nameToYearning = new HashMap<>();
        
        for(int i = 0; i< name.length; i++){
            nameToYearning.put(name[i],yearning[i]);
        }
        
        int[] answer = {};
        
        for(int i = 0; i<photo.length; i++){
            int total = 0;
            for(int j = 0; j<photo[i].length;j++){
                if(null != nameToYearning.get(photo[i][j])){
                    total = total + nameToYearning.get(photo[i][j]);
                }
            answer[i]=total;
            }
        }
        return answer;
    }
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

at Solution.solution(Unknown Source)

at SolutionTest.lambda$main$0(Unknown Source)

at SolutionTest$SolutionRunner.run(Unknown Source)

at SolutionTest.main(Unknown Source)

오 지금 보니 int [] answer를 생성 안 한 채로 {};

이렇게 해두고 쓰고 있었음

import java.util.Map;
import java.util.HashMap;
class Solution {
    public int[] solution(String[] name, int[] yearning, String[][] photo) {
        
        Map<String, Integer> nameToYearning = new HashMap<>();
        
        for(int i = 0; i< name.length; i++){
            nameToYearning.put(name[i],yearning[i]);
        }
        
        int[] answer = new int[photo.length];
        
        for(int i = 0; i<photo.length; i++){
            int total = 0;
            for(int j = 0; j<photo[i].length;j++){
                if(null != nameToYearning.get(photo[i][j])){
                    total = total + nameToYearning.get(photo[i][j]);
                }
            answer[i]=total;
            }
        }
        return answer;
    }
}

통과했다!

Java 다른 사람의 풀이

import java.util.*;
class Solution {
    public int[] solution(String[] name, int[] yearning, String[][] photo) {
        int[] answer = new int[photo.length];
        HashMap<String,Integer> map = new LinkedHashMap<>();
        for(int i=0; i< name.length; i++){
            map.put(name[i],yearning[i]);
        }

        for(int i =0; i< photo.length;i++){
            String[] persons = photo[i];
            int score = 0;
            for(int j=0; j<persons.length; j++){
                String person = persons[j];
                if(map.containsKey(person)){
                    score+=map.get(person);
                }
            }
            answer[i]=score;
        }

        return answer;

    }
}

Q. LinkedHashMap과 HashMap의 차이점?

Insertion order을 유지하는가 아닌가. HashMap은 아무렇게나 저장하고 LinkedHashMap은 들어온 순서대로 저장한다 함

 

  • HashMap: Suitable for most use cases, offers fast O(1) performance for get and put operations, but does not maintain any order.
  • LinkedHashMap: Combines the performance of HashMap with predictable iteration order, ideal for scenarios where insertion order is important.
  • TreeMap: Maintains key-value pairs in sorted order according to their keys, making it suitable for scenarios requiring sorted access to data, though at the cost of slower O(log n) performance for get and put operations.

HashMap

HashMap is a widely used implementation of the Map interface in Java that uses a hash table to store the key-value pairs. It provides constant-time performance for basic operations like get and put, making it an efficient choice for most use cases.

Key features:

  • Fast O(1) performance for get and put operations.
  • Stores key-value pairs in no particular order.
  • Allows one null key and multiple null values.
  • Not thread-safe.

LinkedHashMap

LinkedHashMap is a subclass of HashMap that maintains the insertion order of the key-value pairs. It combines the fast performance of HashMap with predictable iteration order, making it suitable for scenarios where the order is important.

Key features:

  • Fast O(1) performance for get and put operations.
  • Maintains insertion order.
  • Allows one null key and multiple null values.
  • Not thread-safe.

TreeMap

TreeMap is a sorted map implementation that uses a Red-Black tree as the underlying data structure. It maintains key-value pairs in sorted order according to their keys, making it an ideal choice for scenarios requiring sorted access to the data.

Key features:

  • Logarithmic O(log n) performance for get and put operations.
  • Maintains keys in sorted order.
  • Does not allow null keys but permits multiple null values.
  • Not thread-safe.

 

 

⭐containsKey로 Map에 키가 있는지 찾아볼 수 있다

if(map.containsKey(person))

나처럼 null인지 비교 안 해도 됨

다른 풀이도 대충 다 비슷한 거 같다

 

 

'Coding Test' 카테고리의 다른 글

[프로그래머스][Lv.1]공원 산책  (1) 2023.10.26
[프로그래머스][Lv.0]a와 b 출력하기  (1) 2023.10.25
[프로그래머스][Lv.1]달리기 경주  (0) 2023.10.19
2-2. Add two numbers  (0) 2023.10.14
5. Longest Palindromic Substring  (0) 2023.07.20