https://www.codewars.com/kata/5993fb6c4f5d9f770c0000f2/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
6 kyu로 레벨업하고나서, 요즘은 기본적으로 8kyu는 안잡히고 6-7kyu가 잡히는거 같다.
그래서 rank up 말고 기초로 내려왔다 다시.
이번 문제는, 리스트내의 모든 엘리먼트를 더해야한다, 단 중복되는 숫자가 있으면 그 숫자는 피해야 한다.
두가지 방법이 떠올랐다, 하나는 set을 이용하는건데, 이건 알고리즘 문제가 아닌거 같아서 패스했고, for loop을 이용해서 해결해 보자 했다.
정말 생각해야할 케이스가 많았고, 결국 리스트를 두개나 쓰면서 해결해 봤다.
정답과, 중복이 들어갈 리스트들을 따로 만들고, 넣었다 뺐다 하면서 체크를 한다.
def sum_no_duplicates(l):
result = []
already = []
sum = 0
for ele in l:
if ele not in already:
if ele not in result:
result.append(ele)
elif ele in result:
result.remove(ele)
already.append(ele)
for num in result:
sum += num
return sum
나처럼 푼 사람은 당연히 없었고 ㅋㅋ
정답 코드는 아래와 같다. 난 아직 파이썬에 너무 미숙한 느낌이다.
def sum_no_duplicates(l):
return sum(n for n in set(l) if l.count(n) == 1)
근데 set을 사용한 것은 뭔가 꼼수를 쓴거같아서 일단 이렇게 하는구나 까지만 하고 넘어가려한다.
def sum_no_duplicates(l):
new = []
for x in l:
if l.count(x) == 1:
new.append(x)
return sum(new)
이건 좀 신선했다. 리스트내에서 이 value가 한개뿐인걸 찾아서 더한다.. 아 그리고 sum 이라는 함수도 있나보다..
'알고리즘' 카테고리의 다른 글
[CodeWars] 5Kyu : Memoized Fibonacci (1) | 2024.12.10 |
---|---|
[CodeWars] 6Kyu : Unique In Order (0) | 2024.12.08 |
[CodeWars] 7Kyu : Descending Order (1) | 2024.12.06 |
[CodeWars] 6Kyu : Who likes it? (1) | 2024.12.06 |
[CodeWars] 5Kyu : Directions Reduction (2) | 2024.12.05 |