Skip to content

Instantly share code, notes, and snippets.

@spence
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spence/b10809b41e968fc731cc to your computer and use it in GitHub Desktop.
Save spence/b10809b41e968fc731cc to your computer and use it in GitHub Desktop.
def get_products_of_all_ints_except_at_index(int_array):
"""
Single pass.
"""
# Condition where element has neither left nor right elements
if len(int_array) == 1:
# Maybe [None] ?
return [0]
left_product = 1
right_product = 1
products = [1] * len(int_array) # init array
for left_index in xrange(len(int_array)):
right_index = len(int_array) - 1 - left_index
products[left_index] *= left_product
products[right_index] *= right_product
if left_index == 0:
left_product = int_array[left_index]
right_product = int_array[right_index]
else:
left_product *= int_array[left_index]
right_product *= int_array[right_index]
return products
print get_products_of_all_ints_except_at_index([3, 1, 2, 6, 5, 9]) # [540, 1620, 810, 270, 324, 180]
print get_products_of_all_ints_except_at_index([1, 7, 3, 4]) # [84, 12, 28, 21]
print get_products_of_all_ints_except_at_index([1]) # [0]
print get_products_of_all_ints_except_at_index([]) # []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment