Algorithm

[요약] 코딩테스트 파이썬 기초 핵심

potato_pizza 2024. 6. 20. 00:34
728x90

1. 리스트

삽입, 추가

1. 리스트 맨 뒤에 삽입: 리스트명.append()

# 리스트 생성
L = [1, 2, 3]

# 맨 뒤에 4 삽입
L.append(4)
print(L)

## 결과
# [1, 2, 3, 4]

2. 삽입: insert(삽입할 위치 인덱스, 삽입할 값)

# 리스트에 5를 1번 인덱스에 삽입
L.insert(1, 5)
print(L)

## 결과
# [1, 5, 2, 3, 4]

3. 리스트 복사: 리스트명.copy()

# 리스트 복사
L_copy = L.copy()
print(L_copy)

## 결과
# [1, 5, 2, 3, 4]

 

제거

1. 특정 값 하나 제거: 리스트명.remove(특정값)

# 5 제거
L.remove(5)
print(L)

## 결과
# [1, 2, 3, 4]

2. 리스트의 맨 마지막 값 제거: 리스트명.pop()

# 맨 마지막 값 제거
L.pop()
print(L)

## 결과
# [1, 2, 3]

3. 리스트의 첫번째 값 제거: 리스트명.pop(0)

# 첫 번째 값 제거
L.pop(0)
print(L)

## 결과
# [2, 3]

4. 리스트 값 모두 삭제: 리스트명.clear()

# 모든 값을 삭제
L.clear()
print(L)

## 결과
# []

5. 특정 인덱스 값 제거: del(리스트명[인덱스])

# 다시 리스트를 생성
L = [1, 2, 3, 4]
# 1번 인덱스 값 제거
del(L[1])
print(L)

## 결과
# [1, 3, 4]

6. 리스트 삭제: del(L)

# 리스트 L 삭제
del(L)

7. 중복 제거: list(set(리스트명))

# 중복이 있는 리스트
L = [1, 1, 2, 2, 3, 3]
# 중복 제거
L = list(set(L))
print(L)

## 결과
# [1, 2, 3]

 

정렬

1. 정렬(오름차순): 리스트명.sort()

# 리스트 생성
L = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
# 오름차순으로 정렬
L.sort()
print(L)

## 결과
# [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

2. 정렬(내림차순): 리스트명.sort(reverse=True)

# 내림차순으로 정렬
L.sort(reverse=True)
print(L)

## 결과
# [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]

3. 리스트 역순: 리스트명.reverse()

# 역순으로 정렬
L.reverse()
print(L)

## 결과
# [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

 

개수 확인

1. 특정 값의 개수를 확인: 리스트명.count(특정값)

# 값 5의 개수 확인
count_five = L.count(5)
print(count_five)

## 결과
# 3

2. 리스트 길이 확인: len(리스트명)

# 리스트의 길이 확인
length = len(L)
print(length)

## 결과
# 11

3. 특정 값의 인덱스 찾기: 리스트명.index(특정값)

# 값 9의 인덱스 찾기
index_nine = L.index(9)
print(index_nine)

## 결과
# 9

 

List Comprehension

# 리스트 컴프리헨션을 사용하여 0부터 9까지 각 숫자의 제곱을 요소로 하는 리스트 생성
L = [i * i for i in range(10)]
print(L)

## 결과
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

 

Lambda 함수 사용

  • lambda a, b: a+b 
  • 간략한 함수
# 튜플 리스트에서 두 번째 요소로 정렬
array = [('김철수', 100), ('김영미', 95), ('홍길동', 80)]
sorted_array = sorted(array, key=lambda x: x[1])
print(sorted_array)

## 결과
# [('홍길동', 80), ('김영미', 95), ('김철수', 100)]

 

2. 문자열

문자열 기본 조작

1.슬라이싱

# 문자열 슬라이싱
string = "Hello, World!"
sliced = string[0:5]
print(sliced)

## 결과
# Hello

2. 문자열에 있는 특정 문자 개수: 문자열.count(특정문자)

# 문자 'l'의 개수 세기
count_l = string.count('l')
print(count_l)

## 결과
# 3

3. 문자열이 숫자로 이루어져있는지 판별: 문자열.isdigit()

# 숫자인지 판별
num_string = "12345"
is_digit = num_string.isdigit()
print(is_digit)

## 결과
# True

 

치환, 교체, 대소문자

1. 치환: 문자열.replace(찾는 문자, 바꿀문자, 바꿀 문자 개수)

# 'l'을 'z'로 치환
replaced_string = string.replace('l', 'z')
print(replaced_string)

## 결과
# Hezzo, Worzd!

2. 문자열 내 모든 문자를 대문자로: 문자열.upper()

# 모든 문자를 대문자로
upper_string = string.upper()
print(upper_string)

## 결과
# HELLO, WORLD!

3. 문자열 내 모든 문자를 소문자로: 문자열.lower()

# 모든 문자를 소문자로
lower_string = string.lower()
print(lower_string)

