programming language/Python

[Python] 연산관련 function과 method

눈곱만큼도모름 2023. 7. 18. 16:47
728x90
반응형

Operational related functions

 

sum() a + b numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total)  # 출력: 15
divmod() a/b result = divmod(13, 5)
print(result)  # 출력: (2, 3)
pow() a**b result = pow(2, 3)
print(result)  # 출력: 8
abs() 절대값 number = -5
absolute_value = abs(number)
print(absolute_value)  # 출력: 5
round() 반올림 number = 3.7
rounded_number = round(number)
print(rounded_number)  # 출력: 4
max() 최대값 numbers = [1, 3, 5, 2, 4]
maximum = max(numbers)
print(maximum)  # 출력: 5
min() 최소값 numbers = [1, 3, 5, 2, 4]
minimum = min(numbers)
print(minimum)  # 출력: 1

 

Operational related methods

__add__   a + b a.__add__(b)
__sub__ a-b a.__sub__(b)
__mul__ a*b a.__mul__(b)
__pow__ a**b a.__pow__(b)
__div__   , __truediv__  a/b a.__div__(b) ,  a.__truediv__(b)
__floordiv__  a//b a.__floordiv__(b)
__mod__ a%b a.__mod__(b)
__abs__ 절대값 a.__abs__()

코딩테스트에서 아래와 같은 형태로 사용가능

solution=int.__mod__

solution=int.__floordiv__

 

Class내 사용 예시

 

__add__ 

class Number:
    def __init__(self, value):
        self.value = value
    
    def __add__(self, other):
        return self.value + other.value

num1 = Number(5)
num2 = Number(10)
result = num1 + num2
print(result)  # 출력: 15

__sub__ 

 

class Number:
    def __init__(self, value):
        self.value = value
    
    def __sub__(self, other):
        return self.value - other.value

num1 = Number(10)
num2 = Number(5)
result = num1 - num2
print(result)  # 출력: 5

__mul__ 

 

class Number:
    def __init__(self, value):
        self.value = value
    
    def __mul__(self, other):
        return self.value * other.value

num1 = Number(3)
num2 = Number(4)
result = num1 * num2
print(result)  # 출력: 12

__pow__

class Number:
    def __init__(self, value):
        self.value = value
    
    def __pow__(self, other):
        return self.value ** other.value

num1 = Number(2)
num2 = Number(3)
result = num1 ** num2
print(result)  # 출력: 8

__div__ , __truediv__

class Number:
    def __init__(self, value):
        self.value = value
    
    def __div__(self, other):
        return self.value / other.value

num1 = Number(10)
num2 = Number(2)
result = num1 / num2
print(result)  # 출력: 5.0

__floordiv__

class Number:
    def __init__(self, value):
        self.value = value
    
    def __floordiv__(self, other):
        return self.value // other.value

num1 = Number(10)
num2 = Number(3)
result = num1 // num2
print(result)  # 출력: 3

__mod__

class Number:
    def __init__(self, value):
        self.value = value
    
    def __mod__(self, other):
        return self.value % other.value

num1 = Number(10)
num2 = Number(7)
result = num1 % num2
print(result)  # 출력: 3

__abs__

class Number:
    def __init__(self, value):
        self.value = value
    
    def __abs__(self):
        return abs(self.value)

num = Number(-5)
result = abs(num)
print(result)  # 출력: 5
728x90
반응형