https://www.codewars.com/kata/534d2f5b5371ecf8d2000a08/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
6kyu의 문제다
파라미터에 size를 넣으면, 그걸 기준으로 size x size 의 표를 만들고 2중배열로 return 해야한다.
이런문제에 취약해서 한단게씩 접근을 해보기로 했다. 먼저 [[1,2,3]] 을 만들어 보려 했다.
def multiplication_table(size):
arr = []
arr.append([num + 1 for num in range(size)])
return arr
[[2,4,6]] 은 이렇게 만든다.
def multiplication_table(size):
arr = []
arr.append([(num + 1) * 2 for num in range(size)])
return arr
마지막 줄인 [[3,6,9]] 는
def multiplication_table(size):
arr = []
arr.append([(num + 1) * 3 for num in range(size)])
return arr
곱셈을 해주는 부분이 첨에는 size - size, 그리고 until size 까지 라는 규칙이 있는걸 알게됬다.
즉 index다.
JS에서 for 문 작성할때 for i = 0; i < n; ++i 여기서 이 i만큼 곱해주면 되는거 같다.
def multiplication_table(size):
arr = []
for idx in range(size):
arr.append([(num + 1) * (idx + 1) for num in range(size)])
return arr
2중 for loop을 뭔가 더 간결하게 해보고 싶었는데, 일단 이게 되서 그냥 이렇게 제출해봤다.
다른 정답을 확인해 보니,
나랑 비슷한데, 얘는 range안에서 저렇게 두개를 사용했다. 대충 1 부터 size + 1 까지 라는거 같다.
def multiplicationTable(size):
return [[j*i for j in range(1, size+1)] for i in range(1, size+1)]
다른 답으로는 아예 2중 for loop을 풀어쓴게 있었다. 대부분 range 안에서 처리를 했다.
def multiplication_table(size):
columns = []
for i in range(1,size+1):
rows = []
for j in range(1,size+1):
rows.append(i*j)
columns.append(rows)
return columns
'알고리즘' 카테고리의 다른 글
[CodeWars] 5Kyu : Directions Reduction (2) | 2024.12.05 |
---|---|
[CodeWars] Factorial - 7Kyu (0) | 2024.12.05 |
[CodeWars] Simple Pig Latin- 5Kyu (1) | 2024.12.05 |
[CodeWars] Square Every Digit - 7Kyu (0) | 2024.12.05 |
[CodeWars] Does my number look big in this?- 6Kyu (0) | 2024.12.04 |