Prepare > Python > Python Functionals > Map and Lambda Function
2023. 8. 25. 19:30ㆍHackerRank-Python
Map and Lambda Function | HackerRank
This challenge covers the basic concept of maps and lambda expressions.
www.hackerrank.com
문제
Input Format
One line of input: an integer N.
output Format
A list on a single line containing the cubes of the first N fibonacci numbers.
=> 정수 N을 줄건데 피보나치 수열의 첫 N개의 세제곱 값을 리스트에 담아라
코드
cube = lambda x: x ** 3
# complete the lambda function
def fibonacci(n):
# return a list of fibonacci numbers
fibonacci = []
old = 0
new = 1
while len(fibonacci) < n:
fibonacci.append(old)
temp = new
new = old + new
old = temp
return fibonacci
if __name__ == '__main__':
n = int(input())
print(list(map(cube, fibonacci(n))))
노트
map
list(map([적용할 함수], [함수에 들어갈 객체]))
- 객체 하나하나에 함수를 적용하고, list에 넣어 반환
- list가 아니라 tuple등 과 같은 다른 자료형도 가능
- 언패킹도 가능
print(list(map(len, ['Tina', 'Raj', 'Tom'])))
# [4, 3, 3]
lambda
# 기본적인 함수 형태
def 함수이름(입력변수):
return 리턴값
# 람다함수로 나타내면
lambda 입력변수: 리턴값
- 정의와 동시에 사용 가능
- return 문을 사용할 수 없음
- 단일 표현식만 가질 수 있음
- 함수를 생성하고 함수 자체를 반환(def 는 함수를 생성하고 이름을 할당)
- 따라서 재사용 불가
- lists 와 dictionaries 내에서 사용 가능
sum = lambda a, b, c: a + b + c
sum(1, 2, 3)
# 6
두 번째 시도
cube = lambda x: pow(x, 3)
def fibonacci(n):
fibonacci = []
old = 0
new = 1
while len(fibonacci) < n:
fibonacci.append(old)
temp = old
old = new
new = new + temp
return fibonacci
- 같음
old와 new를 갱신하는 쉬운 방법
cube = lambda x: pow(x, 3)
def fibonacci(n):
fibonacci = []
old = 0
new = 1
while len(fibonacci) < n:
fibonacci.append(old)
old, new = new, new + old
return fibonacci
- old, new = new, new + old
참조
4) 람다함수(익명함수)
파이썬에서는 람다함수를 통해 이름이 없는 함수를 만들 수 있습니다. 람다함수의 장점은 코드의 간결함 메모리의 절약이라고 생각할 수 있습니다. `def`키워드를 통해서 함수를 …
wikidocs.net
'HackerRank-Python' 카테고리의 다른 글
Prepare > Python > Numpy > Shape and Reshape (0) | 2023.08.27 |
---|---|
Prepare > Python > Numpy > Arrays (0) | 2023.08.26 |
Prepare > Python > Errors and Exceptions > Incorrect Regex (0) | 2023.08.24 |
Prepare > Python > Errors and Exceptions > Exceptions (0) | 2023.08.22 |
Prepare > Python > Date and Time > Calendar Module (0) | 2023.08.21 |