Python/프로그래머스 6

[프로그래머스] 가까운 수

🪄내가 한 solutionarray의 인덱스와 값으로 부터 [인덱스, |값 - n|, 값] 리스트를 만든다해당 리스트를 sorted()를 사용하여, 정렬 기준으로 x[1](|값 - n|) -> x[-1](값) 오름차순 정렬한다가장 가까운 수가 여러개일 경우 작은 수를 리턴하기 위해 두번째 정렬 조건으로 값(x[-1]) 정해줌정렬이 완료된 리스트에서 0번째 리스트의 0번째 값을 리턴한다def solution(array, n): return array[sorted([[index, abs(n-num), num] for index, num in enumerate(array)], key = lambda x: (x[1], x[-1]))[0][0]] 💡추가로 알아야 할 것sorted(iterable, k..

[프로그래머스] 대문자와 소문자

🪄내가 한 solution upper() 대문자로 변환, lower() 소문자로 변환 함수 def solution(my_string): answer = '' for i in my_string: if i.isupper(): answer += i.lower() else: answer += i.upper() return answer 🪄다른사람이 한 solution def solution(my_string): return my_string.swapcase() 🪄추가로 알아야 할 것 swapcase(): 대문자와 소문자를 각각 소문자, 대문자로 변환 title(): 각 단어의 앞 글자만 대문자로 변환 Python 엄청나다... 이게 있네 싶은 것들이 이미 다 있다. 더 많이 문제 풀어보면서 새로운 함수들 많이 익..

[프로그래머스] 최빈값 구하기

🪄내가 한 solution sorted(iterable, key, reverse) iterable : 반복 가능한 iterable 자료형 입력 key : 정렬을 목적으로 하는 함수를 넣음 reverse : False(오름차순, default), True(내림차순) def solution(array): count = {} max_num = 0 # for 반복문으로 입력 list 순회 for i in array: # 딕셔너리에 현재 key가 있다면 value에 1 더하기 if i in count: count[i] += 1 # 딕셔너리에 현재 key가 할당되어 있지 않다면 1 할당 else: count[i] = 1 # 딕셔너리의 value 값 기준으로 내림차순 정렬 result = sorted(count.it..

[프로그래머스] 분수의 덧셈

🪄내가 한 solution - fractions 사용 fractions.Fraction(분자, 분모) numerator, denominator 메소드 사용 a.numerator : 분자 a.denominator : 분모 import fractions def solution(denum1, num1, denum2, num2): result = fractions.Fraction(denum1, num1) + fractions.Fraction(denum2, num2) answer = [result.numerator, result.denominator] return answer 🪄내가 한 solution - gcd 사용 math.gcd(n1, n2) 분자의 합 구하기 분모 구하기 분자와 분모의 최대공약수 구하기 분..

[프로그래머스 - 파이썬을 파이썬 답게] n진법으로 표기된 string을 10진법 숫자로 변환하기 - int 함수

내가 한 solutionnum, base = map(int, input().strip().split(' '))output = 0for i in range(len(str(num))): output += int(str(num)[-1-i])*(base**i)print(output) 파이썬의 int(x, base = 10)함수는 진법 변환을 지원num, base = map(int, input().strip().split(' '))print(int(str(num), base))int(x, radix) : radix 진수로 표현된 문자열 x를 10진수로 변환 후 반환주의할 점은 첫번째 인자가 무조건 문자열

[프로그래머스 - 파이썬을 파이썬답게] 몫과 나머지 - divmod

내가 한 solution a, b = map(int, input().strip().split(' ')) print(a//b, a%b) divmod 와 unpacking 사용 print(*divmod(a, b)) divmod(x, y) -> x를 y로 나눈 몫과, 나머지가 들어있는 tuple을 리턴 무조건 divmod를 사용하는게 좋은 방법은 아님 divmod는 작은 숫자를 다룰 때는 a//b, a%b 보다 느림. 대신, 큰 숫자를 다룰 때는 divmod가 더 빠름 unpacking 여러 개의 객체를 포함하고 있는 하나의 객체를 풀어서 보여주는 것 >> print(divmod(5, 2)) (2, 1) # 튜플 형태의 하나의 객체를 반환 >> print(*divmod(5, 2)) 2 1 # 튜플 내 2와 1..