파이썬 함수 팁
2022. 8. 29. 11:31ㆍ대학원 입시/알고리즘
collections - Counter, deque, defaultdict, ordereddict
itertools - combinations, combinations_with_replacement, permutations, product
reduce, filter, operator
from functools import reduce
import operator
a = list(range(10))
print(a)
r = reduce(lambda x, y: x + y, a)
print(r)
b = reduce(operator.add, a)
print(b)
c = list(filter(lambda x: x > 5, a))
print(c)
zip으로 행 열 바꾸기
list( zip(*A))
객체복사
import copy
a = b.copy
a = b.deepcopy
a = b[:]
a = [k[:] for k in b]
b = [[i for i in range(5)] for _ in range(5)]
print(b)
a = b
a[0][0] = 5
print(a[0][0], b[0][0])
a = [k[:] for k in b]
a[0][0] = 7
print(a[0][0], b[0][0])
a = copy.deepcopy(b)
a[0][0] = 1
print(a[0][0], b[0][0])
sort시 Lambda 사용
import random
a = [ (i,random.randint(1,40)) for i in range(20)]
print(a)
a = sorted(a, key = lambda x : (-x[1],x[0]))
print(a)
a.sort(key = lambda x : (x[0],-x[1]))
print(a)
진법 변환
https://security-nanglam.tistory.com/508
2진법, 8진법, 16진법
11진법 이상 (문자 사용시)
import string
def convert_recur(num, base):
number = string.digits + string.ascii_uppercase
q, r = divmod(num, base)
return convert_recur(q, base) + number[r] if q else number[r]
10진법 이하
answer = ''
while n > 0:
d = n % k
n //= k
answer += str(d)
answer = answer[::-1]
파이썬 내장함수
bin(87), oct(87), hex(87) ## -> bin(87)[2:] 0b1010111에서 0b 제거
n진법-> 10진법
int(str,n) ## 10진법으로 변환
any(), all()
https://blockdmask.tistory.com/430
bisec
https://programming119.tistory.com/196
import bisect
a = [ i for i in range(20)]
left = bisect.bisect_left(a,10)
right = bisect.bisect_right(a,10)
left = bisect.bisect_left(a,10,lo = 8,hi = 11) # 탐색 범위 설정 lo, hi
right = bisect.bisect_right(a,10,lo = 8,hi = 11) # 탐색 범위 설정 lo, hi
print(left, right)
print(a)