🪄내가 한 solution

  • array의 인덱스와 값으로 부터 [인덱스, |값 - 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, key, reverse)
    • iterable : 반복 가능한 iterable 자료형 입력
    • key : 정렬을 목적으로 하는 함수를 넣음
    •  reverse : False(오름차순, default), True(내림차순)


🪄내가 한 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.items(), key=lambda x: x[1], reverse=True)
    
    # 만약 result가 1개라면 그 값 바로 출력
    if len(result) <= 1: return result[0][0]
    
    # 최빈값이 여러개라면 
    # result(list)의 첫번째 tuple의 1번째 인덱스값과 두번째 tuple의 1번째 인덱스 값 같음
    # 그렇다면 -1 출력
    return result[0][0] if result[0][1] != result[1][11] else -1


🪄내가 한 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)
  1. 분자의 합 구하기
  2. 분모 구하기
  3. 분자와 분모의 최대공약수 구하기
  4. 분자 분모를 최대공약수로 나누어(약분) 배열에 담아 리턴하기
import math

def solution(denum1, num1, denum2, num2):
    boonja = denum1 * num2 + denum2 * num1 # 분자의 합
    boonmo = num1 * num2 # 분모
    gcd_value = math.gcd(boonja, boonmo) # 분자와 분모의 최대공약수 구하기
    return [boonja // gcd_value, boonmo // gcd_value]

 

 


내가 한 solution

num, base = map(int, input().strip().split(' '))

output = 0
for 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진수로 변환 후 반환
  • 주의할 점은 첫번째 인자가 무조건 문자열


내가 한 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이라는 int형 객체를 각각 반환

+ Recent posts