본문 바로가기

Python345

Python _ Decimal 모듈로 부동 소수점 문제 해결하기 Decimal 이란? Decimal은 '부동 소수점 문제'를 해결하고 소수점을 정확하게 표현하기 위해 사용하는 Python 자료형이다. 컴퓨터에서는 소수를 이진수로 표현하다 보니, 0.1과 같은 값이 정확하게 표현되지 않을 수 있다. 이러한 문제 때문에 금융, 회계 등 정확한 계산이 필요한 경우에는 Decimal을 사용해야 한다. 예를 들어, 파이썬에서 소수형을 그대로 사용하면 다음과 같은 부동 소수점 문제가 발생할 수 있다. value = 0.1 + 0.2 print(value) # 출력: 0.30000000000000004 하지만 아래처럼 Decimal 모듈을 사용하면 이런 문제를 피할 수 있다. from decimal import Decimal value = Decimal('0.1') + Decim.. 2023. 5. 16.
Python & FastAPI 로 백엔드 시작하기 (2) _ API 연습 및 단축 스크립트 만들기 02. API 연습 및 단축 스크립트 만들기 개요 - `main.py` 를 `app/views` 경로로 이동합니다. - `main.py` 에 연습용 API를 구현합니다. - `run-server.sh` 스크립트를 생성합니다. - `tree` 를 이용해 디렉터리 구조를 확인합니다. main.py 를 app/views 경로로 이동하기 app 디렉터리와 그 하위에 views 디렉터리를 생성합니다. 각 디렉터리에는 __init__.py 파일을 생성합니다. *__init__.py 파일이 없는 경우, 해당 디렉터리는 단순한 디렉터리로 간주됩니다. 반면 __init__.py 파일이 존재하는 디렉터리는 파이썬 패키지로 간주되며, 패키지 내부에 있는 모듈들을 다른 모듈에서 import할 수 있습니다. 기존 main.py.. 2023. 4. 27.
Python & FastAPI 로 백엔드 시작하기 (1) _ 개발환경 세팅하기 01. 개발환경 세팅하기 이 글은 Python과 FastAPI를 활용하여 백엔드 개발을 시작하고 싶은 분들을 위해 작성하였습니다. 개요 - pyenv로 가상환경을 만들고 Poetry 종속성 관리 도구를 설치한다. - FastAPI 와 Uvicorn 을 사용해 서버를 실행한다. - .gitignore 파일을 생성하여 불필요한 업로드를 막는다. - pre-commit을 활용하여 코드 스타일과 정적 분석을 자동화한다. *사용 기기 : M1 MacBook Air *사용 IDE : Visual Studio Code *만약 터미널 사용이 처음이거나 아직 세팅이 완료되지 않았다면 이전 글을 참고해주세요. 2023.03.18 - [나는 이렇게 논다/백엔드 시작하기 with Python] - Mac M1 터미널 환경 세.. 2023. 4. 10.
0212. Reversed sequence Build a function that returns an array of integers from n to 1 where n>0. Example : n=5 --> [5,4,3,2,1] Solution: reverse_seq = lambda n: sorted(range(1, n+1), reverse=True) def reverseseq(n): return list(range(n, 0, -1)) 2023. 2. 13.
0211. Remove duplicates from list Define a function that removes duplicates from an array of numbers and returns it as a result. The order of the sequence has to stay the same. Solution: def distinct(seq: list[int]) -> list[int]: result = [] for i in seq: if i not in result: result.append(i) return result def distinct(seq: list[int]) -> list[int]: return sorted(set(seq), key=seq.index) def distinct(seq: list[int]) -> list[int]: .. 2023. 2. 12.
0210. Is it a number? Given a string s, write a method (function) that will return true if its a valid single integer or floating number or false if its not. Valid examples, should return true: isDigit("3") isDigit(" 3 ") isDigit("-3.23") should return false: isDigit("3-4") isDigit(" 3 5") isDigit("3 5") isDigit("zero") Solution: def isDigit(string: str) -> bool: return string.strip().lstrip("-").replace(".", "").isd.. 2023. 2. 10.