기술(Tech, IT)/파이썬(Python) 25

[Python] deque(데크)

GeeksforGeeks에 따르면 Deque에 대한 설명은 아래와 같다. :Deque (Doubly Ended Queue) in Python is implemented using the module “collections“. Deque is preferred over a list in the cases where we need quicker append and pop operations from both the ends of the container, as deque provides an O(1) time complexity for append and pop operations as compared to a list that provides O(n) time complexity. : "colletions..

[Python] for문(for loop)

파이썬의 for문은 C언어의 for문과 다르다. C언어에 익숙해 같은 방식으로 선언하니 결과가 다르게 나와 파이썬에서 for문의 원리를 찾아봤거 파이썬 위키에서 차이점을 알게 됐다. 파이썬 위키 설명 중 아래와 같은 문구가 있다. for loops are used when you have a block of code which you want to repeat a fixed number of times. 파이썬의 for문은 고정된 횟수만큼 반복된다. 다음 예시에서 C언어와 차이를 확연하게 확인할 수 있다. 1. C언어(C language) for(i=0; i

[Python] 다중 반복문(multiple loops) 탈출

한 개의 반복문 탈출 시엔 필요한 조건에서 break를 통해 바로 빠져나갈 수 있지만, 다중 반복문에선 그게 불가능하다. 다음은 다중 반복문을 탈출할 수 있는 세 가지 방법이다. 1. flag 사용 : 아래와 같이 flag를 사용한다면 다중 반복문에서 flag를 매 반복문마다 확인해 break를 선언한다면 탈출이 가능하다. i = flag = 0 while i < 5: for j in range(5): if j%2 == 1: print(j) flag = 1 break print(j) if flag == 1: break 실행 결과: 0 1 2. 예외 처리(except) : 아래와 같이 except 처리를 통해서도 다중 반복문을 탈출할 수 있다. class LoopBreak(Exception): pass t..

[Python] pass vs continue vs break

파이썬 알고리즘 문제를 풀던 중 이중 반복문을 탈출하는 방법을 구글링하다 error를 발생시켜 탈출하는 방법을 알게 됐고, 예시에서 pass를 알게 됐다. 다음은 해당 예시다. class LoopBreak(Exception): pass try: for i in range(5): for j in range(5): if i == 1 and j == 1: raise LoopBreak() except LoopBreak: pass W3Schools에 따르면 pass의 정의는 다음과 같다. pass : The pass statement is used as a placeholder for future code. When the pass statement is executed, nothing happens, but y..