My solution for Python3 Product of Everything Else (or Everything)
Found the one condition that if all integers are the same (in the array), to be the challenge
INSTRUCTIONS:
Product of Everything Else
Create a product_of_the_others()
function that takes in an array of integers and replaces each number in the array with the product of all the numbers in the array except the number at that index itself.
For example, product_of_the_others([1, 2, 3, 4, 5])
should return [120, 60, 40, 30, 24]
, and product_of_the_others([5, 5, 5])
should return [25, 25, 25]
.
def product_of_the_others(array):
# Write your code here
total = 1
total_product = []
same_product = []
for i in range(0, len(array)):
if len(array) <= 1:
return array[i]
#this was the challenging condition
elif len(set(array)) == 1:
for n in array:
same_product.append(n * n)
return same_product
for num in array:
if num != array[i]:
total *= num
total_product.append(total)
total = 1
return total_product
#Tests
print(product_of_the_others([1, 2, 3, 4, 5]))
print(product_of_the_others([1, 2, 3]))
print(product_of_the_others([9]))
print(product_of_the_others([]))
print(product_of_the_others([5, 5, 5]))
print(product_of_the_others([4, 4]))