[Python]lambda expressions

Jimin_Noteยท2022๋…„ 5์›” 29์ผ
0

[Python]

๋ชฉ๋ก ๋ณด๊ธฐ
26/34

๐Ÿ“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

๋žŒ๋‹ค ์‚ฌ์šฉํ•˜๊ธฐ

  • ํ‘œํ˜„์‹์ด๊ธฐ ๋•Œ๋ฌธ์— return์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค.
  • ๊ฐ„๋‹จํ•œ ์ธ๋ผ์ธ ์ฝœ๋ฐฑํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค๊ฑฐ๋‚˜ ํ•จ์ˆ˜์•ˆ์—์„œ ๋ณต์žกํ•œ ์ฒ˜๋ฆฌ๋ฅผ ํ•  ์ˆ˜ ์—†์„๋•Œ ์ฃผ๋กœ ์‚ฌ์šฉ ํ•œ๋‹ค.

๐Ÿ‘‰์ฝœ๋ฐฑํ•จ์ˆ˜๋ž€?
์–ด๋–ค ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ–ˆ์„ ๋•Œ ํ˜ธ์ถœ๋˜๋Š” ํ•จ์ˆ˜

์ฝœ๋ฐฑํ•จ์ˆ˜๊ฐ€ ์—ฌ๋Ÿฌ๋ธ”๋ก์œผ๋กœ ๊ตฌ์„ฑ๋œ ์‹คํ–‰๋ฌธ์ด ์•„๋‹ˆ๊ณ  ๋‹ค๋ฅธ ์ปดํฌ๋„ŒํŠธ์—์„œ ์‚ฌ์šฉ๋˜์ง€ ์•Š๋Š”๋‹ค๋ฉด ํ•ด๋‹น ์ปดํฌ๋„ŒํŠธ๋งŒ์„ ์œ„ํ•œ ๋žŒ๋‹คํ‘œํ˜„์‹์ด ์ ์ ˆํ•  ๊ฒƒ์ด๋‹ค

์ผ๋ฐ˜ํ•จ์ˆ˜

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
'''

types๋ชจ๋“ˆ

๐Ÿ“์•„๋ž˜ ํ•จ์ˆ˜๋ฅผ ๋žŒ๋‹ค ํ‘œํ˜„์‹์œผ๋กœ ๋ฐ”๊ฟ”๋ณด๊ธฐ

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

profile
Hello. I'm jimin:)

0๊ฐœ์˜ ๋Œ“๊ธ€