AI/Python
[프로그래머스 입문] dict, math,sort와 sorted에 key값 넣기, 이진수와 십진수 변환, 이차원 배열의 최댓값과 최솟값
brave_sol
2024. 6. 18. 23:49
학습내용 | 예시 |
[1] math 모듈 최대공약수 gcd | import math def solution(denum1, num1, denum2, num2): denum = denum1 * num2 + denum2 * num1 num = num1 * num2 gcd = math.gcd(denum, num) return [denum//gcd, num//gcd] print(solution(9,2,1,3)) # [29,6] |
[2] dict의 value기준으로 내림차순 | color_dict = {'red':3, 'yellow':5, 'blue':1} color_sorted = sorted(color_dict.items(), key= lambda x: x[1], reverse = True) print(color_sorted) # [('yellow', 5), ('red', 3), ('blue', 1)] |
[3] dict.keys() 는 반환값의 type은 dict.keys 리스트가 필요하면 list(dict.keys()) |
print(color_dict.get('red')) # 3 print(color_dict[0]) # Error |
[4] sorted 특정 기준으로 정렬 (1) 정렬 기준이 내장함수일때 sorted(리스트, key=내장함수이름, reverse=True/생략가능) (2) 정렬 기준을 새로 만들어야 할 때 lambda 함수 사용 sorted(리스트, key=lambda x : (len(x), x), reverse=True/생략가능) |
sorted( [-3,-2,-1,0,1,2,3,4,5] , key=abs, reverse=True) 출력 → [0, -1, 1, -2, 2, -3, 3, 4, 5] 절댓값, 오름차순으로 정렬 sorted( [-3,-2,-1,0,1,2,3,4,5] , key=abs, reverse=True) 출력 → [5, 4, -3, 3, -2, 2, -1, 1, 0] 절댓값, 역순으로 정렬 students = [ {"name": "John", "grade": 90}, {"name": "Jane", "grade": 85}, {"name": "Dave", "grade": 92} ] sorted_students = sorted(students, key=lambda student: student["grade"]) print(sorted_students) 출력 → : [{'name': 'Jane', 'grade': 85}, {'name': 'John', 'grade': 90}, {'name': 'Dave', 'grade': 92}] |
[5] 이진수와 십진수 변환 (1) 이진수 → 십진수 : int(이진수,2) # 이진수는 0b형태로 입력 (2) 십진수 → 이진수: bin(십진수) # 출력은 0b형태로 나옴 * 인덱스슬라이싱으로 1과0으로만 반환 가능 |
print(int('0b1001',2)) # 9 print(bin(9)) # 0b1001 |
[6] 이차원 배열의 최댓값과 최솟값, 정렬 | dots = [[1, 1], [2, 1], [2, 2], [1, 2]] print(min(dots)) # [1, 1] print(max(dots)) # [2,2] print(sorted(dots)) # [[1, 1], [1, 2], [2, 1], [2, 2]] |
반응형