본문 바로가기

algorithm13

[알고리즘] 알파벳 찾기 백준 10809 (Python) 알파벳 개수 찾는 문제와 거의 동일하다. 리스트를 -1로 초기화하고 해당 알파벳의 인덱스에 입력받은 알파벳의 인덱스 값을 넣어주면 된다. 코드 import sys alphabet =[-1] * 26 str = sys.stdin.readline().rstrip() for i in range(len(str)): if(alphabet[ord(str[i]) - 97] == -1 ): alphabet[ord(str[i]) - 97] = i print(*alphabet) 입출력 2022. 1. 17.
[알고리즘] 알파벳 개수 백준 10808 (Python) 알파벳 하자마자 아스키 코드가 생각났다. 파이썬에선 아스키코드 값을 반환하는 내장함수 ord()가 존재한다. 틀린 코드 import sys alphabet =[0] * 26 str = sys.stdin.readline() for i in str: alphabet[ord(i) - 97] += 1 print(*alphabet) 입출력 문자열을 입력받을 때 sys.stdin.realine().rstrip()으로 바꿔주니 문제가 해결됐다. 코드 import sys alphabet =[0] * 26 str = sys.stdin.readline().rstrip() for i in str: alphabet[ord(i) - 97] += 1 print(*alphabet) 입출력 아 그리고 처음엔 리스트를 공백으로 구분하.. 2022. 1. 17.
[알고리즘] 덱 백준 10866 (Python) 큐와 비슷하지만 덱은 양쪽에서 push, pop이 가능하다. 코드 import sys n = int(input()) deque = [] for i in range(n): command = sys.stdin.readline().split() if command[0] == 'push_front' : deque.insert(0,command[1]) elif command[0] == 'push_back' : deque.append(command[1]) elif command[0] == "pop_front" : if len(deque) == 0 : print(-1) else : print(deque.pop(0)) elif command[0] == "pop_back" : if len(deque) == 0 : pri.. 2022. 1. 16.
[알고리즘] K번째 수 백준 11004 (Python) 코드 import sys n, k = map(int, input().split()) arr = list(map(int,input().split())) arr.sort() print(arr[k-1]) 입출력 2022. 1. 14.
[알고리즘] 카드 백준 11652 (Python) 처음에는 길이가 n인 배열을 선언해서 카드 숫자에 해당하는 인덱스에 +1을 하려 했다. 하지만 sort함수를 사용하면 카드 숫자와 상관없이 정렬이 되어 정답이 0으로만 나온다. 이 문제를 해결하기 위해서 dictionary를 사용했다. 코드 import sys n = int(sys.stdin.readline()) card = {} for i in range(n): key = int(sys.stdin.readline()) if key in card.keys(): card[key] += 1 else: card[key] = 1 card = sorted(card.items(), key = lambda x : (-x[1], x[0])) print(card[0][0]) 입출력 2022. 1. 14.
[알고리즘] 2xn 타일링 백준 11726 (Python) 문제 2×n 크기의 직사각형을 1×2, 2×1 타일로 채우는 방법의 수를 구하는 프로그램을 작성하시오. 아래 그림은 2×5 크기의 직사각형을 채운 한 가지 방법의 예이다. 입력 첫째 줄에 n이 주어진다. (1 ≤ n ≤ 1,000) 출력 첫째 줄에 2×n 크기의 직사각형을 채우는 방법의 수를 10,007로 나눈 나머지를 출력한다. 코드 n = int(input()) dp = [0]*1001 dp[1] = 1 dp[2] = 2 for i in range(3, n+1): dp[i] = dp[i-1] + dp[i-2] print(dp[n]%10007) 2022. 1. 12.