Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

:)

python 문법 for algorithm 본문

Algorithm(python)

python 문법 for algorithm

mihee 2022. 8. 2. 07:12

함수

import math

nums = [1,2,3,4]
print(math.prod(nums)) ## 곱셈 = 24
print(math.factorial(4)) ## 팩토리얼 4! = 24
print(math.comb(4,2)) ##조합 4C2 = 6
print(int(1.7))  # 내림 = 1
print(math.ceil(1.3))  # 올림 = 2
print(round(1.72))   # 반올림 = 2

float('inf') # 무한대 : inf

str

print("hello" + "world") # helloworld
print("hello" * 3) # hellohellohello
print("hello" in 'aagainhelloworld") # True

str - 함수


## check
print('alphabet'.isalpha()) # 알파벳으로 이루어져 있나? : True
print('12345'.isdigit()) # 숫자로 이루어져 있나? : True
print('PYTHON'.isupper()) # 대문자인가? : True
print('python'.islower()) # 소문자인가? : True
print('alphabet'.startswith('alpha')) # 이 str으로 시작하는기? : True
print('endswith'.endswith('with')) # 이 str으로 끝나는가? : True


## convert
print('python'.upper()) # PYTHON
print('PYTHON'.lower()) # python

## substitution
print('i dont want any spaces'.replace(' '. '')) # 공백 제거 : idontwantanyspaces
print('you still my number one'.replace('one', '1')) # you still my number 1

## strip
print('  python   \n'.strip()) # 양 옆 공백제거
print('python...'/strip('.')) # python
print('   python    \n'.rstrip()) # 오른쪽 공백만 제거 :    python

자료형

List


l = [0,1,2,3,4,5,6,7]
print(l + [8,9,10]) # extend
print(l*3) # mul
print(1 in l) # True
print(l[2:6:2]) # slicing : [2,4]

## 함수

l = [5,3,1,4]

l.append(10) # [5,3,1,4,10]

popped = l.pop() # 10 , l : [5,3,1,4]

l.sort() # sorted(l) : [1,3,4,5]

Tuple

  • list와 비슷
  • immutable, append pop (x)
  • dictionary, set에 넣을 수 있음
d = {[1,0] : True}  # X, list는 unhashable

d = {(1,0) : True}  # 이럴때만 tuple 사용

set (집합)

  • 중복 X
s1, s2 = {1,2,3,4}, {3,4,5,6}
print(s1 & s2) # 교집합 : {3,4}
print(s1 | s2) # 합집합 : {1,2,3,4,5,6}
print(s1 - s2) # 차집합 : {1,2}
print(1 in s1) # True


s = {1,2,3,4}

s.add(5) # append

s.remove(5) # pop


print(s.issubset({1,2,3,4,5,6}) # 부분집합인가?
print(s.issuperset({1,2}) # 모집합인가?
  • list보다 in 연산이 빠름, in 연산을 자주하면 set, dictionary 같은 hash 자료구조를 쓰는게 좋음
s = set(range(10000))

import random
n = random.randint(0,99999)

%%tine
n in l

dictionary

d = {'a' : 1, 'b' : 2}

d['c'] = 3 # adad

del d['c'] # remove

print('a' in d) # in : True


d1 = {'a':1, 'b':2}
d2 = {'b':3, 'c':4}

d1.update(d2) # {'a':1, 'b':3, 'c':4}

Defaultdict

from collections import defaultdict

d = defaultdict(int)
d['sdf']  # : 0

vacab = ['apple', 'banana', 'angle', 'ant', 'boat'] -> {'a': ['apple', angle', 'ant'], 'b':['banana', 'boat']

d = dict()

for word in vocab:
    if word[0] in d:
        d[word[0]].append(word)
    else:
        d[word[0]] = [word]
dd = defaultdict(list)  # 초기화를 list로 해줌

for word in vocab:
    dd[word[0]].append(word)

Counter

animals = ['cat', 'dog', 'dog', 'cat', 'cat'] ---> {'cat':3, 'dog':2}

cntr = defaultdict(int)

for animal in animals:
    cntr[animal] +=1

다음처럼 Counter 함수로 작성가능

from collections import Counter

c = Counter(animals)
more_items = ['elephant', 'dog', 'dog']

c.update(more_items) 
c ## Counter({'cat':3, 'dog':4, 'elephant':1})

c.most_common() # [('dog',4),('cat',3), ('elephant'.1)] # 가장 많이 나오는 순으로 정렬

deque

  • 양끝 삽입 삭제 O(1)
  • lineked list로 구성되어 있어서 index 속도는 list보다 떨어진다
from collections import deque

dq = deque([0,1,2,3,4])

dq.appendleft(5) # [5,0,1,2,3,4]
dq.popleft() # [0,1,2,3,4]

heapq

  • min 값을 빼내야 할때
  • max 값을 구할때는 음수로 값을 변환해 사용
from heapq import heapify, heappop, heappush

# heapify
l = [1,5,2,7,9,10]
heapify(l) # [1,5,2,7,9,10]

# add
heappush(l,0) # [0,5,1,7,9,10,2]

min_item = heappop(l) # 0, l : [1,5,2,7,9,10]

unpacking

l = ['apple', 'banana', 'carrot']
print(l) # : ['apple', 'banana', 'carrot']
print(*l) # : apple banana carrot

List Comprehension

# 10개 제곱수

res = []
for i in range(10):
    res.append(i*i)
print(res)

[i*i for i in range(10)]


res = []
for i in range(3):
    for j in range(3):
        if i != j:
            res.append((i,j))

print(res)

res = [(i,j) for i in range(3) for j in range(3) if i != j]

zip

ids = [1001, 1002, 1003]
names = ['A', 'B','C']
grades = [94, 90, 92]

for i in range(len(names)):
    print((ids[i], names[i], grades[i]))

# (1001, 'A', 94)
# (1002, 'B', 90)
# (1003, 'C', 92)

for record in zip(ids, names, grades):
    print(record)
  • 학생의 평균점수

scores = {'math':[60,30,90], 'english':[80,90,70], 'korean':[50,60,70]}

for x in zip(*scores.values()):
    print(x, sum(x)/3)
# (60,80,50), 63.3
# (30,90,60), 60.0
# (90,70,70), 83.3

enumerate

l = ['a', 'b', 'c', 'd']
for i, x in zip(range(len(l)), l):
    print(i,x)

# 0 a
# 1 b
# 2 c
# 3 d

for i, x in enumerate(l):
    print(i,x)

brute force

product

from itertools import product

top = ['반팔', '나시', '가디건']

for p in product(top, top,top):
    print(p)

# 중복순열 결과

permutation (순열) : 순서를 고려해 뽑는 경우

from itertools import permutations

top = ['반팔1', '반팔2', '반팔3', '나시1', '나시2', '나시3']
for p in permutations(top, 5)
    print(p)

combinations(조합) : 순서 고려 X

from itertools import combinations

for x in combinations(top, 3):
    print(x)

combinations with replacement (중복조합)

# 같은 옷을 여러가 살 수 있다. 5개를 살때 경우의 수

from itertools importr combinations_with_replacement

top = ['반팔1', '반팔2', '반팔3']

for c in combinations_with_replacement(top, 5):
    print(c)
Comments