Last active
July 21, 2017 18:02
-
-
Save kylelemons/98ab9a3c461bb8fb166589d39e38ee21 to your computer and use it in GitHub Desktop.
Get the products of a list excluding the current element
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
#!/usr/bin/python3 | |
def getProducts(values): | |
""" Return an array where each index is the product of all other values, runs in O(N) time """ | |
left = [] | |
leftProduct = 1 | |
right = [] | |
rightProduct = 1 | |
for i in range(len(values)): | |
left.append(leftProduct) | |
leftProduct *= values[i] | |
right.append(rightProduct) | |
rightProduct *= values[-1 - i] | |
return [l * r for l, r in zip(left, reversed(right))] |
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
#!/usr/bin/python3 | |
# This is a one-liner that computes an array were each index is the product of all other values, runs in O(N^2) time | |
getProducts = lambda v: [reduce(lambda x,y: x*y, [val for i, val in enumerate(v) if i != t]) for t in range(len(v))] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment