Last active
May 9, 2021 04:53
-
-
Save Julisam/69d792463f2d86dcf3caf951c34abeb0 to your computer and use it in GitHub Desktop.
AlgorithmFriday_Week4
This file contains hidden or 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
def get_product(nums=[]): | |
""" | |
Given an integer array nums, | |
returns an arry products, such that each entry at position i, in products is a produc of all the other lements in nms except num[i] | |
Examle: nums=[4,5,10,2] | |
Output: [100,80,40,200] | |
""" | |
try: | |
#check for cases of Null array | |
if nums==None: | |
return [] | |
#check for cases of an empty array | |
elif len(nums) == 0: | |
return [] | |
#check for cases of one-element array | |
elif len(nums) == 1: | |
return [1] | |
#check for cases of two-element (just swap element) | |
elif len(nums) == 2: | |
return nums[::-1] | |
else: | |
arr_prod=1 | |
for i in nums: | |
arr_prod *=i | |
start = 0 | |
end = len(nums)-1 | |
while(start<=end): | |
if (start != end): | |
nums[start] = arr_prod//nums[start] | |
nums[end] = arr_prod//nums[end] | |
else: | |
nums[start] = arr_prod//nums[start] | |
# move pointer forward and backward | |
start += 1 | |
end -= 1 | |
return nums | |
except: | |
return [] |
Thank you for your honest review. I really appreciate it.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello @Julisam, thank you for participating in Week 4 of Algorithm Fridays.
This is a really neat solution, one I like very much - from your optimization on lines 20 and 24 to your use of the two-pointer concept. Very clean!
The one test case your solution doesn't pass however, is when one of the entries of the array is 0.
Another not-so-serious thing I'd say is you can combine the conditions on line 12 and 16 into one,
if (nums == None) || len(nums) == 0
, but apart from that, this is a great attempt!