Last active
May 7, 2019 03:22
-
-
Save arsho/99a5adbdd2493e7a530dcc695ccab4bb to your computer and use it in GitHub Desktop.
Several Python functions example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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