알고리즘 공부 2일차

김서영·2023년 12월 12일
0

알고리즘

목록 보기
2/25

1. 프로그래머스 - 신규 아이디 추천

def solution(new_id):
    answer = ''
    id_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '_', '.']
    new_id = new_id.lower()
    for i in new_id:
        if i in id_list:
            answer += i
    while True:
        if '..' in answer:
            answer = answer.replace('..', '.')
        else:
            break
    if len(answer) > 0 and answer[0] == '.':
        answer = answer[1:]
    if len(answer) > 0 and answer[-1] == '.':
        answer = answer[:-1]
    if answer == '':
        answer = 'a'
    if len(answer) >= 16:
        answer = answer[:15]
        if answer[-1] == '.':
            answer = answer[:-1]
    if len(answer) <= 2:
        while len(answer) != 3:
            answer += answer[-1]
    return answer

2. 프로그래머스 - 햄버거 만들기

def solution(ingredient):
    lst = []
    answer = 0
    for i in ingredient:
        lst.append(i)
        if lst[-4:] == [1, 2, 3, 1]:
            answer += 1
            for _ in range(4):
                lst.pop()
    return answer

3. 프로그래머스 - 둘만의 암호

def solution(s, skip, index):
    answer = ''
    alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    for i in skip:
        alpha.remove(i)
    for i in s:
        if alpha.index(i)+index < len(alpha):
            answer += alpha[alpha.index(i)+index]
        else:
            answer += alpha[(alpha.index(i)+index) % len(alpha)]
    return answer

4. 프로그래머스 - 완주하지 못한 선수

def solution(participant, completion):
    participant.sort()
    completion.sort()
    
    for i, j in zip(participant, completion):
        if i!=j:
            return i
    
    return participant[-1]

collections.Counter

컨테이너안의 데이터를 편리하고 빠르게 개수를 세도록 지원하는 계수기 도구

import collections
ex_list = ['kim', 'kim', 'park', 'choi', 'kim', 'kim', 'kim', 'choi', 'park', 'choi']
ex_counter = collections.Counter(ex_list)
print(ex_counter)
Counter({'kim': 5, 'choi': 3, 'park': 2})

이걸 활용해서 위의 문제를 풀면

import collections

def solution(participant, completion):
    answer = collections.Counter(participant) - collections.Counter(completion)
    return list(answer.keys())[0]

print(solution(["leo", "kiki", "eden"], ["eden", "kiki"]))

이렇게도 가능하다고 한다!! 신기👍👍

profile
개발과 지식의 성장을 즐기는 개발자

0개의 댓글