유랑하는 나그네의 갱생 기록

だけど素敵な明日を願っている -HANABI, Mr.children-

Study/Python

[Python] Live Test를 위한 코드 뭉치

Madirony 2025. 9. 19. 00:23
반응형

Intro

1학년 수업 때 썼던 책 (포스트 내용과 무관합니다.)

Python은 학부생 때 잠깐 만졌다가 멀리했었는데, 이번에 Live Test를 보게 되면서 기억을 되살릴 필요가 있어서 포스팅하게 되었습니다. 그나마 다행인 건 Python 사용 경험이 있고, 구글링이 가능하다는 점입니다.

 

간단하게 문법 정도 원활히 활용할 수 있도록 정리할 생각입니다.

빠르게 시작하겠습니다.

 

 


본론

Python Syntax

Python Runtime 확인

(base) ☁  python  python --version
Python 3.9.10

 

기본 문법 & 자료형

x = 10 # 타입 선언 없음
f = 3.14
s = "Hello, World!"
a = False
b = True

print("---- Swapping Variables ----")
a, b = b, a
print(a, b) # True False

print("\n---- Function Definition and Call ---")
def add(x, y):
    return x + y
result = add(x, f)
print(result) # 13.14

print("\n---- if Condition ---")
if result > 10:
    print(s) # Hello, World!

print("\n---- for Looping ---")
for i in range(5):
    print("for : ", i)
"""
for :  0
for :  1
for :  2
for :  3
for :  4
"""

print("\n---- while Looping ---")
while x > 0:
    x -= 1
print("\nwhile : ", x) # while :  0

None은 Java에서 사용하는 null과 유사하고, 동일 객체 비교는 is, 값 비교는 == 연산자입니다.

 

 

문자열

s = "Hello"
print(s[0], s[-1]) # H o
print(s[:3]) # Hel
print(s[::-1]) # olleH

name, age = "Alice", 30
print(f"{name} is {age} years old.") # Alice is 30 years old.

print("Hello World".replace("World", "Python")) # Hello Python
s = s.replace("l", "x")
print(s) # Hexxo
s = s.replaceAt(2, "L")
print(s) # HeLxo


print(" ".join(["a", "b", "c"])) # a b c
print("abc,def".split(",")) # ['abc', 'def']

print("  hello  ".strip()) # hello

print("Hello".upper()) # HELLO
print("WORLD".lower()) # world

print("Hello World".find("World")) # 6
print("Hello World".count("o")) # 2
print("Hello World".startswith("Hello")) # True
print("Hello World".endswith("Python")) # False
print("Hello World".index("o")) # 4

def sb():
    str_list = []
    for num in range(5):
        str_list.append(str(num))
    return '\n'.join(str_list)

print(sb())
"""
0
1
2
3
4
"""

Java에서 사용하는 StringBuilder로 문자열을 만들고 싶다면? 빈 list를 생성하고 데이터를 넣은 다음, join 함수를 통해 문자열로 반환하면 되겠습니다.

 

 

그리고 부분 문자열 관련으로는 in 연산자가 되게 성능이 좋아졌는데, 관련 내용은 아래 포스트를 확인하면 되겠습니다.

https://claris.tistory.com/71

 

[Java] Java로 풀면 KMP를 써야하는 브론즈 문제가 있다?

관련 링크 : https://www.acmicpc.net/problem/16916  약 1년 전, 백준 스트릭을 유지하던 때가 있었습니다. 자바로 코테 준비를 시작한 지 얼마 안 됐기도 하고, 여러 가지 준비로 바빠서 가볍게 몸풀기로

claris.tistory.com

 

 

리스트

arr = [3,1,2]
arr.append(4) # [3,1,2,4]
arr.insert(0,0) # [0,3,1,2,4]
arr.pop() # [0,3,1,2] << 인덱스 인자를 넣으면 해당 위치 pop

