-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2020-01-26.py
46 lines (37 loc) · 1.28 KB
/
2020-01-26.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""
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?
"""
from math import log, exp
from typing import List
Vector = List[int]
def set_minus_one_product(user_list: Vector):
if not user_list:
return 0
product = 1
for item in user_list:
product *= item
result: Vector = list()
for item in user_list:
result.append(int(product / item))
return result
def set_minus_one_product_no_div(user_list: Vector):
if not user_list:
return 0
product = 1
for item in user_list:
product *= item
log_product = log(product)
result: Vector = list()
for item in user_list:
result.append(round(exp(log_product - log(item))))
return result
if __name__ == "__main__":
input_list = [1, 2, 3, 4, 5]
result = set_minus_one_product(input_list)
assert result == [120, 60, 40, 30, 24]
result = set_minus_one_product_no_div(input_list)
assert result == [120, 60, 40, 30, 24]