알고리즘

[CodeWars] Counting sheep... - 8Kyu

또롱또 2024. 12. 4. 05:40
728x90


https://www.codewars.com/kata/54edbc7200b811e956000556/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

 

이번에는 배열안에 True가 몇개인지 세는 문제이다.

 

null 아니 undefined 의 값도 체크를 해줘야한다고 Hint가 써있다.

 

이번에도 그냥 for - in 을 사용해서 풀었다. 

배열안의 엘리먼트가 True면 카운트를 하나 올리고 아니면 continue로 작업을 pass 했다.

def count_sheeps(sheep):
   count = 0
   for shp in sheep:
      if shp == True:
         count += 1
      else:
         continue
   return count

 

다른 정답을 확인해보니, 굳이 continue를 안해줘도 되나 싶다.

그리고 나도 파라미터 이름을 sheeps 이런걸로 했어야 했는데, 깜빡했다.

def count_sheeps(array_of_sheep):
  # TODO May the force be with you
  count = 0
  for sheep in array_of_sheep:
      if sheep:
          count += 1 
  return count

 

그리고 숏코딩은 이런게 있었다. ㅋㅋㅋ count라는 간단한 함수가 있다니.. 이건 살짝 편법 쓴거 같긴한데,

def count_sheeps(arrayOfSheeps):
  return arrayOfSheeps.count(True)

 

이 아래꺼가 진정한 쇼코딩이라 생각한다.

def count_sheeps(sheep):
  return len([x for x in sheep if x])

 

if x 에서 이미, boolean 으로 체크를 하고있고, 그거를 다시 하나의 배열로 정의해서 len으로 길이를 재는건 정말 생각도 못해보긴했다.

728x90

'알고리즘' 카테고리의 다른 글

[CodeWars] Array.diff - 6Kyu  (0) 2024.12.04
[CodeWars] Rock Paper Scissors! - 8Kyu  (0) 2024.12.04
[CodeWars] Count by X - 8Kyu  (0) 2024.11.30
[CodeWars] Build a square - 7Kyu  (0) 2024.11.30
알고리즘(JS) - BFS DFS  (0) 2022.06.28