2/1 (Wed): 파이썬 자료구조 및 내장함수 공부

Minsang Kang·2023년 2월 1일
1

Python

목록 보기
1/6

Python 라이브러리

sys

>>> import sys
>>> input = sys.stdin.readline

collections

>>> from collections import deque
>>> d = deque()

math

>>> import math
>>> print(math.pi)

numpy

>>> import numpy
>>> b = numpy.array(b)

Python 내장형

논리연산

  • and, or: short-circuit 연산자 (왼쪽에서 오른쪽으로 값이 구해지고, 결과가 결정되면 뒷 연산자는 무시)
  • not: 비논리 연산자보다 낮은 우선순위
    숫자형
  • -x: 음의 x
  • x // y: 몫
  • x % y: 나머지
  • abs(x): 절댓값 x
  • int(x), math.floor(x): 정수 x (x보다 작거나 같은 가장 큰 정수)
    • math.ceil(x): x보다 크거나 같은 가장 작은 정수
  • float(x): 실수 x
  • pow(x, y), x ** y: x ^ y

비트 연산

  • x ^ y: xor 연산 (다른경우 1)
  • x << n: n비트만큼 왼쪽으로 시프트
  • x >> n: n비트만큼 오른쪽으로 시프트
  • ~x: 비트 반전

정수의 비트관련 연산

  • bin(n): 2진수 문자열 반환 (양수기준)
>>> n = -37
>>> bin(n)
'-0b100101'
  • n.bit_length(): 비트수 반환 (0인경우 0)
>>> n.bit_length()
6
  • n.bit_count(): 비트 1 갯수 반환
>>> n = 19
>>> bin(n)
'0b10011'
>>> n.bit_count()
3
# 동일코드
>>> bin(n).count("1")

실수 정수인지 여부

>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False

시퀀스 연산

  • x in s: s 내 x값 존재여부
  • x not in s: s 내 x값 없는지 여부
  • s + t: 두 시퀀스 붙이기
  • s * n: s를 n번 붙이기
  • s[i:j]: i 에서 j-1까지의 슬라이스
  • s[i:j:k]: i 에서 j-1까지 k구간 슬라이스
  • len(s): 시퀀스 길이
  • min(s): 최소값
  • max(s): 최대값
  • s.count(x): x 개수

얕은복사 주의

# 같은 리스트가 3번 복제되기 때문에 발생하는 문제
>>> lists = [[]] * 3
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]
# for in range 를 통해 리스트를 n번 만들어 해결
>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists
[[3], [], []]

Python 내장형

삼항연산자

>>> small = x if x < y else y

2차원배열 생성

>>> w, h = 2, 3
>>> A = [[]*w for i in range(h)]
>>> A[0] = [0, 1]
>>> A
[[0, 1][][]]

Python 다차원리스트

Python 자료구조

list

  • list.append(x) 값 추가
    • a[len(a):] = [x]
    • a.insert(len(a), x)
  • list.extend(iterable) 리스트 확장
  • list.insert(i, x) i 위치에 값 추가
  • list.remove(x) 첫번째 항목 삭제 (없으면 ValueError 발생)
  • list.pop(i) i 위치값 제거 후 반환
  • list.pop() 마지막값 제거 후 반환
  • list.clear() 모든값 제거
    • del a[:]
  • list.index(x) 첫번째 동일값 인덱스 반환
  • list.index(x, 4) 인덱스 4부터 첫번재 동일값 인덱스 반환
  • list.count(x) 값 개수 반환
  • list.sort(*, key=None, reverse=False) 정렬
  • list.reverse() 역순 정렬
  • list.copy() 얕은 복사본 반환
    • a[:]
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # Find next banana starting at position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'

Python 자료구조

list 컴프리헨션

제곱수 리스트

squares = [x**2 for x in range(10)]

튜플 리스트 (for, if)

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

flatten

>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [v for ve in vec for v in ve]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
# for ve in vec for v in ve 동일코드
>>> for ve in vec:
        for v in ve:
            list.append(v)

Python 자료구조

Stack with list

  • append(x) 값추가
  • pop() 마지막값 제거
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

Python 자료구조

Queue

from collections import deque

  • append(x) 값 추가
  • popleft() 왼쪽 값 제거 및 반환
  • appendleft(x) 왼쪽에 값 추가
  • pop() 오른쪽 값 제거 및 반환
  • clear() 전체 제거
  • copy() 얕은 복사본 반환
  • count(x) x와 같은 값의 수 반환
  • extend(iterable) 오른쪽에 값들 추가
  • extendleft(iterable) 왼쪽에 값들 추가 (역순으로)
  • index(x) x의 첫번째 위치 반환
  • insert(i, x) i 위치에 값 추가
  • remove(x) 첫번째 항목 제거
  • reverse() 순서 뒤집기
  • reversed(deque) 순서 뒤집어진 deque 반환
  • rotate(1) 우측방향으로 1씩 이동
>>> from collections import deque

>>> d = deque('ghi')                 # make a new deque with three items
>>> for elem in d:                   # iterate over the deque's elements
        print(elem.upper())
G
H
I

>>> d.append('j')                    # add a new entry to the right side
>>> d.appendleft('f')                # add a new entry to the left side
>>> d                                # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])

>>> d.pop()                          # return and remove the rightmost item
'j'
>>> d.popleft()                      # return and remove the leftmost item
'f'
>>> list(d)                          # list the contents of the deque
['g', 'h', 'i']
>>> d[0]                             # peek at leftmost item
'g'
>>> d[-1]                            # peek at rightmost item
'i'

