Skip to content

Instantly share code, notes, and snippets.

@arsho
Last active May 7, 2019 03:22
Show Gist options
  • Save arsho/99a5adbdd2493e7a530dcc695ccab4bb to your computer and use it in GitHub Desktop.
Save arsho/99a5adbdd2493e7a530dcc695ccab4bb to your computer and use it in GitHub Desktop.
Several Python functions example
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)
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment