Algorithm
파이썬 문법

str

join()

문자열을 합치는 함수.
기본형 👇

str.join(iterable)

문자열 뒤집기

str Type에서는 reverse()를 사용할 수 없는데다가 reverse()는 슬라이싱에 비해서 5배 정도 느리다.
[::-1] 왼쪽과 같이 슬라이싱을 하게 되면 (리스트도 동일) 문자열을 뒤집을 수 있다.

str1 = "hello world"
print(str1[::-1]) # dlrow olleh

list를 str으로 변환

alphabet = ['a', 'b', 'c', 'd', 'e']
alphabet = ''.join(alphabet)
print(alphabet) # abcde

print

f-string

'' 앞에 f를 붙이면 에서 변수 접근이 가능며, 안에서 간단한 연산도 가능하다.

fruit = ["apple", "water melon"]
idx = 0
 
print(f'fruit index 0 is {fruit[idx]}') # apple
print(f'fruit index 1 is {fruit[idx + 1]}') # water melon

연산

나눗셈

  1. / : 나눗셈의 결과를 float로 반환
  2. // : 나눗셈의 을 int로 반환
  3. % : 나눗셈의 나머지를 반환
print(5 / 2) # 2.5
print(5 // 2) # 2
print(5 % 2) # 1

list

enumerate()

list의 index와 value를 동시에 return 하는 함수

list1 = ['a','b','c','d','e']
for idx, val in enumerate(list1) :
  print(idx, val) 

출력 👇

0 a
1 b
2 c
3 d
4 e

Couneters & most_common()

Couneter는 dictionary의 요소를 카운트해서 dictionary 형태로 반환한다.
Counter의 함수 중 most_common()은 가장 많은 빈도를 갖는 요소를 반환한다. ()안에 숫자를 넣으면 상위 n개의 요소를 반환한다.

예시
import collections
 
list1 = [1,2,3,4,5,5,2,1,5,1,1]
counter = collections.Counter(list1)
print(counter) # Counter({1: 4, 5: 3, 2: 2, 3: 1, 4: 1})
print(counter.most_common()) # [(1, 4), (5, 3), (2, 2), (3, 1), (4, 1)]
print(counter.most_common(1)) # (1,4)
print(counter.most_common(2)) # [(1, 4), (5, 3)]
print(counter.most_common(2)[0][1]) # 4

list comprehension

list를 생성하는 방법 중 하나

기본식
  • 예시
list1 = [i * 2 for i in [1,2,3,4] if i % 2 == 0]
print(list1) # [4, 8]
list2 = list(map(lambda x: x * 2, [1,2,3,4])) # () 사용
print(list2) # [2, 4, 6, 8]

사용 예시

sort()

정렬할 때 사용 key에 lambda를 사용하면 정렬 기준을 정할 수 있다.

logs = [
  "dig1 8 1 5 1",
  "let1 art can",
  "dig2 3 6",
  "let2 own kit dig",
  "let3 art zero"
]
letters = []
digits = []
for log in logs : 
  if not (log.split()[1].isdigit()) :
    letters.append(log)
  else : 
    digits.append(log)
 
letters.sort(key = lambda x : (x.split()[1:], x.split()[0]))

callble()

sort()의 정의를 보면 key 부분에 callable이라고 되어 있는 것을 볼 수 있는데, 이는 호출 가능한 클래스 인스턴스, 함수, 메서드 등의 객체를 의미한다. (opens in a new tab) 쉽게 생각해서 callback이라고 생각하면 될 것 같은데, sort 함수에서는 key에 split 된 str을 return 하는 Callback을 넣어주게 되고 sort 내부적으로 list를 반복해서 return str을 각각 비교해주고 해당 index를 정렬하는 형식인 것 같다.

예를 들면,

logs = [
  "dig1 8 1 5 1",
  "let1 art can",
  "dig2 3 6",
  "let2 own kit dig",
  "let3 art zero"
]
 
def func1(x) :
  return x.split()[1].isdigit(), x.split()[0]
 
letters = []
for log in logs : 
  if not (log.split()[1].isdigit()) :
    letters.append(log)
 
temp = letters
letters.sort(key = lambda x : (x.split()[1], x.split()[0]))
temp.sort(key = func1)
print(str(letters) + "\n" + str(temp)) 

위의 코드에서 lambda를 이용한 정렬과 func1을 이용한 정렬이 동일한 결과를 출력하는 것을 볼 수 있다.

sorted()

reversed: True

문자열을 거꾸로 정렬하는 방법도 문자간의 ascii 코드를 기준으로 정렬하기 때문에 apple을 거꾸로 정렬한다고 elppa가 되지는 않는다.

apple: str = "apple"
numbers: list = [1,2,3,4,5]
print(sorted(numbers, reverse=True)) # [5, 4, 3, 2, 1]
print(sorted(apple, reverse=True)) # ['p', 'p', 'l', 'e', 'a']

cmp_to_key()

커스텀하게 정렬을 하고 싶을 때 사용하는 방법이다.
이를 사용하기 위해선

from functools import cmp_to_key

를 임포트 해줘야 하며

sorted( 반복 가능한 자료형 , cmp_to_key( callable ))

형태로 사용한다.
이 때 callable에서는 -1, 0, 1을 return 해줘야 하는데 이는 각각

  • 1 : 정렬이 필요하다. 그러므로 순서를 거꾸로 변경한다.
  • 0 : 정렬이 필요하지 않다.
  • -1 : 정렬이 필요하지 않다. 라는 의미를 가지고 있다.
from functools import cmp_to_key
 
def custom_sort(a, b):
  if a + b < b + a:
    return 1
  elif a + b > b + a:
    return -1
  else:
    return 0
 
def solution(numbers):
  str_numbers = [str(num) for num in numbers]
  sorted_numbers = sorted(str_numbers, key=cmp_to_key(custom_sort))
  answer = ''.join(sorted_numbers)
  
  # 모든 숫자가 0인 경우 "0" 반환
  if answer[0] == '0':
    return '0'
  
  return answer

pop()

기본형

list.pop(index)

활용 하는 방법

aplphabet_list = [chr(i) for i in range(97, 123)] 
print(aplphabet_list.pop()) # z
print(aplphabet_list.pop(len(aplphabet_list) - 1)) # y
print(aplphabet_list.pop(0)) # a
 
# ['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x']
print(aplphabet_list) 

dictionary

del

dictionary에서 요소를 삭제한다.

dict1 = {'a': 1, 'b': 2, 'c': 3}
del dict1['a'] # {'b': 2, 'c': 3}

정규식

정규식으로 문자열 찾기

# 라이브러리를 임포트 해준 뒤
import re
 
# Pattern을 먼저 저장한 뒤 
# 해당 Pattern을 이용해서 정규식에 해당되는 문자열을 찾고
# str 형태로 저장할 수 있다.
regex = re.compile(r'정규식')
regex_list = regex.findall('문자열') # def findall(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> list[Any]: ...
alphabet = ''.join(regex_list)