Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Python Slices Finding the biggest slice Your goal is to find the slice of a list that has the largest sum. You will find both
Python Slices
Finding the biggest slice Your goal is to find the slice of a list that has the largest sum. You will find both the largest sum as well as the indices starting and ending the slice. That is, if L13:91 is the largest slice and the sum of the elements is 508, you will return the tuple (500, 3, 9). Call your function slicesum and start at start and go up to but not including end First, a short and slow solution It's often useful to just get something working at first. In this case, it's possible to just try every slice, sum its elements, and find the max def slowslicesum(L): return max( (sum(L[i:j]), i,j for j in range(len(L)+1) for i in range(j)) # Let's try it a couple times to see. print (slowslicesum(1-1, 2, 3,11)) print(slowslicesum(I-1, 2, 3, -1, 4, -101)) Like a lot of one-liners, there's a lot in there. Let's break it down for practice understanding such expressions. It is taking the max of the sum of a slice for all possible slices of the list. We could have written it out more explicitly, as follows. def longslowslicesum(L) sums for j in range(len(L) 1): for i in range(j) sums.append((sum(Li:j), i, j)) return max(sums) hard to get it down to O(n2) time by precomputing the sums of some slices. Finding the biggest slice Your goal is to find the slice of a list that has the largest sum. You will find both the largest sum as well as the indices starting and ending the slice. That is, if L13:91 is the largest slice and the sum of the elements is 508, you will return the tuple (500, 3, 9). Call your function slicesum and start at start and go up to but not including end First, a short and slow solution It's often useful to just get something working at first. In this case, it's possible to just try every slice, sum its elements, and find the max def slowslicesum(L): return max( (sum(L[i:j]), i,j for j in range(len(L)+1) for i in range(j)) # Let's try it a couple times to see. print (slowslicesum(1-1, 2, 3,11)) print(slowslicesum(I-1, 2, 3, -1, 4, -101)) Like a lot of one-liners, there's a lot in there. Let's break it down for practice understanding such expressions. It is taking the max of the sum of a slice for all possible slices of the list. We could have written it out more explicitly, as follows. def longslowslicesum(L) sums for j in range(len(L) 1): for i in range(j) sums.append((sum(Li:j), i, j)) return max(sums) hard to get it down to O(n2) time by precomputing the sums of some slicesStep by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started