람다 표현식의 이해와 코드

람다 표현식 다양한 함수 활용

클래스의 이해

수업 예시 코드

# 예시 코드
## 람다 표현식
c=set(map(lambda a:((a+100)*2)/3, [10,20,30]))

# 리스트의 각 요소에 대해 두 가지 연산을 수행
operate_on_list = lambda lst, op1, op2: [op1(item) + op2(item) for item in lst]

# 람다 함수를 활용하여 각 요소를 제곱하고 1을 더한 결과
numbers = [1, 2, 3, 4, 5]
result1 = operate_on_list(numbers, lambda x: x ** 2, lambda x: x + 1)

# 각 요소에 대해 제곱을 계산하는 map 함수
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))

# 람다 함수를 사용하여 문자열의 길이를 기준으로 정렬
sort_strings_by_length = lambda strings: sorted(strings, key=lambda s: len(s))
string_list = ["apple", "banana", "cherry", "date", "elderberry"]
result2 = sort_strings_by_length(string_list)

# 람다 함수를 사용하여 두 수 중 큰 수를 반환하는 함수
get_max = lambda a, b: a if a > b else b
result3 = get_max(7, 12)

# 리스트의 각 요소 중에서 짝수만 필터링하는 filter 함수
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

# 리스트의 모든 요소를 누적해서 곱하는 reduce 함수
product_of_numbers = reduce(lambda x, y: x * y, numbers)

## 클래스
class person:
    def __init__(self):
        self.hello='안녕?'
        
    def greeting(self):
        print(self.hello)
        
jm = person()
jm.greeting()

class Book:    
    def __init__(self, title, author, price):
        self.title = title
        self.author = author
        self.price = price

    def set_discount_rate(self, rate):
				"""
        클래스 메서드: 할인율을 설정하는 메서드

        Parameters:
        - rate (float): 할인율 (0.0에서 1.0 사이의 값)
        """
        self.discount_rate = rate

    def create_book_with_discount(self, title, author, price):
				"""
        클래스 메서드: 할인된 가격으로 Book 인스턴스를 생성하는 메서드
				"""
        discounted_price = price - (price * self.discount_rate)
        return Book(title, author, discounted_price)

    def __str__(self):
        return f"{self.title} by {self.author}, Price: ${self.price:.2f}"

book_instance = Book("Sample Book", "Anonymous Author", 100.0)
book_instance.set_discount_rate(0.2)
book_with_discount = book_instance.create_book_with_discount("Python Mastery", "John Doe", 50.0)