본문 바로가기

Python191

[LeetCode] Broken Calculator https://leetcode.com/problems/broken-calculator/ Broken Calculator - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 자꾸 풀라고 알람이 와서 풀어버리겠다!! 첫 풀이 class Solution: def brokenCalc(self, startValue: int, target: int) -> int: q : Deque = collections.deque() q.append((startValue, 0)) whil.. 2022. 3. 23.
[LeetCode] Merge Two Sorted Lists https://leetcode.com/problems/merge-two-sorted-lists/ Merge Two Sorted Lists - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 정렬된 두 연결 리스트를 크기 순서대로 정렬하여 병합하는 문제 1. list1과 list2를 비교해 주면서 merge_list에 추가 2. 원소가 남은 친구들을 추가 # Definition for singly-linked list. # class ListNode: # def _.. 2022. 3. 23.
[LeetCode] Palindrome Linked List https://leetcode.com/problems/palindrome-linked-list/ Palindrome Linked List - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com Deque를 활용하면 popleft도 O(1) 이므로 성능 향상 # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self... 2022. 3. 23.
python 다중 할당 동작방식 python 다중 할당의 동작 방식에 대해 어렴풋이 이해하고 있었는데, 이번 기회에 확실하게 짚고 넘어가야겠다. 일단 파이썬에서는 다중 할당(Multiple Assignment)을 지원한다. 이는 2개 이상의 값을 2개 이상의 변수에 동시에 할당하는 것을 말한다. a, b = 1, 2 >>> a 1 >>> b 2 위와 같이 a와 b 변수 각각의 값을 1, 2로 할당해 주었다. 좀 더 복잡한 경우에 어떻게 동작하는지 테스트해보았다. 아래 코드를 보자. class SingleLinkedList: def __init__(self, name, val=0, next=None) -> None: self.name = name self.val = val self.next = next def __repr__(self):.. 2022. 3. 23.
python typing optional python에서는 굳이 타입을 명시하지 않아도 duck typing (동적 타이핑)을 통해 객체의 타입이 결정된다. 이는 편리하다는 장점이 있지만, 코드가 많아지게 되면 뭐가 뭔지 알아보기 힘들다는 단점이 있다. 이를 보완하기 위해 파이썬에서는 typing을 지정할 수 있게 typing 모듈을 제공한다. https://docs.python.org/3/library/typing.html typing — Support for type hints — Python 3.10.3 documentation Note The Python runtime does not enforce function and variable type annotations. They can be used by third party tools .. 2022. 3. 23.
[LeetCode] Reverse String https://leetcode.com/problems/reverse-string/submissions/ Reverse String - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 문자열을 뒤집는 문제 투 포인터 활용 class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ left, right = 0,.. 2022. 2. 28.
[LeetCode] Valid Palindrome https://leetcode.com/problems/valid-palindrome/ Valid Palindrome - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 유효한 펠린드롬인지 확인하는 문제 Deque를 활용해서 풀이 가능 class Solution: def isPalindrome(self, s: str) -> bool: strs: Deque = collections.deque() for char in s: if char.isalnum(): strs.a.. 2022. 2. 25.
[프로그래머스] 110 옮기기(Python) https://programmers.co.kr/learn/courses/30/lessons/77886 코딩테스트 연습 - 110 옮기기 0과 1로 이루어진 어떤 문자열 x에 대해서, 당신은 다음과 같은 행동을 통해 x를 최대한 사전 순으로 앞에 오도록 만들고자 합니다. x에 있는 "110"을 뽑아서, 임의의 위치에 다시 삽입합니다. 예를 programmers.co.kr 문제의 핵심은 111보다 110이 앞에 와야 함. def solution(s): answer = [] for string in s: stack = [] counting = 0 for st in string: if(len(stack) >= 2 and stack[-1] == '1' and stack[-2] =='1' and st =='0'):.. 2022. 2. 12.
[프로그래머스] 블록 게임(Python) https://programmers.co.kr/learn/courses/30/lessons/42894 코딩테스트 연습 - 블록 게임 [[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,4,0,0,0],[0,0,0,0,0,4,4,0,0,0],[0,0,0,0,3,0,4,0,0,0],[0,0,0,2,3,0,0,0,5,5],[1,2,2,2,3,3,0,0,0,5],[1,1,1,0,0,0,0,0,0,5]] 2 programmers.co.kr 구현이 좀 까다로웠던 문제다. 처음에 블록 게임을 테트리스처럼 생각해서 헷갈렸는데 검정 블록은 아래로 쭉 가는 방향으로만 쌓을 수 있다. 1. 매번.. 2022. 2. 10.
[LeetCode] Two Sum https://leetcode.com/problems/two-sum/ Two Sum - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com Leet Code의 문제들을 풀어 볼 예정이다. 처음 문제인 Two Sum 문제를 풀어봤다. 예전 화이트보드 코딩 테스트때 이 문제를 접한 적이 있었는데, 이렇게 유명한 문제인지 몰랐다. 그 때는 잘 못 풀었는데.. 이 문제는 dict 를 사용하면 O(n) 으로 풀이할 수 있다. 나의 풀이 class Solution: def tw.. 2022. 2. 9.
[프로그래머스] 카드 짝 맞추기(Python) https://programmers.co.kr/learn/courses/30/lessons/72415 코딩테스트 연습 - 카드 짝 맞추기 [[1,0,0,3],[2,0,0,0],[0,0,0,2],[3,0,1,0]] 1 0 14 [[3,0,0,2],[0,0,1,0],[0,1,0,0],[2,0,0,3]] 0 1 16 programmers.co.kr 완전 탐색 + bfs로 풀이하려다 실패하고 다른 풀이를 참고했다. 알고리즘은 모든 경우에 대해 탐색하는 것인데, 매번 경우에서 순서를 정해놓고 탐색하는 아이디어다. 제거된 카드인지 확인하는 부분에서 비트 연산을 쓰는 것이 인상적이다. 나도 이렇게 짤 수 있게 노력해야겠다잇 import math import queue Board = [] Allremoved = 1 A.. 2022. 2. 8.
[프로그래머스] [3차] 자동완성(Python) https://programmers.co.kr/learn/courses/30/lessons/17685 코딩테스트 연습 - [3차] 자동완성 자동완성 포털 다음에서 검색어 자동완성 기능을 넣고 싶은 라이언은 한 번 입력된 문자열을 학습해서 다음 입력 때 활용하고 싶어 졌다. 예를 들어, go 가 한 번 입력되었다면, 다음 사용자는 g programmers.co.kr Trie 알고리즘을 활용해서 풀었다. 나의 풀이 class Trie(): def __init__(self): self.child = dict() self.count = 0 def insert(self,string): curr = self for str in string: if str not in curr.child: curr.child[str].. 2022. 2. 7.
[프로그래머스] 호텔 방 배정(Python) https://programmers.co.kr/learn/courses/30/lessons/64063 코딩테스트 연습 - 호텔 방 배정 programmers.co.kr 딕셔너리를 활용해서 해당 방 선택 시 몇 번으로 이동하면 되는지 저장하면 된다. def solution(k, room_number): answer = [] room = {} for num in room_number: index = num visit = [index] while index in room: index = room[index] visit.append(index) answer.append(index) for i in visit: room[i] = index + 1 return answer 2022. 2. 5.
[프로그래머스] 미로 탈출(Python) https://programmers.co.kr/learn/courses/30/lessons/81304 코딩테스트 연습 - 미로 탈출 4 1 4 [[1, 2, 1], [3, 2, 1], [2, 4, 1]] [2, 3] 4 programmers.co.kr 방문처리에서 굉장히 헷갈렸던 문제다. 다른 풀이를 보고 참고했다. 비트 마스크에 대해 알게 되었다. import heapq INF = 987654321 def dijkstra(n,graph,start,end,traps): visited = [[False for _ in range(1 2022. 2. 4.
[프로그래머스] 선입 선출 스케줄링(Python) https://programmers.co.kr/learn/courses/30/lessons/12920 코딩테스트 연습 - 선입 선출 스케줄링 처리해야 할 동일한 작업이 n 개가 있고, 이를 처리하기 위한 CPU가 있습니다. 이 CPU는 다음과 같은 특징이 있습니다. CPU에는 여러 개의 코어가 있고, 코어별로 한 작업을 처리하는 시간이 다릅니 programmers.co.kr 이진탐색을 활용해야 하는 문제였다. 비슷한 문제를 풀었었는데 떠올리지 못했다. def solution(n,cores): if n = n: right = mid else: left = mid + 1 for core in cores: n -= (right-1)//core for i in range(len(cores)): if right .. 2022. 1. 31.