Skip to content

Instantly share code, notes, and snippets.

@kylelemons
Last active July 21, 2017 18:02
Show Gist options
  • Save kylelemons/98ab9a3c461bb8fb166589d39e38ee21 to your computer and use it in GitHub Desktop.
Save kylelemons/98ab9a3c461bb8fb166589d39e38ee21 to your computer and use it in GitHub Desktop.
Get the products of a list excluding the current element
#!/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))]
#!/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