[Python]#13 Lambda, Reduce

Jude's Sound Lab·2025년 1월 9일

Algorithm & Coding

목록 보기
2/5

Lambda

"lambda arguments: expression" equals to "function"
  • arguments: Input values to the function.
  • expression: The single operation or computation performed on the arguments. The result of this expression is the function's return value.

Simple usage

# Regular function
def add(x, y):
    return x + y

# Lambda function (same as above)
add_lambda = lambda x, y: x + y

print(add(3, 4))         # Output: 7
print(add_lambda(3, 4))  # Output: 7

Combined with map

# map(function, iterable) is a built-in function in Python.
pairs = [(1, 2), (3, 4), (5, 6)]
sums = list(map(lambda pair: pair[0] + pair[1], pairs))
print(sums)  # Output: [3, 7, 11]

Reduce

""" from python functools.py
reduce(function, iterable[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence
or iterable, from left to right, so as to reduce the iterable to a single
value.  For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
of the iterable in the calculation, and serves as a default when the
iterable is empty.
"""
	# from functools.py
    # designed to treating first two values at the start. 
    # and iterative applying function from the output of the previous and new input
    it = iter(sequence)

    if initial is _initial_missing:
        try:
            value = next(it)
        except StopIteration:
            raise TypeError(
                "reduce() of empty iterable with no initial value") from None
    else:
        value = initial

    for element in it:
        value = function(value, element)

    return value

Simple usage

from functools import reduce
from operator import mul

axial_shape = (64, 64)
self.max_seq_len = reduce(mul, axial_shape, 1) # 64 * 64
# 2. Find the Maximum Value
# Find the maximum value in a list (without using max):
# from functools import reduce

nums = [3, 1, 7, 9, 2]
result = reduce(lambda x, y: x if x > y else y, nums)
print(result)  # Output: 9

# remember two elements inside the iterables
from functools import reduce

nested_list = [[1, 2], [3, 4], [5, 6]]
result = reduce(lambda x, y: x + y, nested_list)
print(result)  # Output: [1, 2, 3, 4, 5, 6]
profile
chords & code // harmony with structure

0개의 댓글