## 결과
# hello, world!

4. 문자열의 대소문자 상호 전환: 문자열.swapcase()

# 대소문자 전환
swap_string = string.swapcase()
print(swap_string)

## 결과
# hELLO, wORLD!

5. 특정 문자 찾기: 문자열.find(찾을 문자, 시작 index, 끝 index)

# 'W'의 위치 찾기
find_w = string.find('W')
print(find_w)

## 결과
# 7

6. 2진수 to 10진수: int('이진숫자', 2)

# 2진수 '1101'를 10진수로 변환
binary = '1101'
decimal = int(binary, 2)
print(decimal)

## 결과
# 13

 

문자열로 이루어진 리스트나 딕셔너리에서 특정 문자가 포함된 항목 찾을 때

word = 'abcd'
# 'ab'로 시작하는지
start = word.startswith('ab')

# 'cd'로 끝나는지
end = word.endswith('cd')
print("Starts with 'ab':", start)
print("Ends with 'cd':", end)

## 결과
# Starts with 'ab': True
# Ends with 'cd': True

 

3. 표준 라이브러리

내장 함수: 기본 입출력, 정렬 함수와 같은 기본적인 함수

1. 수식 계산

  • 수식 계산: eval(계산식)
result = eval("(3+5)*7")
print(result)

## 결과
# 56

2. 합

result = sum([1, 2, 3, 4, 5])
print(result)

## 결과 
# 15

3. 최대, 최소

  • max(), min()
min_result = min(2, 3, 5, 7)
max_result = max(2, 3, 5, 7)
print(min_result, max_result)

## 결과
# 2 7

4. 정렬

  • 기본 정렬
# 문자열을 알파벳 순서로 정렬
string = "banana"
sorted_string = ''.join(sorted(string))
print(sorted_string)

## 결과

# aaabnn

 

  • 정렬 with key
# 문자열 리스트를 문자 길이로 정렬

words = \["apple", "banana", "cherry", "date"\]  
sorted\_words = sorted(words, key=len)  
print(sorted\_words)

## 결과

# \['date', 'apple', 'banana', 'cherry'\]

 

itertools: 반복되는 형태의 데이터를 처리하기 위한 기능

1. 순열(Permutations)

import itertools

# 요소 1, 2, 3으로 구성된 순열 생성

items = \[1, 2, 3\]  
permutations = list(itertools.permutations(items))  
print("Permutations of \[1, 2, 3\]:", permutations)

## 결과

# Permutations of \[1, 2, 3\]: \[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)\]

2. 조합(Combinations)

# 요소 1, 2, 3 중 2개를 선택하는 조합 생성

combinations = list(itertools.combinations(items, 2))  
print("Combinations of \[1, 2, 3\] taken 2 at a time:", combinations)

## 결과

# Combinations of \[1, 2, 3\] taken 2 at a time: \[(1, 2), (1, 3), (2, 3)\]

3. 중복 순열, 조합

import itertools

# 요소 1, 2, 3으로 구성된 중복 순열 생성, 2개를 선택

items = \[1, 2, 3\]  
product = list(itertools.product(items, repeat=2))  
print("Product (repeat=2) of \[1, 2, 3\]:", product)

## 결과

# Product (repeat=2) of \[1, 2, 3\]: \[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)\]

# 요소 1, 2, 3 중 2개를 선택하는 중복 조합 생성

combinations\_with\_replacement = list(itertools.combinations\_with\_replacement(items, 2))  
print("Combinations with replacement of \[1, 2, 3\] taken 2 at a time:", combinations\_with\_replacement)

## 결과

# Combinations with replacement of \[1, 2, 3\] taken 2 at a time: \[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)\]

 

Collections: deque, Counter와 같은 유용한 자료구조

1. Counter

  • 요소의 등장 횟수
    from collections import Counter
    
    # 문자열에서 각 문자의 등장 횟수를 세기
    string = "mississippi"
    count = Counter(string)
    print(count)
    
    ## 결과
    # Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})

2. deque

  • 양쪽 끝에서 빠르게 추가하고 제거할 수 있는 자료형
from collections import deque

# deque 생성과 활용
dq = deque([1, 2, 3])
dq.appendleft(0) # 왼쪽 끝에 추가
dq.append(4) # 오른쪽 끝에 추가
print(dq)
dq.popleft() # 왼쪽 끝의 요소 제거
print(dq)

## 결과
# deque([0, 1, 2, 3, 4])
# deque([1, 2, 3, 4])

 

math 함수

1. 최대 공약수(GCD)

import math

# 두 수의 최대 공약수 계산
num1 = 36
num2 = 60
gcd = math.gcd(num1, num2)
print("GCD of 36 and 60 is:", gcd)

## 결과
# GCD of 36 and 60 is: 12

2. 최소 공배수(LCM)

cm = num1 * num2 // math.gcd(num1, num2)
print("LCM of 36 and 60 is:", lcm)

## 결과
# LCM of 36 and 60 is: 180

 

728x90
반응형