상봉동개발자

프로그래머스 - [1차] 다트게임, 전력망을 둘로 나누기, 모음 사전 본문

코테준비

프로그래머스 - [1차] 다트게임, 전력망을 둘로 나누기, 모음 사전

상봉동개발자 2022. 10. 3. 16:15
728x90

[1차] 다트게임

  • 사이트/난이도: 프로그래머스 / 1
  • 코드
def solution(dartResult):
    answer = 0
    
    num = ''
    score = []
    for dart in dartResult:
        if dart.isnumeric():
            num += dart
        else:
            if dart in ["S", "D", "T"]:
                num = int(num)
                if dart == "S":
                    score.append(num**1)
                if dart == "D":
                    score.append(num**2)
                if dart == "T":
                    score.append(num**3)
                num = ''
            else:
                if dart == "*":
                    if len(score) >= 2:
                        score[-2] = score[-2] * 2
                    score[-1] = score[-1] * 2
                if dart == "#":
                    score[-1] = score[-1] * (-1)
        
    return sum(score)
  • 느낀점
    • 문자열 구현 문제처음에 * 이랑 # 은 이전 기록이 있어야 되서 어떻게 해야할지 고민했는데, score라는 배열에 담아 놓으면 해결 가능
    • 문제가 요구한 대로 각 케이스 나눠서 구현하면 되는문제

전력망을 둘로 나누기

  • 사이트/난이도: 프로그래머스 / 2
  • 코드
from collections import deque
import copy

def solution(n, wires):
    answer = n
    for i in range(len(wires)): # n-1개의 wires들을 하나씩 제거하는 모든 경우의 수
        temp = copy.deepcopy(wires)
        del temp[i]
        graph = [[] for _ in range(n+1)]
        visited = [False] * (n+1)
        
        for wire in temp:
            a, b = wire
            graph[a].append(b)
            graph[b].append(a)
            
        count = get_count(graph, 1, visited)
        rest = n - count
        answer = min(answer, abs(rest-count))
    return answer

def get_count(graph, start, visited):
    count = 1
    q = deque([start])
    visited[start] = True
    while q:
        now = q.popleft()
        for i in graph[now]:
            if not visited[i]:
                visited[i] = True
                q.append(i)
                count += 1
    return count

def solution(n, wires):
    ans = n
    for sub in (wires[i+1:] + wires[:i] for i in range(len(wires))):
        s = set(sub[0])
        print(sub)
        print(s)
        [s.update(v) for _ in sub for v in sub if set(v) & s]
        print(s)
        ans = min(ans, abs(2 * len(s) - n))
    return ans

  • 느낀점
    • 완전탐색 문제
    • wires들을 하나씩 제거한 모든 경우의 수에 대해서 완탐 하기
    • wire 제거 한 후, 나는 bfs 를 통해 개수를 구했는데 다른 사람 풀이를 보니 집합 이용해서 간단하게 구함...
    • 근데 for _ in sub 이 코드는 먼지 이해가 잘안간다…

모음 사전

  • 사이트/난이도: 프로그래머스 / 2
  • 코드
from itertools import product

def solution(word):
    answer = 0
    aeiou = ["A", "E", "I", "O", "U"]
    strings = []
    for i in range(1, 6):
        for s in list(product(aeiou, repeat=i)):
            s = "".join(s)
            strings.append(s)
    strings.sort()
    answer = strings.index(word)
    return answer + 1
  • 느낀점
    • 완전탐색 문제
    • 모음으로 만들 수 있는 1~5자리의 문자열을 중복순열을 통해 오름차순 정렬 후 인덱스 반환하기
728x90
Comments