Daily Coding Problem sends daily coding problem sample when you subscribe to their service. This service is very useful to practice your coding ability and think through the logic you will be using to solve the problem.
This problem was asked by Uber.
Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
Follow-up: what if you can’t use division?
The key to above problem is to multiply all the numbers in the list except the one at index “i”. Index “i” in this case is the value where that index was pointed during the iteration.
If the given list is [1, 2, 3, 4, 5], the calculation will be:
[2*3*4*5] where the output should be 120
then the next will be
[1*3*4*5] and the output will be 60
and so on…
On each computation, you need to add them in to new list and eventually, you need do complete a list looks like [120, 60, 40, 30, 24].
We know that to get the product, you just need to multiply all the numbers in the list except the index at i. We also know that anything you multiply by 1 has pretty much no effect. So What I did is, for the value we need to skip, replace with value of 1. once the multiplication is done in the list, put back the original value and move on to next computation. Below is the sample code.
given_list = [1, 2, 3, 4, 5] def compute(a_list): new_list =  for index, value in enumerate(a_list): original_list = a_list original_int = original_list[index] original_list[index] = 1 result = 1 for x in original_list: result = result * x new_list.append(result) original_list[index] = original_int return new_list r = compute(given_list) print(r)
Sample Code Download
Download from here