본문 바로가기
Algorithm

[프로그래머스] 서울에서 김서방 찾기 (JS, Python)

by YGSEO 2021. 2. 4.
728x90

Javascript

Python에서 format와 유사한 기능을 하는 메서드를 찾다가 발견한 것

 

"~" 키와 같이 있는 "`" 따옴표 비슷하게 생긴 얘는 grave accent 혹은 backtick이라고 불린다.

언어에서는 프랑스어나 포르투갈어 등에서 사용하는 accent 기호.

Template literals (Template strings)

Template literals are enclosed by the backtick (` `) (grave accent) character instead of double or single quotes.

Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}). The expressions in the placeholders and the text between the backticks (` `) get passed to a function.

The default function just concatenates the parts into a single string. If there is an expression preceding the template literal (tag here), this is called a tagged template. In that case, the tag expression (usually a function) gets called with the template literal, which you can then manipulate before outputting.

To escape a backtick in a template literal, put a backslash (\) before the backtick.

 

function solution(seoul) {
    let idx = 0
    for (let i=0;i<seoul.length;i++) {
        if (seoul[i] == 'Kim') {
          idx = i
        } else continue
    };
    // let idx = 0
    var answer = `김서방은 ${idx}에 있다`;
    return answer;
}

다른풀이 : indexOf 사용해서 index 찾기

function findKim(seoul){
  var idx = seoul.indexOf('Kim');
  return "김서방은 " + idx + "에 있다";
}

indexOf는 return으로 first index else -1


Python

def solution(seoul):

    return "김서방은 {}에 있다".format(seoul.index('Kim'))

리스트의 index 메서드로 해결

But ! Caveats are followed. link

list.index(x[, start[, end]])

Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.

3가지 caveats 즉 주의 사항이 존재하는데,

- 리스트에서 찾고자 하는 item이 없다면 ValueError가 발생한다.

- Time complexity, 즉 start idx부터 끝까지 찾기 때문에 리스트가 길어질 경우 많은 시간 소요.

- 리스트 안에서 찾고자 하는 item의 첫 번째만 return. not all indices

 

728x90

댓글