-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSequence_sum.py
70 lines (61 loc) · 1.6 KB
/
Sequence_sum.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""
Given a non-empty list of positive integers l and a
target positive integer t, write a function solution(l,
t) which verifies if there is at least one consecutive
sequence of positive integers within the list l (i.e.
a contiguous sub-list) that can be summed up to the
given target positive integer t (the key) and returns
the lexicographically smallest list containing the
smallest start and end indexes where this sequence can
be found, or returns the array [-1, -1] in the case
that there is no such sequence (to throw off Lambda's
spies, not all number broadcasts will contain a coded
message).
-- Python cases --
Input:
solution.solution([1, 2, 3, 4], 15)
Output:
-1,-1
Input:
solution.solution([4, 3, 10, 2, 8], 12)
Output:
2,3
"""
import queue
def solution(l, t):
start = stop = 0
while start <= stop and stop < len(l):
s = sum(l[start:stop+1])
if s == t:
return [start, stop]
elif s < t:
stop += 1
else:
start += 1
stop = max(start, stop)
return [-1, -1]
def solution_queue(l, t):
queue = []
sum = 0
for i, elem in enumerate(l):
# print(elem)
queue.append(elem)
sum += elem
if sum > t:
sum -= queue.pop(0)
# print(sum)
if sum == t:
return i + 1 - len(queue), i
return [-1, -1]
print(solution_queue([250,0,0], 250))
print(solution_queue([1,2,3,4], 15))
print(solution_queue([4, 3, 10, 2, 8], 12))
print(solution_queue([4, 3, 5, 7, 8], 12))
print(solution_queue([260], 260))
'''
[0, 0]
[-1, -1]
[2, 3]
[0, 2]
[0, 0]
'''