알고리즘/코드워
[python]Watermelon
(ㅇㅅㅎ)
2020. 5. 6. 20:52
728x90
반응형
https://www.codewars.com/kata/55192f4ecd82ff826900089e/train/python
Codewars: Train your coding skills
Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.
www.codewars.com
이 문제는 1에서 100 사이 수를 입력받았을 때 입력받은 수가 2개로 나누었을 때 짝수가 되는 수가 있으면 True를 출력하고 없으면 False를 출력하는 것입니다.
예를 들어서 1의 경우는 2개의 수로 나눌 수 없기 때문에 False를 출력하고 2의 경우는 2개의 수로 나눌 때 1과 1이 될 수 있습니다. 하지만 1은 짝수가 아니기 때문에 False를 출력합니다. 4의 경우 1과 3 혹은 2와 2가 되는데 2와 2의 경우 두 수가 짝수이기 때문에 True를 출력합니다.
전체 코드를 보시려면 더보기를 클릭하시면 됩니다.
더보기


Watermelon
전체 코드
# My Code
def divide(weight):
# weight가 3이하면 2개로 나누었을 때 짝수가 될 수 없다.
if weight > 3:
if weight % 2 == 0:
return True
else:
return False
else:
return False
# 한줄로 줄이면 다음과 같다.
return (True if weight % 2 == 0 else False) if weight > 3 else False
if __name__=='__main__':
print(divide(4))
print(divide(2))
print(divide(5))
print(divide(88))
print(divide(100))
print(divide(67))
print(divide(90))
print(divide(10))
print(divide(99))
print(divide(32))
|
결과


이중 if문을 쓸 필요 없이 and 연산자를 썼어도 될 문제였습니다.
# My Code
def divide(weight):
return True if weight % 2 == 0 and weight > 3 else False
|
그리고 굳이 True를 적어 주지 않아도 됩니다. 하지만 정확히 명시하는 것이 좋다고 생각됩니다.
# My Code
def divide(weight):
return weight % 2 == 0 and weight > 3
|
반응형