본문 바로가기
Python/코딩

기억해야할 표현 - 파이썬알고리즘 인터뷰 공부

by Rainbound-IT 2021. 5. 6.
반응형

letters.sort(key=lambda x: (x.split()[1:], x.split()[0]))

 

letters를 x.split[1:]순으로 정렬하고 일치시 [0]로 정렬

 

 

class Solution:

def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:

words = [word for word in re.sub(r'[^\w]', ' ', paragraph)

.lower().split()

if word not in banned]

counts = collections.Counter(words)

# 가장 흔하게 등장하는 단어의 첫 번째 인덱스 리턴

return counts.most_common(1)[0][0]

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
import collections
import re
from typing import List
 
class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        words = [word for word in re.sub(r'[^\w]'' ', paragraph)
            .lower().split()
                 if word not in banned]
 
        counts = collections.Counter(words)
        # 가장 흔하게 등장하는 단어의 첫 번째 인덱스 리턴
        return counts.most_common(1)[0][0]
cs

d

 

1
2
3
4
5
6
7
8
9
10
11
12
import collections
from typing import List
 
 
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        anagrams = collections.defaultdict(list)
 
        for word in strs:
            # 정렬하여 딕셔너리에 추가
            anagrams[''.join(sorted(word))].append(word)
        return list(anagrams.values())
cs

defaultdict - 딕셔너리형은 원래 key, value 이런식으로 두개 추가해야하는데 초기값설정하기 위해 이걸 사용

a= 'zyx'

sorted(a)

>>['z', 'y', 'x']

''.join(sorted(a))

>>'xyz

 

 

두수의 합이 target에 있는지 있다면 그거 반환

1
2
3
4
5
6
7
8
9
10
11
12
 
from typing import List
 
 
class Solution:
    def twoSum(self, nums: List[int], target: int-> List[int]:
        nums_map = {}
        # 하나의 `for`문으로 통합
        for i, num in enumerate(nums):
            if target - num in nums_map:
                return [nums_map[target - num], i]
            nums_map[num] = i
 
cs

 

 

아이디어는 타겟값에 해당값을빼면 다른수를 바로 알수 있다는점을 이용

for 문 이것처럼 두개를 저렇게 할수가있다.

 

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)):
            for j in range(i + 1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i, j]

 

 

 

 

 

 

반응형

'Python > 코딩' 카테고리의 다른 글

main 함수  (0) 2021.06.22
'_' 언더스코어  (0) 2021.05.12
Algorithm  (0) 2021.04.28
python 여러 함수들  (0) 2021.04.24
코딩 개요  (0) 2021.04.24

댓글