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