[英]How do I check if the given number is the sum of a list slice?
I have a python
list
consist of integers.我有一个python
list
由整数组成。 I need to find whether the given number is sum(mylist[some slice])
我需要找出给定的数字是否为sum(mylist[some slice])
a = [1, 2, 2, 3, 3, 5, 5, 6, 6]
num = 22
Answer will be either [3, 3, 5, 5, 6] or [5, 5, 6, 6]
#'.' sum([3, 3, 5, 5, 6]) == 22 || sum([5, 5, 6, 6]) == 22
So far I have done something like a recursive way.到目前为止,我已经做了类似递归的方法。 Note: I am getting the expected output注意:我得到了预期的 output
def find_slice(mylist, num, extra=2):
if len(mylist) == 0:
return None
for i in range( len(mylist )-1):
if sum( mylist[:extra + i] ) == num:
return mylist[ :extra + i]
return find_slice(mylist[1:], num, extra+1)
>>> a = [1, 2, 2, 3, 3, 5, 5, 6, 6]
>>> print(find_slice(a, 22))
[3, 3, 5, 5, 6]
In terms of time complexity, it takes O(n!)
(N factorial) .就时间复杂度而言,它需要O(n!)
(N factorial) 。
How can I modify this in terms of time complexity
and space complexity
?如何在time complexity
和space complexity
方面进行修改? Or Is there any better approach?或者有没有更好的方法?
you can use a window while you are iterating over your items:您可以在迭代项目时使用 window :
a = [1, 2, 2, 3, 3, 5, 5, 6, 6]
num = 22
def find_slice(mylist, num):
window = []
for e in a:
window.append(e)
s = sum(window)
if s > num:
window.pop(0)
while sum(window) > num:
window.pop(0)
s = sum(window)
if s == num:
return window
print(find_slice(a, num))
# [3, 3, 5, 5, 6]
this will be O(n) time complexity and O(n) space这将是 O(n) 时间复杂度和 O(n) 空间
Adding to @kederrac's sliding window solution, its worth mentioning that popping the first item with pop(0)
is O(N)
, whereas popping the last item from the end with pop(-1)
is O(1)
.添加到@kederrac 的滑动 window 解决方案中,值得一提的是,使用pop(0)
第一项是O(N)
,而使用pop(-1)
从末尾弹出最后一项是O(1)
。 We can see this comparison in the Time Complexity - Python Wiki .我们可以在时间复杂度 - Python Wiki中看到这种比较。
We can make popping the first item O(1)
using popleft
from collections.deque
:我们可以使用popleft
中的collections.deque
弹出第一项O(1)
:
Remove and return an element from the left side of the deque.从双端队列的左侧移除并返回一个元素。 If no elements are present, raises an IndexError.如果不存在任何元素,则引发 IndexError。
Modified code:修改后的代码:
from collections import deque
a = [1, 2, 2, 3, 3, 5, 5, 6, 6]
num = 22
def find_slice(mylist, num):
window = deque()
for e in a:
window.append(e)
s = sum(window)
if s > num:
window.popleft()
while sum(window) > num:
window.popleft()
s = sum(window)
if s == num:
return window
print(list(find_slice(a, num)))
# [3, 3, 5, 5, 6]
The solution above should now be approximately O(N * W)
, where N
is the number of elements in the list, and W
is the window size.上面的解决方案现在应该约为O(N * W)
,其中N
是列表中的元素数, W
是 window 大小。 I don't think you can get much better than this.我不认为你能得到比这更好的了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.