본문 바로가기
LeetCode/Problems

Daily Coding Problem #5

by 벤진[Benzene] 2020. 6. 19.

Problem:

cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.

 

Given this implementation of cons:

def cons(a, b):
    def pair(f):
        return f(a, b)
    return pair

Implement car and cdr.

 

-Summary-

def car(pair):
    def return_first(a, b):
        return a
    return pair(return_first)

def cdr(pair):
    def return_last(a, b):
        return b
    return pair(return_last)

이번문제를 풀면서 python closures 라는 개념에 대해 배웠다.

https://www.learnpython.org/en/Closures#:~:text=A%20Closure%20is%20a%20function,variables%20of%20the%20enclosing%20scope.

 

Learn Python - Free Interactive Python Tutorial

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 575,000 other learners and get started learning Python for data science today! Welcome Welcome to the LearnPython.org interactive Pyth

www.learnpython.org

 

'LeetCode > Problems' 카테고리의 다른 글

LeetCode 91. Decode Ways  (0) 2020.06.21
LeetCode 226. Invert Binary Tree  (0) 2020.06.20
Floor and Ceiling of a Binary Search Tree  (0) 2020.06.19
LeetCode 41. First Missing Positive  (0) 2020.06.18
LeetCode 665. Non-decreasing Array  (0) 2020.06.18

댓글