Get nth Fibonacci number using reduce

from functools import reduce


def get_first_n_fibonacci(n):
    if n<1:
        return []
    ar = [0, 1]
    for i in range(2, n):
        ar.append(ar[i-1] + ar[i-2])
    return ar[:n]


def get_first_n_fibonacci_reduce(n):
    initializer = [0, 1]
    if n<2:
        return initializer[:n]
    ar = reduce(lambda fib, _: fib + [fib[-1] + fib[-2]], range(n-2), initializer)
    return ar


if __name__ == '__main__':
    assert get_first_n_fibonacci(5) == get_first_n_fibonacci_reduce(5)
    assert get_first_n_fibonacci(0) == get_first_n_fibonacci_reduce(0)
    assert get_first_n_fibonacci(1) == get_first_n_fibonacci_reduce(1)
    assert get_first_n_fibonacci(10) == get_first_n_fibonacci_reduce(10)

List multiplication using reduce

from functools import reduce


def get_list_multiplication(ar):
    result = 1
    for i in ar:
        result *= i
    return result

def get_list_multiplication_using_reduce(ar):
    return reduce(lambda x, y: x*y, ar, 1)

if __name__ == '__main__':
    ar = [3, 1, 4, 5, -23]
    assert get_list_multiplication(ar) == get_list_multiplication_using_reduce(ar)

Reference

Advertisement

Cite This Work
APA Style
Shovon, A. R. (2018, May 7). Python Reduce Example. Ahmedur Rahman Shovon. Retrieved March 25, 2024, from https://arshovon.com/snippets/python-reduce-example/
MLA Style
Shovon, Ahmedur Rahman. “Python Reduce Example.” Ahmedur Rahman Shovon, 7 May. 2018. Web. 25 Mar. 2024. https://arshovon.com/snippets/python-reduce-example/.
BibTeX entry
@misc{ shovon_2018,
    author = "Shovon, Ahmedur Rahman",
    title = "Python Reduce Example",
    year = "2018",
    url = "https://arshovon.com/snippets/python-reduce-example/",
    note = "[Online; accessed 25-March-2024; URL: https://arshovon.com/snippets/python-reduce-example/]"
}
Next Post

8-diamond