목록Coding test(Python3)/Programmers (115)
NIRVANA
문제 두 정수 a, b가 주어졌을 때 a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수, solution을 완성하세요. 예를 들어 a = 3, b = 5인 경우, 3 + 4 + 5 = 12이므로 12를 리턴합니다. 문제 풀이 접근법1 1) 정수 a, b를 비교하여 둘 중 작은 것을 반복문의 시작값으로, 큰 것을 끝값으로 둔다 2) 반복문을 진행하면서 answer 두 수 사이의 값을 더한다 def solution(a, b): answer = 0 if a > b: for i in range(b, a+1): answer = answer + i else: for i in range(a, b+1): answer = answer + i return answer 다른 분들 풀이 def adder(a, b): if..
문제 양의 정수 x가 하샤드 수이려면 x의 자릿수의 합으로 x가 나누어져야 합니다. 예를 들어 18의 자릿수 합은 1+8=9이고, 18은 9로 나누어 떨어지므로 18은 하샤드 수입니다. 자연수 x를 입력받아 x가 하샤드 수인지 아닌지 검사하는 함수, solution을 완성해주세요. 문제 풀이 접근법1 1) n→str→list 형으로 형변환 2) map()함수를 사용하여 list의 각 원소를 int로 형변환 3) sum()를 사용하여서 리스트의 각 원소의 합을 구함 4) x를 리스트의 원소의 합(각 자릿수를 합한 값)으로 나누어서 나누어 떨어지면 True, 아니면 False를 반환 def solution(x): answer = True number = list(str(x)) number = list(map..
문제 함수 solution은 정수 n을 매개변수로 입력받습니다. n의 각 자릿수를 큰것부터 작은 순으로 정렬한 새로운 정수를 리턴해주세요. 예를들어 n이 118372면 873211을 리턴하면 됩니다. 문제 풀이 접근법1 1) 정수 n 입력 받기 2) 정수를 n을 형변환 및 각 자릿수를 list의 원소로 입력 받기 3) sort(reverse=True)를 사용하여 각 리스트 원소를 내림차순 정렬 4) join()를 사용하여 리스트를 문자열로 형변환 5) 문자열을 int형으로 형변환 def solution(n): answer = 0 arr='' number = [] for i in str(n): number.append(i) number.sort(reverse=True) arr = ''.join(number..
문제 문자열 s를 숫자로 변환한 결과를 반환하는 함수, solution을 완성하세요. 문제 풀이 접근법1 1) find함수로 '-'의 여부를 판단한다. 2) 만약 -부호가 있을 경우에는 0에서 int(s)를 빼서 마이너스 부호를 붙여준다. 3) 아니라면 그냥 int()로 str형에서 int형으로 바꾼다. def solution(s): answer = 0 find = s.find('-') if find > 0: answer = 0 - int(s) else: answer = int(s) return answer 원래는 in으로 찾으려고 했는데 내 생각대로 '-'를 찾지 못해서 find함수를 사용해서 -여부를 판단했다. 아마 내가 코드를 잘못 만들어서 그런 것 같은데 나중에 다시 한번 in으로 풀어봐야지.. ..
문제 임의의 양의 정수 n에 대해, n이 어떤 양의 정수 x의 제곱인지 아닌지 판단하려 합니다. n이 양의 정수 x의 제곱이라면 x+1의 제곱을 리턴하고, n이 양의 정수 x의 제곱이 아니라면 -1을 리턴하는 함수를 완성하세요. 문제 풀이 접근법1 1) sqrt()함수를 사용하여 n에 루트를 씌운 값을 저장한다. 2) n과 sqrt함수로 반환 받은 √n을 나눈다. 3) 2의 나머지가 나누어 떨어진다면 어떠한 양의 정수 x의 제곱근이므로 n+1의 제곱한 값을 반환한다. 4) 2의 나머지가 나누어 떨어지지 않는다면 어떠한 양의 정수 x의 제곱근이 아니므로 -1을 반환한다. import math def solution(n): answer = 0 sqrt_n = math.sqrt(n) if n % sqrt_n ..
문제 자연수 n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴해주세요. 예를들어 n이 12345이면 [5,4,3,2,1]을 리턴합니다. 문제 풀이 접근법1 1) 자연수 N을 입력 받는다. 2) 자연수 N을 str형으로 바꾼 뒤, 반복문을 통해 리스트에 원소를 추가한다 3) reverse() 통해 리스트를 거꾸로 출력한다. def solution(n): answer = [] for i in str(n): answer.append(i) answer = list(map(int, answer)) answer = list(reversed(answer)) return answer vscode에서는 결과가 잘 나왔는데 채점을 하니 에러가 났다. 그래서 혹시 reversed()를 사용 못하나 싶어서 다시 풀..