목록프로그래밍/파이썬 (7)
어디까지 갈 수 있을까?
a='aa' print(a[0:3] + '|') print(a[3:5] + '|') print('|') 해당 코드를 돌릴 경우 에러가 날까? 답은 '에러가 나지 않는다' 이다 배열 a는 끝 인덱스가 1 임에도 불구하고, a[0:3]을 부르면 aa까지만 출력되고 a[3:5]를 부르면 아무것도 출력되지 않는다 그러므로 위의 코드의 전체적인 출력값은 aa| | | 이 된다. 관련된 stackoverflow의 답변에서는 stackoverflow.com/questions/9490058/why-does-substring-slicing-with-index-out-of-range-work Why does substring slicing with index out of range work? Why doesn't 'exa..
보통 본인이 선언한 변수명이 함수명과 일치할 때 생긴다 예를 들어 str='' print(str(11)) 이 코드의 경우 본인이 선언한 변수명 str과 사용하고자 하는 함수명 str()이 중복돼 오류가 생긴다
deque -선입선출 - BFS from collections import deque q=deque() q.append('l') q.popleft() heapq -최소힙, 최대힙 -다익스트라, 최소값이나 최대값을 빨리 찾아야 할 때 from heapq import heappush, heappop, heapify q=[] heappush(q, 1) heappop(q) heapify(arr)
1 2 3 4 5 from bisect import bisect_left, bisect_right nums = [4,5,5,6] n = 5 print(bisect_left(nums, n)) #1 print(bisect_right(nums, n)) #3 cs bisect_left는 정렬된 배열에서 n값이 들어갈 수 있는 가장 왼쪽 인덱스를 반환한다 bisect_right는 정렬된 배열에서 n값이 들어갈 수 있는 가장 오른쪽 인덱스를 반환한다 * 범위 안 수의 갯수를 구하고 싶을 때 1 2 3 from bisect import bisect_left, bisect_right nums = [4,5,5,6,6,7,8] print(bisect_right(nums, 7)-bisect_left(nums, 5)) #5 ..

[해결방법] invalid literal for int() with base 10: '\n' 오류 메시지가 난다면 1 2 3 4 import sys input=sys.stdin.readline a=input().rstrip() cs 이와 같이 끝에 rstrip()를 붙여주면 된다 [이유] 1 2 3 4 5 6 import sys input=sys.stdin.readline a=input() print(a) print('b') cs 프로그램을 돌리면 위와 같이 enter가 한 번 더 추가적으로 들어간다 그 이유는 sys.stdin.readline은 우리가 입력한 값을 모두 받기 때문에 문자열에 끝에 입력한 개행문자 (\n)도 같이 받는다. 이 때문에 끝에 rstrip()를 붙여주면 개행문자가 제거돼 정상적..
*중복 개수 찾기 : try-except 문 사용 1 2 3 4 5 6 count={} lists = ["a","a","b",'c','c','d'] for i in lists: try: count[i] += 1 except: count[i]=1 print(count) #{'a': 2, 'b': 1, 'c': 2, 'd': 1} cs 딕셔너리와 try-except 문을 사용하여 try : count[i] 값이 존재하면 +1, except : count[i]값이 존재하지 않으면 1 삽입 하는 형태로 생각하면 된다 1 print(count['a']) #2 cs 위와 같이, 원하는 값의 중복 개수를 찾아줄 수도 있다 *중복 요소 제거하기 : set 사용 1 2 3 4 5 6 7 8 lists = ["a","a"..