Creative Code

Chapter6(자료구조) 본문

코딩 study/python

Chapter6(자료구조)

빛하루 2023. 10. 17. 15:01
# STACK 자료구조 (리스트를 스택으로 활용)
a = [1, 2, 3, 4, 5]
a.append(10)  # 10을 리스트 끝에 추가 (push)
print(a)
a.append(20)  # 20을 리스트 끝에 추가 (push)
print(a)
print(a.pop())  # 리스트의 맨 뒤 요소를 제거하고 출력 (pop)
print(a.pop())  # 리스트의 새로운 맨 뒤 요소를 제거하고 출력 (pop)

word = input('단어 입력: ')
word_list = list(word)
print(word_list)
result = []
for i in range(len(word_list)):
    result.append(word_list.pop())  # 'word'의 문자 순서를 뒤집음
print(result)

# QUEUE 자료구조 (리스트를 큐로 활용)
a = [1, 2, 3, 4, 5]
a.append(10)  # 10을 리스트 끝에 추가 (enqueue)
a.append(20)  # 20을 리스트 끝에 추가 (enqueue)
print(a)
print(a.pop(0))  # 리스트의 첫 번째 요소를 제거하고 출력 (dequeue)
print(a.pop(0))  # 리스트의 새로운 첫 번째 요소를 제거하고 출력 (dequeue)
print(a)

# TUPLE 자료구조
t = (1, 2, 3)
print(t + t + t, t * 3)  # 튜플 연결 및 반복
t = (3,)
print(t)

# SET 자료구조
s = set([1, 2, 3, 1, 2, 3])  # 집합 생성 (중복 요소 제거)
print(s)
s.add(1)  # 요소를 집합에 추가
print(s)
s.remove(1)  # 요소를 집합에서 제거
print(s)
s.update([1, 4, 5, 6, 7])  # 여러 요소를 집합에 추가
print(s)
s.discard(3)  # 요소를 제거 (요소가 집합에 없어도 오류가 발생하지 않음)
print(s)
s.clear()  # 집합 초기화
print(s)

s1 = set([1, 2, 3, 4, 5])
s2 = set([3, 4, 5, 6, 7])
print(s1.union(s2))  # 두 집합의 합집합
print(s1 | s2)
print(s1.intersection(s2))  # 두 집합의 교집합
print(s1 & s2)
print(s1.difference(s2))  # 집합 차집합
print(s1 - s2)

# Dictionary (dict) 자료구조
student_info = {20153201: 'A', 20165945: 'B', 20148435: 'C'}
print(student_info[20153201])  # 키를 사용하여 값에 접근
student_info[20143201] = 'D'  # 새로운 키-값 쌍 추가
print(student_info.keys())  # 키 목록 가져오기
print(student_info.values())  # 값 목록 가져오기
print(student_info.items())  # 키-값 쌍 목록 가져오기

for k, v in student_info.items():
    print("키:", k)
    print('값:', v)

print(20153201 in student_info.keys())  # 키의 존재 여부 확인

# deque 모듈 (덱, 양방향 큐)
from collections import deque
deque_list = deque()
for i in range(10):
    deque_list.append(i)  # 덱의 오른쪽 끝에 추가 (push)
print(deque_list)
print(deque_list.pop())  # 가장 오른쪽 요소를 제거하고 출력 (pop)

deque_list1 = deque()
for i in range(10):
    deque_list1.appendleft(i)  # 덱의 왼쪽 끝에 추가
print(deque_list1)
print(deque_list1.pop())  # 가장 왼쪽 요소를 제거하고 출력

deque_list1 = deque()
for i in range(10):
    deque_list1.appendleft(i)
print(deque_list1)
deque_list1.rotate(2)  # 덱을 2만큼 회전
print(deque_list1)
deque_list1.rotate(3)  # 덱을 3만큼 회전
print(deque_list1)

print(reversed(deque_list1))  # 덱 뒤집기
deque_list1.extend([10, 11, 12])  # 덱을 오른쪽으로 확장
deque_list1.extendleft([13, 14, 15])  # 덱을 왼쪽으로 확장
print(deque_list1)

# OrderedDict 모듈
from collections import OrderedDict
d = OrderedDict()
d['a'] = 100
d['b'] = 200
d['y'] = 500
d['f'] = 400
for k, v in d.items():
    print(k, v)

def sort_by_key(t):
    return t[0]

def sort_by_value(t):
    return t[1]

d = dict()
d['x'] = 400
d['y'] = 200
d['z'] = 300
d['f'] = 600

for k, v in dict(sorted(d.items(), key=sort_by_key)).items():
    print(k, v)

print('')
for k, v in OrderedDict(sorted(d.items())).items():
    print(k, v)

print('')
for k, v in dict(sorted(d.items(), key=sort_by_value)).items():
    print(k, v)

print('')
for k, v in OrderedDict(sorted(d.items(), key=sort_by_value)).items():
    print(k, v)

# defaultdict 모듈
from collections import defaultdict
d = defaultdict(lambda: 0)
print(d["first"])  # 존재하지 않는 키에 접근, 기본 값 반환

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)  # 기본 값은 빈 리스트
for k, v in s:
    d[k].append(v)  # 각 키에 대한 값 리스트 생성
print(d.items())

# Counter 모듈
from collections import Counter
text = list('gallahad')
print(text)
c = Counter(text)  # 리스트 내 각 요소의 발생 횟수 계산
print(c)

c = Counter({'red': 4, 'blue': 2})
print(c)
print(list(c.elements()))  # 발생 횟수에 따른 모든 요소 목록 가져오기

c = Counter(cats=4, dogs=8)  # 이름 있는 요소를 가진 Counter 생성
print(list(c.elements()))

c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
print(c - d)  # Counter 간 뺄셈
print(c + d)  # Counter 간 덧셈
print(c & d)  # Counter 간 교집합
print(c | d)  # Counter 간 합집합

# namedtuple 모듈
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, y=22)
print(p)
print(p.x, p.y)
print(p[0] + p[1])

text = '''A press release is the quickest and easiest way to get gree publicity.
If well written, a press release can result in multiple published articles about
your firm and its products. and that can mean new prospects contacting you asking
you to sell to them.'''.lower().split()

from collections import defaultdict

word_count = defaultdict(lambda: 0)
for word in text:
    word_count[word] += 1
from collections import OrderedDict
for i, v in OrderedDict(sorted(word_count.items(), key=lambda t: t[1], reverse=True)).items():
    print(i, v)

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

Chapter8(파이썬 스타일 코드)  (0) 2023.10.19
Chapter7(파이썬 스타일 코드)  (0) 2023.10.19
Chapter5(문자열,포맷팅)  (0) 2023.10.16
Chapter4(함수)  (0) 2023.10.16
Chapter3(제어문)  (0) 2023.10.13