목록Coding test(Python3)/Programmers (115)
NIRVANA
문제 문자열 s에 나타나는 문자를 큰것부터 작은 순으로 정렬해 새로운 문자열을 리턴하는 함수, solution을 완성해주세요. s는 영문 대소문자로만 구성되어 있으며, 대문자는 소문자보다 작은 것으로 간주합니다. 문제 풀이 접근법1 1) 문자열을 리스트로 형변환한다. 2) sort()를 사용하여 내림차순 정렬한다. 3) join()를 사용하여 리스트를 문자열로 합친뒤 반환한다. def solution(s): answer = '' list_s = list(s) list_s.sort(reverse=True) answer = ''.join(list_s) return answer sort()를 사용하면 대문자도 고려해서 정렬해준다는 걸 오늘 처음 알았다! 신기해 다른 분들 풀이 def solution(s): r..
문제 두 정수 left와 right가 매개변수로 주어집니다. left부터 right까지의 모든 수들 중에서, 약수의 개수가 짝수인 수는 더하고, 약수의 개수가 홀수인 수는 뺀 수를 return 하도록 solution 함수를 완성해주세요. 문제 접근법1 1) for문으로 left-right까지 반복한다 2) 이중 반복문을 사용하여 i % j 로 약수를 확인한다 (이때, j는 1부터 자기자신(i)+1까지 증가한다) 3) i % j == 0이면 count에 1을 더한다 4) count가 짝수이면 answer에 i를 더하고 count가 홀수이면 answer에 i를 뺀다. def solution(left, right): answer = 0 for i in range(left, right+1): count = 0 ..
문제 길이가 같은 두 1차원 정수 배열 a, b가 매개변수로 주어집니다. a와 b의 내적을 return 하도록 solution 함수를 완성해주세요. 이때, a와 b의 내적은 a[0]*b[0] + a[1]*b[1] + ... + a[n-1]*b[n-1] 입니다. (n은 a, b의 길이) 문제 풀이 접근법1 1) 리스트 a와 b의 길이 만큼 반복문을 진행하며 a[i]와 b[i]를 곱한뒤, 해당 값을 answer에 더한다. def solution(a, b): answer = 0 for i in range(len(a)): answer = answer + (a[i] * b[i]) return answer 다른 분들 풀이 def solution(a, b): return sum([x*y for x, y in zip(..
문제 길이가 n이고, "수박수박수박수...."와 같은 패턴을 유지하는 문자열을 리턴하는 함수, solution을 완성하세요. 예를들어 n이 4이면 "수박수박"을 리턴하고 3이라면 "수박수"를 리턴하면 됩니다. 문제 풀이 접근법1 1) 반복문으로 n만큼 반복하며 리스트에 '수' or '박'을 추가한다. 2) 이때, (for문을 기준으로) i가 짝수이면 리스트에 '수'를, i가 홀수이면 리스트에 '박'을 추가한다. 3) 리스트를 str로 변환한 뒤 반환한다. def solution(n): answer = [] for i in range(n): if i % 2 == 0: answer.append('수') else: answer.append('박') arr = ''.join(answer) return arr 다..
문제 단어 s의 가운데 글자를 반환하는 함수, solution을 만들어 보세요. 단어의 길이가 짝수라면 가운데 두글자를 반환하면 됩니다. 문제 풀이 접근법1 1) String s를 list로 변환 2) list의 길이 / 2로 중간이 되는 위치 파악 홀수: (list의 길이) // 2 짝수: (list의 길이) //2, (list의 길이 ) // 2 -1 3) 중간이 되는 곳의 글자 반환 홀수: 그냥 반환 짝수: 글자를 list에서 str형으로 바꾼 뒤 반환 def solution(s): answer = '' posi = [] arr = [] arr = list(s) if len(arr) % 2 != 0: posi = len(arr) // 2 answer = arr[posi] else: posi.appe..
문제 정수를 저장한 배열, arr 에서 가장 작은 수를 제거한 배열을 리턴하는 함수, solution을 완성해주세요. 단, 리턴하려는 배열이 빈 배열인 경우엔 배열에 -1을 채워 리턴하세요. 예를들어 arr이 [4,3,2,1]인 경우는 [4,3,2]를 리턴 하고, [10]면 [-1]을 리턴 합니다. 문제 풀이 접근법 1 1) 리스트 arr의 길이가 1보다 큰지 확인한 뒤, 1보다 작다면 answer에 -1을 추가한다. 2) 반복문에서 원소를 비교하며 min값을 찾는다. 3) 찾은 min값을 remove()를 사용하여 제거한다 4) answer리스트를 반환한다. def solution(arr): answer = [] min = 100 if len(arr)