알고리즘

[CodeWars] 6Kyu : Who likes it?

또롱또 2024. 12. 6. 03:13
728x90

https://www.codewars.com/kata/5266876b8f4bf2da9b000362/train/python

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

 

5 kyu에서 좌절을 맛보고 다시 6kyu로 내려왔다.

 

조금 더 연습을 해보기로 했다.

 

좋아요 같은걸 만들라 한다.

 

아무도 없으면 아무도 좋아하지않는다, 1~3명이면 and로 다 보여주고, 4명부턴 others로 보여주면 된다.

 

태그는 string 그리고 fundamentals다.

 

def likes(names):
    if len(names) == 0:
        return "no one likes this"
    elif len(names) == 1:
        return f"{names[0]} likes this"
    elif len(names) == 2:
        return f"{names[0]} and {names[1]} like this"
    elif len(names) == 3:
        return f"{names[0]}, {names[1]} and {names[2]} like this"
    else:
        return f"{names[0]}, {names[1]} and {len(names) - 2} others like this"

 

string이라 그냥 이 문제의 목적은 string 내부에서 변수를 보여주는게 아닐까 싶어서 이렇게 if else로 해봤다.

 

아래처럼 switch case 사용도 가능하다. 훨씬 보기 좋다. 파이썬은 match ~ case 다.

def likes(names):
    match names:
        case []: return 'no one likes this'
        case [a]: return f'{a} likes this'
        case [a, b]: return f'{a} and {b} like this'
        case [a, b, c]: return f'{a}, {b} and {c} like this'
        case [a, b, *rest]: return f'{a}, {b} and {len(rest)} others like this'
728x90