본문 바로가기

Python345

What is between? Complete the function that takes two integers (a, b, where a [1, 2, 3, 4] Solution: def between(a,b): number = get_number_generater(range(a,b+1)) return [next(number) for i in range(b+1-a)] def get_number_generater(range): for i in range: yield i Solve it using a generator. It can .. 2022. 7. 24.
Anagram Detection An anagram is the result of rearranging the letters of a word to produce a new word (see wikipedia). Note: anagrams are case insensitive Complete the function to return true if the two arguments given are anagrams of each other; return false otherwise. Examples "foefet" is an anagram of "toffee" "Buckethead" is an anagram of "DeathCubeK" Solution: def is_anagram(test, original): if len(test) < l.. 2022. 7. 21.
Sum of all the multiples of 3 or 5 Your task is to write function findSum. Upto and including n, this function will return the sum of all multiples of 3 and 5. For example: findSum(5) should return 8 (3 + 5) findSum(10) should return 33 (3 + 5 + 6 + 9 + 10) Solution: def find(n): return sum([i for i in range(1, n+1) if i%3 == 0 or i%5 == 0]) 1. Find a number less than 'n'. 2. Find a number that is divisible by 3 or divisible by 5.. 2022. 7. 20.
Python _ TypedDict를 사용하는 이유(feat. mypy) Python도 Type을 확인한다구! 파이썬은 타입 힌트를 제공함으로써 해당 데이터가 어떤 타입을 갖고 있는지 알 수 있다. 다만 파이썬은 타입을 강제하지 않기 때문에 일반 런타임 환경에서는 타입의 정상여부를 알기 어렵다. 때문에 타입이 정상인지 확인하기 위해 mypy 나 pyright 같은 정적 검사 도구를 이용한다. 하지만 그럼에도 애매한 경우가 있는데 바로 dict와 같은 value들이 다양한 타입을 가질 경우이다. dict value들의 타입을 일일이 확인하고 명시하기란 매우 귀찮은 일이다. 때문에 Dict[str, Any] 처럼 value에 해당되는 타입을 Any로 넘기는 경우가 많다. 하지만 이는 바람직하지 않다. Any가 어떤 문제를 일으키는지 먼저 살펴보고, 이에 대한 해결책으로서 Type.. 2022. 6. 22.
Python _ dict의 keys()처럼 dataclass에서 속성 목록 가져오기 파이썬에서 객체를 만드는 방법 중에 dataclass가 있다. @dataclass 데코레이터를 사용하면 타입 유형을 명시한 객체를 만들 수 있다. dataclass를 만드는 코드는 아래와 같다. from dataclasses import dataclass @dataclass(frozen=True) class Dataclass: a:int b:int c:int data = Dataclass(a=1,b=3,c=5) print(data) # 출력 : Dataclass(a=1, b=3, c=5) print(data.a) # 1 print(data.b) # 3 print(data.c) # 5 이렇게 만든 객체는 타입 유형을 명시하고 싶을 때나 DTO, 값 객체 등의 불변 객체로도 사용할 수 있다. dataclas.. 2022. 6. 21.
Python _ @dataclass 사용법과 타입 확인 파이썬에서는 @dataclass를 통해 데이터의 타입을 명시하고 안정적으로 다룰 수 있습니다. 이 글에서는 간단한 사용법을 소개하고 타입 확인까지 해보겠습니다. @dataclass 사용법 먼저 다음처럼 코드를 작성합니다. from dataclasses import dataclass @dataclass() class Data: name: str int: int dict: dict name은 str, int는 int, dict는 dict로 타입을 지정하였습니다. 이어서 데이터를 만들어보겠습니다. data1 = Data( name = "변덕순", int = 1, dict = {"a":"b"} ) Data클래스를 활용해 data1 이라는 인스턴스를 만들었습니다. print로 name과 타입을 출력해보겠습니다. .. 2022. 5. 18.