>>> list(reversed(d))                # list the contents of a deque in reverse
['i', 'h', 'g']
>>> 'h' in d                         # search the deque
True
>>> d.extend('jkl')                  # add multiple elements at once
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> d.rotate(1)                      # right rotation
>>> d
deque(['l', 'g', 'h', 'i', 'j', 'k'])
>>> d.rotate(-1)                     # left rotation
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])

>>> deque(reversed(d))               # make a new deque in reverse order
deque(['l', 'k', 'j', 'i', 'h', 'g'])
>>> d.clear()                        # empty the deque
>>> d.extendleft('abc')              # extendleft() reverses the input order
>>> d
deque(['c', 'b', 'a'])

메서드 연쇄 가능

>>> d->insert("a")->remove("b")->sort();

Python Deque

tuple

쉼표로 구분되는 여러값 (불변)

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
# t[0] = 0 불가 (불변)

중첩 가능

# Tuples may be nested:
>>> u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))

튜플은 불변이나, 튜블은 가변 object를 지닐 수 있다.

# but they can contain mutable objects:
>>> v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])

Python 자료구조

sets

중복 요소가 없는 순서 없는 컬렉션 (집합)

빈집합 생성

>>> s = set()

요소들로 집합 생성

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}

string 값으로 집합 생성

>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
{'a', 'r', 'b', 'c', 'd'}

요소 존재여부

>>> 'orange' in basket                 # fast membership testing
True
>>> 'crabgrass' in basket
False

집합간 연산

# Demonstrate set operations on unique letters from two words
>>> a - b                              # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b                              # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # letters in both a and b
{'a', 'c'}
>>> a ^ b                              # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}

집합 컴프리헨션

>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

Python 자료구조

dictionary

숫자들로 인덱싱되는 시퀀스와 달리 키로 인덱싱
키: 숫자, 문자열, 불변 튜플 (숫자, 문자열, 튜플들만 포함된)

빈 딕셔너리 생성

>>> d = {}

딕셔너리 생성 및 값 추가

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}

딕셔너리 값 반환

>>> tel['jack']
4098

딕셔너리 값 제거

>>> del tel['sape']

딕셔너리 key 리스트

>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> list(tel)
['jack', 'guido', 'irv']

딕셔너리 정렬된 key 리스트

>>> sorted(tel)
['guido', 'irv', 'jack']

딕셔너리 key값 존재여부 확인

>>> 'guido' in tel
True
>>> 'jack' not in tel
False

딕셔너리 튜플배열로 생성

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}

딕셔너리 간단한 문자열 key일 경우 생성방식

>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'guido': 4127, 'jack': 4098}

Python 자료구조

Python 알고리즘

get index

배열 내에서 특정값 인덱스 찾기

>>> a = [123, 421, 212, 11, 24, 102, 29, 92, 10]
>>> a.index(421)
1

>>> b = ['hi', 'hello', 'bye', 'hello', 'hi']
>>> b.index('hello')
1

배열 내에서 중복되는 원소들의 인덱스 모두 찾기

>>> import numpy
>>> b = numpy.array(b)
>>> numpy.where(b == 'hello')[0]
array([1, 3])

Python Index

sort, sorted

sort: 리스트를 정렬된 상태로 변경
sorted: 정렬된 새로운 리스트를 생성 후 반환

>>> myList = [4, 2, 3, 5, 1]
>>> myList.sort()
>>> myList
[1, 2, 3, 4, 5]

>>> sorted([4, 2, 3, 5, 1])
[1, 2, 3, 4, 5]

sort: 리스트용 메소드
sorted: 이터러블 객체 가능 (딕셔너리 객체)

>>> sorted({3: 'D', 2: 'B', 5: 'B', 4: 'E', 1: 'A'})
[1, 2, 3, 4, 5]

key 매개변수로 정렬기준 설정

>>> students = [
        ('홍길동', 3.9, 2016303),
        ('김철수', 3.0, 2016302),
        ('최자영', 4.3, 2016301),
]
>>> sorted(students, key=lambda student: student[2])
[('최자영', 4.3, 2016301), ('김철수', 3.0, 2016302), ('홍길동', 3.9, 2016303)]

내림차순 정렬

>>> sorted(students, key=lambda student: student[2], reverse=True)
[('홍길동', 3.9, 2016303), ('김철수', 3.0, 2016302), ('최자영', 4.3, 2016301)]

Python sort, sorted

del

특정위치값 제거

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]

범위 제거

>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]

Python 자료구조

looping

딕셔너리.items() 를 통해 key, value 조회

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
        print(k, v)
gallahad the pure
robin the brave

enumerate(시퀀스) 를 통해 index, value 조회

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
        print(i, v)
0 tic
1 tac
2 toe

zip(시퀀스1, 시퀀스2) 를 통해 동시 조회

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
        print('What is your {0}?  It is {1}.'.format(q, a))
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

reversed(시퀀스) 를 통해 역방향 조회

>>> for i in reversed(range(1, 10, 2)):
        print(i)
9
7
5
3
1

set(), sorted() 를 통해 중복제거 및 정렬 조회

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
        print(f)
apple
banana
orange
pear

Python 자료구조

and, or

and 와 or 는 short-circuit 연산자 (왼쪽에서 오른쪽으로 값이 구해지고, 결과가 결정되면 뒷 연산자는 무시)

>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'

Python 자료구조

자료구조

Priority Queue

우선순위가 높은 데이터가 먼저 나오는 자료구조
Heap 으로 PriorityQueue 구현

  • enqueue(): PQ에 값 삽입 O(logN)
  • dequeue(): PQ 우선순위 높은 데이터 삭제 및 반환 O(logN)
  • peek(): PQ 우선순위 높은 데이터 반환
profile
 iOS Developer

0개의 댓글