arr.sort() # [0,1,2,3]
arr.sort(reverse=True) # [3,2,1,0]
arr2 = sorted(arr) # [0,1,2,3] 새로운 리스트 반환
arr2.sort(key=lambda x: -x) # [3,2,1,0]
arr2.sort(key=lambda x: x%2) # [0,2,1,3] 짝수 먼저
arr2.sort(key=lambda x: (x%2, -x)) # [2,0,3,1] 짝수 먼저, 내림차순

evens_sq = [x*x for x in range(10) if x%2==0] # [0,4,16,36,64]

 

 

딕셔너리

d = {"a":1, "b":2}
d["c"] = 3
print(d.get("z", 2)) # 2
arr = []
for k, v in d.items():
    arr.append(k)
    arr.append(str(v))
print("".join(arr)) # abc

from collections import defaultdict, Counter
cnt = Counter("banana")
freq = defaultdict(int); freq["x"] += 1
print(cnt, freq) # Counter({'a': 3, 'n': 2, 'b': 1}) defaultdict(<class 'int'>, {'x': 1})

 

 

집합

s = {1, 2, 3}
s.add(4); s.remove(2)
print(3 in s) # Output: True
print(s) # Output: {1, 3, 4}

 

 

조건, 반복, 열거

# 조건
x = 0
if x > 5: print("x is greater than 5")
elif x == 5: print("x is equal to 5")
else: print("x is less than 5")

#반복
for i in range(5): print(i)
for i, v in enumerate(['a', 'b', 'c']): print(i, v)
while x < 5: print(x); x += 1

 

 

함수, 스코프

def add(a, b = 0):
    return a + b
print(add(1)) # 1

def f(*args, **kwargs):
    print(args, kwargs)
f(1, 2, 3, x=4, y=5) # (1, 2, 3) {'x': 4, 'y': 5}

# 람다
key_fn = lambda x: x * 2
print(key_fn(3)) # 6
print((lambda x: x + 1)(4)) # 5
print((lambda x, y=2: x + y)(3)) # 5

key_fn = lambda p: (p[0], -p[1])
print(sorted([(1, 2), (3, 4), (1, -1)], key=key_fn)) # [(1, 2), (1, -1), (3, 4)]

 

 

예외

try:
    1/0
except ZeroDivisionError as e:
    print("Caught an exception:", e)
else:
    print("No exception occurred.")
finally:
    print("Execution completed.")

 

 

입출력

import sys
input = sys.stdin.readline
n = int(input())
print(n)
arr = list(map(int, input().split()))
print(*arr)

 

 

deque

from collections import deque
q = deque([1,2]); q.append(3); q.popleft()
print(q) # Output: deque([2, 3])

 

 

heap

import heapq
h = []; heapq.heappush(h, 5); heapq.heappush(h, 1)
heapq.heappush(h, 3); print(heapq.heappop(h))
# OUTPUT: 1
heapq.heappush(h, 2); print(heapq.heappop(h))
# OUTPUT: 2

 

 

이진 탐색

import bisect
arr = [1, 2, 4, 5]
x = 3
i = bisect.bisect_left(arr, x)
print(i) # 
j = bisect.bisect_right(arr, x)
print(j) # 2

 

 

itertools

from itertools import combinations, permutations, accumulate
print(list(combinations([1,2,3], 2))) # [(1, 2), (1, 3), (2, 3)]
print(list(permutations([1,2,3], 2))) # [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
print(list(accumulate([1,2,3]))) # [1, 3, 6]
print(list(map(lambda x: x * 2, [1,2,3]))) # [2, 4, 6]
print(list(filter(lambda x: x % 2 == 0, [1,2,3]))) # [2]

 

 

math

import math
print(math.gcd(10, 20)) # 10
print(math.lcm(10, 20)) # 20
print(math.isqrt(10)) # 3
print(math.prod([1, 2, 3, 4])) # 24
print(math.inf) # inf
print(math.nan) # nan
print(math.pi) # 3.141592653589793

 

 

정렬 패턴

arr = [(1, 2), (3, 4), (1, -1), (2, 2), (3, 1)]
arr.sort(key=lambda x: (x[0], -x[1]))
print(arr) # 문자열/숫자 혼용 정렬, 다중 키 정렬을 자주 사용

