본문 바로가기
WIL&TIL/TIL

20230401 TIL

by 코드뭉치 2023. 4. 1.

1. 직사각형 넓이 구하기

def solution(dots):
    (x1, y1), (x2, y2), (x3, y3), (x4, y4) = dots
    a = abs(x1 - x2) if x1 != x2 else abs(x1 - x3)
    b = abs(y1 - y2) if y1 != y2 else abs(y1 - y3)
    return a*b

 

 ↓ 삼항 연산자 활용해보기

def solution(dots):
    (x1, y1), (x2, y2), (x3, y3), (x4, y4) = dots
    a, b = abs(x1 - x2) or abs(x1 - x3), abs(y1 - y2) or abs(y1 - y3)
    return a * b

 

 

2. 문자열 최빈값 구하기

input = "hello my name is sparta"

def find_max_occurred_alphabet(string):
    a = {}
    for i in string:
        if i not in a and i.isalpha():
            a[i] = 1
        elif i in a and i.isalpha():
            a[i] += 1
    cnt = max(a.values())
    frequency = ''
    for j,k in a.items():
        if k == cnt:
            frequency = j
            break
    return (f"{frequency}가 {cnt}회로 가장 많이 나왔습니다")

result = find_max_occurred_alphabet(input)
print(result)

 

↓ lambda, filter 활용해보기

input = "hello my name is sparta"

def find_max_occurred_alphabet(string):
    a = {}
    for i in string.lower():
        if i.isalpha():
            if i in a:
                a[i] += 1
            else:
                a[i] = 1
    cnt = max(a.values())
    frequency = filter(lambda x: a[x] == cnt, a.keys())
    return (f"{next(frequency)}가 {cnt}회로 가장 많이 나왔습니다")

result = find_max_occurred_alphabet(input)
print(result)

댓글