-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2389.py
51 lines (38 loc) · 1.37 KB
/
2389.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
47
48
49
50
51
from typing import List
import unittest
import itertools
import bisect
class Solution:
# def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
# result: List[int] = []
# numsSize = len(nums)
# for query in queries:
# total, i = 0, 0
# while i < numsSize and (total + nums[i] <= query):
# total += nums[i]
# i += 1
# result.append(i)
# return result
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
"""Prefix sum approach: it uses itertools.accumulate to create a new
list with the result of accumulation of previous + current item.
Than it uses bisect.bisect_right to find the next index of greater number of n.
"""
nums.sort()
numsSum = list(itertools.accumulate(nums))
return [bisect.bisect_right(numsSum, n) for n in queries]
class Test(unittest.TestCase):
def setUp(self):
self.solution = Solution()
def test_first(self):
self.assertEqual(
self.solution.answerQueries(nums=[1, 2, 4, 5], queries=[3, 10, 21]),
[2, 3, 4],
)
def test_second(self):
self.assertEqual(
self.solution.answerQueries(nums=[2, 3, 4, 5], queries=[1]),
[0],
)
if __name__ == "__main__":
unittest.main()