위에서 리스트 정렬을 하긴 했지만, 한번 더!

 

 

파일 I/O

# 읽기
with open("in.txt") as f:
    data = [line.strip() for line in f]

# 쓰기
with open("out.txt","w") as f:
    f.write("\n".join(map(str, arr)))

 

 

BFS/DFS

from collections import deque
# BFS
def bfs(start):
    q = deque([start]); vis = set([start])
    while q:
        u = q.popleft()
        for v in graph[u]:
            if v not in vis:
                vis.add(v); q.append(v)

# DFS (재귀)
import sys
sys.setrecursionlimit(1_000_000)

def dfs(u):
    vis.add(u)
    for v in graph[u]:
        if v not in vis:
            dfs(v)
import sys
N, M, V = map(int, sys.stdin.readline().split())
graph = [[] for _ in range(N + 1)]
for _ in range(M):
    a, b = map(int, sys.stdin.readline().split())
    graph[a].append(b)
    graph[b].append(a)

def dfs(v, visited):
    visited[v] = True
    print(v, end=' ')
    for i in sorted(graph[v]):
        if not visited[i]:
            dfs(i, visited)

def bfs(v, visited):
    queue = [v]
    visited[v] = True
    while queue:
        v = queue.pop(0)
        print(v, end=' ')
        for i in sorted(graph[v]):
            if not visited[i]:
                queue.append(i)
                visited[i] = True

dfs(V, [False] * (N + 1))
print()
bfs(V, [False] * (N + 1))
# 1
import sys
N, M = map(int, sys.stdin.readline().split())
visited = [False] * (N + 1)
path = []
def dfs(depth):
    if(depth == M):
        print(' '.join(map(str, path)))
        return
    for i in range(1, N + 1):
        if(visited[i] == False):
            visited[i] = True
            path.append(i)
            dfs(depth + 1)
            visited[i] = False
            path.pop()

dfs(0)

# 2
import sys
N, M = map(int, sys.stdin.readline().split())
visited = [False] * (N + 1)
path = []
def dfs(idx, depth):
    if(depth == M):
        print(' '.join(map(str, path)))
        return
    for i in range(idx, N + 1):
        if(visited[i] == False):
            visited[i] = True
            path.append(i)
            dfs(i+1, depth + 1)
            visited[i] = False
            path.pop()

dfs(1, 0)

# 3
import sys
N, M = map(int, sys.stdin.readline().split())
visited = [False] * (N + 1)
path = []
def dfs(depth):
    if(depth == M):
        print(' '.join(map(str, path)))
        return
    for i in range(1, N + 1):
        path.append(i)
        dfs(depth + 1)
        path.pop()

dfs(0)

# 4
import sys
N, M = map(int, sys.stdin.readline().split())
visited = [False] * (N + 1)
path = []
def dfs(idx, depth):
    if(depth == M):
        print(' '.join(map(str, path)))
        return
    for i in range(idx, N + 1):
        path.append(i)
        dfs(i, depth + 1)
        path.pop()

dfs(1,0)

[N과 M 시리즈]

 

 

Dijkstra

import heapq, math
def dijkstra(n, graph, src):
    dist = [math.inf]*n; dist[src] = 0
    pq = [(0, src)]
    while pq:
        d,u = heapq.heappop(pq)
        if d != dist[u]: continue
        for v,w in graph[u]:
            nd = d + w
            if nd < dist[v]:
                dist[v] = nd
                heapq.heappush(pq, (nd, v))
    return dist

 

 

Union Find

def find(x):
    if parent[x] != x:
        parent[x] = find(parent[x])
    return parent[x]

def union(a,b):
    ra, rb = find(a), find(b)
    if ra == rb: return False
    if rank[ra] < rank[rb]: ra, rb = rb, ra
    parent[rb] = ra
    if rank[ra] == rank[rb]: rank[ra] += 1
    return True

 

 


P.S.

어.. 화이팅..

반응형
TOP