코테16) 없는 숫자 더하기

gyu·2024년 4월 12일

Algorithm

목록 보기
17/45

📝 문제설명

0부터 9까지의 숫자 중 일부가 들어있는 정수 배열 numbers가 매개변수로 주어집니다. numbers에서 찾을 수 없는 0부터 9까지의 숫자를 모두 찾아 더한 수를 return 하도록 solution 함수를 완성해주세요.

제한사항
1 ≤ numbers의 길이 ≤ 9
0 ≤ numbers의 모든 원소 ≤ 9
numbers의 모든 원소는 서로 다릅니다.

나의 풀이:

def solution(numbers):
    answer = 0
    for i in range(10):
        if not i in numbers:
            answer += i         
    return answer

0-9까지의 숫자가 일부 들어있는 정수배열 중 없는 수만 더해서 리턴하는 문제다.
not을 사용하여 없는 숫자들을 구하고 더했다

✔ Tips to improve

return sum(set(range(10)) - set(numbers))

역시나 있을 줄 알았던 한줄코드 답안...ㅋㅋㅋㅋ
i) create a set containing the numbers from range(10)(0-9) and a set with some specific numbers
ii) find the difference between two sets using - operator
iii) use sum() to calculate the sum of the elements in the resulting set.

🔗 관련개념

set(iterable): create a set obj

  • The set list is unordered -> result will display in a random order
EX)
x = set(("apple", "banana", "cherry"))
print(x)  #{"banana", "cherry", "apple"}
  • elements are immutable but can add/update/remove elements from the set (set - mutable / elements in set are immutable)
  • Using set, we can do mathematical set operations like union, intersection, difference and symmetric difference.
profile
#TechExplorer 🚀 Curious coder exploring the tech world, documenting my programming journey in a learning journal

0개의 댓글