I was asked to write a python function that 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. For example a list l containing the elements [4, 3, 5, 7, 8] and the key t as 12, the function would return the list [0,2] since the list contains the indexes of the values 4,3 and 5 and another list l containing the elements [1,2,3,4] and key t to be 15, the function would return [-1,-1] because there is no sub-list of list l that can be summed up to the given target value t = 15. I am supposed to write a function that identifies the first given sub-list that sums up to the key t, it should hence only return one sub-list. The sub-list can only be identified by the following:
- Each list l will contain at least 1 element but never more than 100.
- Each element of l will be between 1 and 100.
- t will be a positive integer, not exceeding 250.
- The first element of the list l has index 0.
- For the list returned by solution(l, t), the start index must be equal or smaller than the end index. So far I have been able to implement the first two examples I had mentioned earlier. This is what I have tried so far:
def solution(l, t):
if len(l) <= 100 and len(l) > 0 and t > 0 and t <= 250:
if all(a<100 for a in l):
for j in range(0, len(l) - 1):
for k in range(0, len(l)):
for m in range(0, len(l)):
if l[j] + l[k] == t or l[j] + l[k] + l[m] == t:
if j + 1 == k and k + 1 == m:
return (j, k) if l[j] + l[k] == t else (j,k, m) if l[j] + l[k] + l[m] == t else (-1,-1)
return (-1,-1)
else:
return False
else:
return False
My function only returns a list of maximum 3 values and I want it to return any number of values. Please help me as this is due in 4 days. Help is very much appreciated and please go easy on me as I have little experience in python.