공부일지

[공부정리]Python 사칙연산 - 누적계산, 최종값 본문

Computer/공부정리

[공부정리]Python 사칙연산 - 누적계산, 최종값

이르리의 공부일지 2025. 3. 21. 17:24

계산기를 만들면서 다양한 사칙연산 프로그래밍을 위한 방법을 정리해보고자 한다.

여러 숫자에 대해 적용하는 방법이며, 첫 번째 숫자에 대해 나머지 숫자들이 하나의 연산으로 누적계산되고 최종으로 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를 간단히 이용해주자.