본문 바로가기
SWE/코테

Python 사용 모음

by S나라라2 2022. 3. 2.
반응형

  • recursion limit
import sys
sys.setrecursionlimit(2000)

  • 사용자 입력받기
# 사용자 입력받기
i = input() #default: str

# Integer로 변환하기
num = int(input())

# integer list 입력받기
#띄어쓰기로 값들 구분되어짐
arr = list(map(int, input().split()))

# str list 입력받기
strArr = list(map(str, input().split())

  • int list -> string
arr = [1,2,3]

# 방법 1
strArr = list(map(str, arr))
print(strArr) 				# ['1', '2', '3']
print(''.join(strArr))			 # 123



# 방법 2
strArr = [str(i) for i in arr]
print(strArr)				# ['1', '2', '3']
print(''.join(strArr))			# 123

  • string list -> int list
arr = ['1','2','3']
print(arr)					# ['1', '2', '3']

intArr = list(map(int, arr))
print(intArr)				# [1, 2, 3]

  • list 초기화
arr = [0]*3
#[0,0,0]

  • 2차원 리스트 N*M

N,M = 3,5

arr = [[0]*M for _ in range(N)]
# [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

  • dictionary 만들기
>>> dic = {'name':'pey', 'phone':'0111111111'}
>>> a = {1: 'hi'} # int : string
>>> a = {'a' : [1,2,3]} # value = list
  • dictionary 추가하기
# 추가하기
>>>a = {1:'a'}
>>>a[2] ='b'
>>>a
{1: 'a', 2:'b'}

>>>a['name']='pey'
>>>a
{1:'a', 2:'b', 'name':'pey'}

>>>a[3]=[1,2,3]
>>>a
{1:'a', 2:'b', 'name':'pey', 3:[1,2,3]}
  • dictionary 삭제하기
>>> del a[1]
>>> a
{2: 'b', 'name': 'pey', 3: [1, 2, 3]}

dic.keys()
dic.values()
a['nokey'] -> return error
a.get('nokey') -> return None
a.get('nokey', 'default')
출처 : https://wikidocs.net/16

  • dictionary muliple value - defaultdict 모듈 사용 -> 2차원 배열로도 사용할 수 있음
from collections import defaultdict

d = defaultdict()

#setdefault() 메서드를 사용하여 사전의 특정 키에 여러 값 추가
for i in range(10):
    d.setdefault(0,[]).append(i) # key:0 value: 0~9
 
for j in range(10, 30, 10): 
    d.setdefault(1,[]).append(j) #key:1 value: 10~20
    
for k in range(1000, 4000, 1000): 
    d.setdefault(3,[]).append(k) #key:3 value: 1000~3000

print(d)
'''
output
defaultdict(None, {0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 1: [10, 20], 3: [1000, 2000, 3000]})
'''


for key in d :
    print(f'key {key} : ')
    for value in d[key]:
       print(value,end=' ') 
    print('')
'''
output
key 0 : 
0 1 2 3 4 5 6 7 8 9 
key 1 : 
10 20 
key 3 : 
1000 2000 3000
'''

https://www.delftstack.com/ko/howto/python/dictionary-with-multiple-values-in-python/

  • dictioanry 초기화. 줄바꿈없이 print
d = dict() # init dictionary (key,value)
d[3] = "I'm Hwayoung"
d[0] = "hello"

for key sorted(d) : #key기준으로 sorting 3, 0 -> 0, 3
	print(key, end=' ')
    print(d[key])
    
#key value 출력됨

  • split해서 변수로 -> hackerRanker compiler에서 split안됨
for item in queries :
	#operation, name = item.split() #error
	operation = item[0]
    name = item[1]
    if operation == 'add' :
    	# to do

  • define class
class Node(object):
	def __init(self, info=None, depth=0):
    	self.info = info
        self.left = None
        self.right = None
        self.depth = 1

  • heap - heapq 모듈 사용

-> 기본 min heap이기 때문에,
max heap을 원하면 값을 음수(-)로 넣어주고 빼서 사용할 때 다시 -처리해준다.

import heapq as hq

minq = []
maxq = []

hq.heappush(minq, value)
hq.heappush(maxq, -value)

minimum = hq.heqppop(minq)
maximum = hq.heappop(maxq)


DFS - Queue (FIFO)
BFS - Stack (LIFO)

  • queue - queue 모듈 사용
import queue

q = queue.Queue()
q.put(1)
q.put(2)
q.put(3)

while not q.empty() :
	num = q.get()
    print(num)
    
#output : 1 2 3

  • 10진수와 2진수 변환
# 10진수 13 -> 2진수
>>>bin(13) 
'0b1101'

# 2진수 1101 -> 10진수
>>> 0b1101
13
# 2진수 문자열 '1101' -> 10진수
>>> int('1101', 2)
13

# 16진수 문자열 -> 10진수
print(int('01', 16))  #1
print(int('10', 16))  #16
print(int('110', 16))  #272

# 2진수 문자열 -> 10진수
print(int('01', 2))  #1
print(int('10', 2))  #2
print(int('110', 2))  #6

  • 비트 논리 연산자
# AND
>>> bint(0b1101 & 0b1001)
'0b1001'
>>> 13 & 9
9

# OR
>>> bin(0b1101 | 0b1011)
'0b1101'
>>> 13 | 9
13

# XOR
>>> bin(0b1101 ^ 0b1001)
'0b100'
>>> 13 ^ 9
4

#NOT
>>> bin(~0b1101)
'-0b1110'
>>> ~13
-14



아래 링크 더 참고하기
https://hkim-data.tistory.com/30?category=1016184

#1 Python 코딩테스트 대비 여러 Tip 정리

https://www.youtube.com/watch?v=m-9pAwq1o3w&list=PLRx0vPvlEmdAghTr5mXQxGpHjWqSz0dgC&index=2 이 포스트는 위의 영상을 보고 제가 필요하다고 생각된 부분을 정리한 포스팅 입니다. - 실수형 데이터의 경우,..

hkim-data.tistory.com

반응형