본문 바로가기

dict12

[자료구조] 방문 길이 파이썬 (hash) def solution(dirs): x,y = 5,5 # start point mapping = {"U":(0,1), "D":(0,-1), "R":(1,0), "L":(-1,0)} visited = [[0 for _ in range(11)] for _ in range(11)] for i,d in enumerate(dirs): if 0 2021. 4. 24.
[자료구조] 좌석구매 파이썬 (hashable VS. unhashable) unique한 pair를 구하면 될거라 생각해서 2d 리스트를 그대로 set에 넣었지만 TypeError: unhashable type: 'list' unhashable 에러가 발생했다. 문제를 마저 풀기 전에 unhashable과 hashable의 차이점을 알아보자. 출처: realpython.com/lessons/immutable-vs-hashable/ hashable object라는 것은 can't modify 정도로 이해가 가능한데 좀 더 설명이 필요하기 때문에 다른 글을 찾아봤다. 요약: non-duplicate를 요구하는 python object들은 hashable하다. 출처: https://analytics4everything.tistory.com/m/138 2021. 4. 22.
[자료구조] 운송 트럭 파이썬 (dict) def solution(max_weight, specs, names): answer = [] answer.append(None) print(answer) specs = dict(specs) # print(specs) tmp = 0 cnt = 1 for n in names: tmp += int(specs[n]) if tmp > max_weight: cnt += 1 tmp = int(specs[n]) # print(tmp, cnt) return cnt 처음에 pseudo 코드로 만들고 풀었을때 에러가 났던 부분은 if 문에서 tmp를 int(specs[n])이 아니라 0로 설정해서 안풀렸다 tmp에 새로운 무게를 추가했을때, max_weight을 초과하게 되면 tmp는 추가한 무게로 초기화 시켜주는 것이 중.. 2021. 4. 20.
[LeetCode] Valid Anagram 파이썬 (dict) class Solution: def isAnagram(self, s: str, t: str) -> bool: def get_dict(word): res = {} for c in word: if c in res: res[c] += 1 else: res[c] = 1 return sorted(res.items()) sd = get_dict(s) td = get_dict(t) return sd == td dict를 sort 하려면 sorted 안에 dict.items()를 넣어주면 된다. 아래 처럼 key를 사용해서 key, value 순으로 sort가능하다. ygseo.tistory.com/215 2021. 4. 7.
[LeetCode] Contains Duplicate II 파이썬 (dict) class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: seen = {} for idx, value in enumerate(nums): if value not in seen: seen[value] = [idx] else: seen[value] += [abs(idx - seen[value][-1])] for key in seen.keys(): if len(seen[key])>1: if sum( [x 0: return True return False seen 이라는 dict를 만들어서 value 들은 list 형식으로 추가해서 duplicate일 경우(seen에 있는 key일 경우) 현재 위치 - 기존의 가장 최근.. 2021. 4. 5.
[LeetCode] Happy Number 파이썬 (dict, cycle) class Solution: def isHappy(self, n): lookup = {} while n != 1 and n not in lookup: lookup[n] = True n = self.nextNumber(n) return n == 1 def nextNumber(self, n): new = 0 for char in str(n): new += int(char)**2 return new 출처: github.com/jiapengwen/LeetCode/blob/master/Python/happy-number.py 2021. 4. 4.
[LeetCode] Majority Element 파이썬 (dict, Counter, median) nums = [2,2,1,1,1,2,2] d = dict() for n in nums: if n in d: d[n] += 1 else: d[n] = 0 print(d) print(sorted(d.items(), key=lambda x: -x[1])[0][0]) # output # {2: 3, 1: 2} # [(2, 3), (1, 2)] #(key, value) # 2 dict에 넣어서 sorted key items()로 iterable하게 만든 다음 tuple로 나오는 값 중에서 뒤의 value 인 x[1]을 기준으로 오름차순으로 해야하기 때문에 -x[1] 으로 해준다. 제일 앞에 있는 tuple 중에서 key값을 return 해야되기 때문에 [0][0] 2021. 4. 2.
[LeetCode] Excel Sheet Column Title 파이썬 (divmod, chr, ord) class Solution: def convertToTitle(self, columnNumber: int) -> str: q = columnNumber ans = "" while True: if q == 0: break q, r = divmod(q-1,26) ans += chr(r + ord('A')) return ans[::-1] 0-indexing이기 때문에 q-1을 한 값에 divmod를 26으로 추출 대문자를 출력해야 되기 때문에 ord("A") ,즉 65를 기준으로 r(나머지) 를 더한 값을 chr에 인자로 넣어서 character를 ans에 추가해준다. return은 역순으로 해줘야 한다. dict을 활용한 방법 alpha = {} az = [chr(x) for x in range(ord("A.. 2021. 4. 2.
[LeetCode] Two Sum II - Input array is sorted 파이썬 class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: seen = {} for i, v in enumerate(numbers): remaining = target - v if remaining in seen: return [seen[remaining]+1, i+1] seen[v] = i return [] 기존의 Two Sum 과 다른 점은 sorted array라는 점과 zero-indexed가 아니라 1-indexed이라는 점. 2021. 4. 2.