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

Citation

Click to select citation style

Shovon, A. R. (2018, May 7). Python Reduce Example. Ahmedur Rahman Shovon. Retrieved December 3, 2024, from https://arshovon.com/blog/python-reduce-example/

Shovon, Ahmedur Rahman. “Python Reduce Example.” Ahmedur Rahman Shovon, 7 May. 2018. Web. 3 Dec. 2024. https://arshovon.com/blog/python-reduce-example/.

@misc{ shovon_2018,
    author = "Shovon, Ahmedur Rahman",
    title = "Python Reduce Example",
    year = "2018",
    url = "https://arshovon.com/blog/python-reduce-example/",
    note = "[Online; accessed 3-December-2024]"
}
Python Reduce Example
Python Reduce Example
Next post

8-diamond