일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 함수형 프로그래밍
- boto3
- OS
- [초급(예비) 개발자 오픈소스 실무 역량강화 교육]
- functools.wraps
- 순수함수
- PIP
- selenium-wire
- slicing [::-1]
- S3
- ds_store
- sort(reverse=True) v.s. reverse
- Airflow
- 고차함수
- timestamp
- 코딩 테스트
- decorator
- pandas
- r-string
- blinker
- sort v.s. sorted
- Python
- 쿼리
- reverse v.s. reversed
- CI/CD
- os.path
- 생각
Archives
- Today
- Total
공부일지
[공부정리]Python 사칙연산 - 누적계산, 최종값 본문
계산기를 만들면서 다양한 사칙연산 프로그래밍을 위한 방법을 정리해보고자 한다.
여러 숫자에 대해 적용하는 방법이며, 첫 번째 숫자에 대해 나머지 숫자들이 하나의 연산으로 누적계산되고 최종으로 1개의 값을 반환하는 법이다.
덧셈
# 함수명 참고: add_all 할건데 간단히 add로 지음.
# sol0: 연산자 +, for-loop
def add(operands):
total = 0
for i in operands:
total += i
return total
# sol1: 내장함수 sum
def add(operands):
return sum(operands)
# sol2: itertools.accumulate
import itertools
def add(operands):
return itertools.accumulate(operands)
# sol3: numpy.cumsum
import numpy
def add(operands):
nums = numpy.array(operands)
return numpy.cumsum(nums)
# sol4: functools.reduce
import functools
def add(operands):
return functools.reduce(lambda x, y: x + y, operands)
빼기
# 함수명 참고: 첫 번째 숫자에서 나머지 값들을 모두 뺀다는 의미로 sub_from_first였지만 가독성을 위해 subside로 바꿈.
# ex. [a, b, c, d]에 대한 연산식: a - b - c - d
# sol0: for loop
def subside(operands):
total = operands[0]
for i in operands[1:]:
total -= i
return total
# sol1: fuctools.reduce
import functools
def subside(operands):
return functools.reduce(lambda x, y: x - y, operands)
곱셈
# 함수명 참고:
# sol 0: 연산자 *, for-loop
def prod(operands):
total = 0
for i in operands:
total *= i
return total
# sol1: math
import math
def prod(operands):
return math.prod(operands)
나눗셈
# sol 0: 연산자 /, for-loop
def divide(operands):
total = operands
for i in operands[1:]:
total /= i
return round(total, 3)
# sol1: functools.reduce
import functools
def divide(operands):
return functools.reduce(lambda x, y: x / y, operands)
궁금증
Q 합은 sum이라는 내장함수 있는데 나머지는 왜 없?
궁금증 해소
(참고) math는 차/나눗셈 누적을 지원 안 하는 이유
- 덧셈/곱셈은 **결합 법칙(Associativity)**이 있어서 누적 계산에 자주 쓰이지만,
- 뺄셈이나 나눗셈은 결합 법칙이 없고 순서 의존이라 내장화하기 애매
ex. (10 - 2 - 1) ≠ (10 - (2 - 1))
누적 연산 | 내장 함수 | math 모듈 함수 | 추천방식(3.8 이상) |
합 (+) | ✅ sum() | ❌ 없음 | sum(nums) |
곱 (*) | ❌ 없음 | ✅ math.prod() | math.prod(nums) |
차 (-) | ❌ 없음 | ❌ 없음 | reduce(lambda x, y: x - y, nums) |
나눗셈 (/) | ❌ 없음 | ❌ 없음 | reduce(lambda x, y: x / y, nums) |
결론
제공해주는 간단한 함수 혹은 모듈 함수 이용하고, 차와 나눗셈같은 순서가 중요한 경우(함수명 지을 때도 느꼈듯이)는 functools.reduce를 간단히 이용해주자.
'Computer > 공부정리' 카테고리의 다른 글
[AI]ChatGPT memory, reference Chat History, Archive chats에 관한 내용 (0) | 2025.04.17 |
---|---|
[AI][강의 요약]1강 - 생성 AI와 프롬프트 엔지니어링 (0) | 2025.04.17 |
[Python]Selenium Wire Request/Response Objects (0) | 2024.10.09 |
[실무개념] CI/CD (1) | 2024.10.03 |
[Python] S3 버킷과 폴더의 개념 (1) | 2024.10.01 |