파이썬 라이브러리

원종서·2022년 2월 19일
0
import sys

# numbers = sys.stdin.readline().rstrip()

print("A")

# library

# inner func

# 1.

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

result2 = min(5,3)  #max(5,3) -> 5
print(result2)

result3 = eval("(3+5) * 7")
print(result3)

result4 = sorted([9,1,43,5,2])
print(result4)
result5 = sorted([9,1,43,5,2], reverse=True)
print(result5)

# 두번째 원소를 기준으로 내림차순

result6 = sorted([('홍길동', 35),('이순신', 75),('아무개', 50)] , key= lambda x: x[1], reverse=True)

print(result6)

# itertools

# permutations 는 리스트와 같은 iterable  객체에서 r 개의 데이터를 뽑아 일렬로 나열하는 모든 경우를 계산한다.
# combinations 는 리스트와 같은 iterable  객체에서 r 개의 데이터를 뽑아 순서를 고려하지 않고 일렬로 나열하는 모든 경우를 계산한다.
# product 는 리스트와 같은 iterable  객체에서 r 개의 데이터를 뽑아 일렬로 나열하는 모든 경우를 계산한다.


from itertools import permutations, combinations , product

data = ['A', 'B', 'C']

result7 = list(permutations(data,3))


print(result7)

print("----")

result8 = list(combinations(data,2))

print(result8)

# result9 = list(product(data,re))

# print("----")
# print(result9)

import heapq

def heapsort(iterablee):
    h = []
    result10 = []

    for value in iterablee :
        heapq.heappush(h,value)
        # heapq.heappush(h, -value)

    for value in range(len(h)):
        result10.append(heapq.heappop(h))
        # result10.append(-heapq.heappop(h))

    return result10

import bisect
# 이진탐색 , 정렬된 베열에서 특정한 원소 찾는데 매우 효율적.

from bisect import bisect_left, bisect_right

# bisect_left(a,x) = 정렬된 순서를 유지하면서 리스트 a에 x 를 삽입할 가장 왼쪽 인덱스틀 찾음


a = [1, 2 , 4, 4 ,8]
x = 4

print(bisect_left(a,x)) # 2
print(bisect_right(a,x)) # 4

#  정렬된 리스트에서 값이 특정 범위에 솏하는 원소의 개수 구할때 활용

# left_value <= x <= right_value  를 O(logN) 으로 찾음.

def count_by_range(b,left_value , right_value):
    right_index = bisect_right(b,  right_value)
    left_index = bisect_left(b, left_value)
    return right_index - left_index

b = [1,2,3,3,3,3,4,4, 8, 9]

print(count_by_range(b,4,4))  # 2
print(count_by_range(b,-1,3)) # 6

# deque 는 스택 혹은 큐 자료구조로 사용됨.

# 첫원소 제거 popleft, 마지막 원소 pop
# 첫번째 인덱스에 원서 삽입 appendleft , 마지막 인덱스에 삽입 append()
# deque를 큐로 이용할때는 append()popleft() 를 사용

from collections import deque

data3 = deque([2,3,4])
data3.appendleft(1)
data3.append(5)

print(data3) # 1,2,3,4,5

from collections import Counter

# Counter iterable 객체의 내부 원소가 몇번 등장했는지 알려줌.

counter = Counter(['red','blue','red','green','blue','blue'])

print(counter['blue'])  # 3
print(counter['green'])  # 1
print(dict(counter))  # {'red': 2, 'blue': 3, 'green': 1}

import math

print(math.factorial(5)) # 120

print(math.sqrt(49)) # 7.0

print(math.gcd(21,14)) # 7

0개의 댓글