๐lambda expressions
ํจ์๋ฅผ ๊ฐํธํ๊ฒ ์์ฑํ ์ ์์ด์ ๋ค๋ฅธ ํจ์์ ์ธ์๋ก ๋ฃ์ ๋ ์ฃผ๋ก ์ฌ์ฉ
์ผ๋ฐํจ์
def add_func(x,y,z):
return x+y+z
print(add_func(1,2,3)) #6
๋๋ค ํํ์
f = lambda x,y,z : x+y+z
print(f(1,2,3)) #6
๋๋ค ์ฌ์ฉํ๊ธฐ
๐์ฝ๋ฐฑํจ์๋?
์ด๋ค ์ด๋ฒคํธ๊ฐ ๋ฐ์ํ์ ๋ ํธ์ถ๋๋ ํจ์
์ฝ๋ฐฑํจ์๊ฐ ์ฌ๋ฌ๋ธ๋ก์ผ๋ก ๊ตฌ์ฑ๋ ์คํ๋ฌธ์ด ์๋๊ณ ๋ค๋ฅธ ์ปดํฌ๋ํธ์์ ์ฌ์ฉ๋์ง ์๋๋ค๋ฉด ํด๋น ์ปดํฌ๋ํธ๋ง์ ์ํ ๋๋คํํ์์ด ์ ์ ํ ๊ฒ์ด๋ค
์ผ๋ฐํจ์
def square(x):
return x ** 2
def power_3(x):
return x ** 3
def power_4(x):
return x ** 4
powers = [ square, power_3, power_4 ]
for f in powers:
print( f(2) )
'''
4
8
16
'''
๋๋ค ํํ์
Lambdas = [
lambda x : x ** 2,
lambda x : x ** 3,
lambda x : x ** 4
]
for lambda_func in Lambdas:
print( lambda_func(2) )
'''
4
8
16
'''
๋ด๋ถ ๋๋ค ํํ์
def my_fun(n):
return lambda a : a ** n;
x = my_fun(2) #์ธ์ n
y = my_fun(3)
z = my_fun(4)
print(x(3)) #์ธ์ a
print(y(4))
print(z(5))
'''
9
64
625
'''
def check_password(password):
if len(password) < 8:
return 'SHORT_PASSWORD'
if not any(c.isupper() for c in password):
return 'NO_CAPITAL_LETTER_PASSWORD'
return True
lambda ๋งค๊ฐ๋ณ์๋ค : ์1 if ์กฐ๊ฑด์ else ์2 if ์กฐ๊ฑด์ else
๋๋ค ํํ์
lambdas = [
lambda password : 'SHORT_PASSWORD' if len(password) < 8 else 'NO_CAPITAL_LETTER_PASSWORD' if not any(c.isupper() for c in password) else True
]
def check_password_using_lambda(password):
for f in lambdas:
if f(password) is not None:
return f(password)
return True
print( check_password_using_lambda('123') ) # SHORT_PASSWORD
print( check_password_using_lambda('12356789f') ) # NO_CAPITAL_LETTER_PASSWORD
print( check_password_using_lambda('123456789F') ) # True
reference
https://dojang.io/mod/page/view.php?id=2359
https://m.blog.naver.com/scyan2011/221704493688
https://velog.io/@hj8853/TIL-9-Python-lambda-%ED%91%9C%ED%98%84%EC%8B%9D