본문 바로가기
🍃 Language/Python

[Python] 코딩테스트에 자주쓰이는 함수 (정렬, 문자열, 숫자, 리스트 )

by 카프리썬 2021. 5. 18.
728x90

내장함수

  • sum/min/max 
  • sorted(객체, key= ,reverse=True) : 내림차순으로 정렬
  • reversed(객체) : reversed객체
result = sorted([("홍길동", 35), ("이순신", 75), ("아무개", 50), key = lambda x: x[1], reverse=True)

# [('이순신', 75), ('아무개', 50), ('홍길동', 35)]

문자열(str) 

  • str.isalnum() : 알파벳 또는 숫자로 이루어져있는지, 특수문자들어가면 False (ex: a2A -True, 1&A- False)
  • str.isalpha() : 모두 알파벳으로만 되어 있는지, 알파벳 아닌게 하나라도 있으면 False
  • str.isdigit() : 모두 숫자로만 되어 있는지 , 숫자아닌게 하나라도 있으면 False
  • str.upper() : 대문자로 변환 ( str.isupper(): 대문자로만 되어 있는지)
  • str.lower() : 소문자로 변환 ( str.islower(): 소문자로만 되어 있는지)

리스트

  • list.append(원소) : list에 원소넣기
  • list.insert(원소,위치) : list의 인덱스위치에 원소넣기

리스트를 문자열로 바꾸고 싶다면?

  • map(바꾸고싶은타입,리스트) 
lst = [1,2,3,4]
str_list = list(map(str,lst)) # ['1','2','3','4']
str = ''.join(str_list) #1234

숫자 

impot math

  • math.pow(n,p) : n의 p승
  • math.sqrt(n) : 루트n의 값
  • 양수인지 판단 math.sqrt(n) == int(math.sqrt(n))

 from itertools import permutations, combinations, product

  • permutations(list ,n) : list에서 중복을 허용하지 않고, 순서대로 N개씩 뽑을때 (순열, 중복허용x)
  • product(list , repeat=n) : list에서 중복 포함하고, 순서대로 N개씩 뽑을때 (순열, 중복허용o)
  • combinations(list ,n) : list에서 중복을 허용하지 않고, 순서무시하고 N개씩 뽑을때 (조합,중복허용x)
lst = [1,2,3,4]

p = list(permutations(lst, 2)) 
# [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]

pro = list(product(lst, repeat=2))
#[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)]

com = list(combinations(lst, 2))
#[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

 

참고

문자열 https://buyandpray.tistory.com/48

반응형

$(document).ready(function() { var $toc = $("#toc"); $toc.toc({content: ".tt_article_useless_p_margin", headings: "h2,h3,h4"}); });