본문 바로가기

Programming/Programmers

(40)
[프로그래머스/Python] 타겟넘버(DFS) 전형적인 DFS 문제다. 그나저나 전역변수 쓰는법 몰라서 오래 걸렸다. answer = 0 def dfs(numbers, target, cnt, num): global answer if cnt == len(numbers): if num == target: answer+=1 return dfs(numbers,target,cnt+1,num+numbers[cnt]) dfs(numbers,target,cnt+1,num-numbers[cnt]) return def solution(numbers, target): global answer dfs(numbers, target, 0, 0) return answer
[프로그래머스/Python] K번째수(정렬) def solution(array, commands): answer = [] for i in commands: tmp = array[i[0]-1:i[1]] tmp.sort() answer.append(tmp[i[2]-1]) return answer
[프로그래머스/Python] 모의고사(단순구현) def correct_counter(supoza, answers): cnt=0 for i in range(len(answers)): if answers[i] == supoza[i%len(supoza)]: cnt+=1 return cnt def solution(answers): supoza1 = [1, 2, 3, 4, 5] supoza2 = [2, 1, 2, 3, 2, 4, 2, 5] supoza3 = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5] cnt=[] cnt.append(correct_counter(supoza1,answers)) cnt.append(correct_counter(supoza2,answers)) cnt.append(correct_counter(supoza3,answers))..
[프로그래머스/Python] 카펫(소인수분해) brown yellow 24 24 1. yellow가 만들어 낼 수 있는 모든 경우의 수를 탐색해야한다. -> 소인수분해로 만들 수 있는 사각형 찾아낸다. (1, 24) (2, 12) (3, 8) (4, 6) 2. 각 사각형에 대해서 테두리갯수를 구하고 brown이랑 같으면 그때의 사각형을 sort해서 return import math def get_divisor(num): divisors = [] length = int(math.sqrt(num))+1 for i in range(1,length): if num%i == 0: a =(i, num//i) divisors.append(a) return divisors def solution(brown, yellow): answer = [] tmp = get_..
[프로그래머스/Python] 완주하지 못한 선수(해쉬) 참가자들을 key값으로 등장횟수를 count해서 딕셔너리에 담아주는 Counter함수를 사용하자. 여기서 completion이 등장할 때마다 빼주면 마지막에 count=1인 놈이 혼자 남은 놈 import collections def solution(participant, completion): answer = '' dict_p = collections.Counter(participant) for i in completion: if i in dict_p: dict_p[i] -=1 for i in dict_p: if dict_p[i] == 1: answer = i return answer 더 짧게 풀 수 있네.. import collections def solution(participant, complet..
[프로그래머스/Python] 소수찾기(소수/순열/중복제거) from itertools import permutations def isPrime(num): if num < 2: return False for i in range(2,num): if num%i==0: return False return True def solution(numbers): answer = [] for k in range(1, len(numbers)+1): perlist = list(map(''.join, permutations(list(numbers), k))) for num in list(set(perlist)): if isPrime(int(num)): answer.append(int(num)) return len(set(answer))
[프로그래머스/Python] 전화번호 목록(효율성) 1) 부르트 포스 접두사가 같은게 하나라도 발생하면 False이므로 이것을 검사하여 걸리면 바로 break한다. def solution(phone_book): answer = True for i in range(len(phone_book)): for j in range(i+1, len(phone_book)): if phone_book[j].find(phone_book[i]) == 0 or phone_book[i].find(phone_book[j])== 0: answer=False break return answer 2) sort하면 for문을 한번만 거치고 짧은 거 기준으로만 비교하면 된다. def solution(phone_book): answer = True phone_book = sorted(pho..
[프로그래머스/C++] 가장 큰 수(정렬) 예외처리만 주의하자.. #include #include #include #include using namespace std; bool greater_str(string a, string b){ return a+b > b+a; } string solution(vector numbers) { string answer = ""; vector a; for(int i=0;i