slices of the list in this file sum up to at least 32?
How manyDetails and Assumptions:
[4,5,6]
is a slice of
[1,2,3,4,5,6,7,8,9]
but
[3,4,5,7]
is not.
[-23,5,20,21,18]
. This slice can be found near the end of the array.
[1,-2,3,-4,5]
There are 6 such slices:
[[1, -2, 3], [1, -2, 3, -4, 5], [-2, 3, -4, 5], [3], [3, -4, 5], [5]]
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
It is.
How can we improve on the number of operations performed?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Doesn't this code evaluate every possible slice of the list?
Log in to reply
nah, just the partial sums.
using:
sum(array[lo:hi]) == sum(array[:hi]) - sum(array[:lo])
, it goes through each partial sum of the array and searches for another that would give it a difference greater than or equal to 32.
since there are
n
elements to consider and
n
partial sums, the algorithm runs in
O
(
n
2
)
time without ever recalculating a slice's sum.
side note: although I changed the code, the first one had the same complexity; it walked through a dict w/ partial sums as keys, and a list of indices where they appear as values. the new one just walks through the partial sums linearly (I realized I was over-complicating things w/ the dict thanks to Chew-Seong Cheong's answer :p)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Yay level 5 lol, its jest sub-array checking. I posted basic function and tweaked to problem. Just replace array with set of numbers, and 32 with target.
Python code
arr = [-22,-26,16, … 21,18,32]
def simple():
n = 0
for a in range(len(arr)):
for b in range(a, len(arr)):
if sum(arr[a:b+1]) >= 32:
n += 1
print n
def faster():
sums = [0]
for i in range(len(arr)):
sums += [sums[-1] + arr[i]] # or use itertools.accumulate
n = 0
for a in range(len(sums) - 1):
for b in range(a+1, len(sums)):
if sums[b] - sums[a] >= 32:
n += 1
print n
a=open("list-GfO0iB928U.txt","r")
b=a.readline().split(",")
c=[]
for i in b:
c.append(int(i))
count=0
for x in range(1,len(c)+1):
for y in range(len(c)-x+1):
m=sum(c[y:y+x])
if m>=32:
count+=1
print count
Nice and compact, but also a bit slow. Mathematica
1 2 |
|
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 |
|
This is a problem for which a so-called sliding window iterator is a good part of a solution. As someone first said, 'Good programmers are lazy.' Accordingly, I've copied code from http://stackoverflow.com/questions/6822725/rolling-or-sliding-window-iterator-in-python.
I don't know if this is by any means the fastest iterator for this job.
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 |
|
Problem Loading...
Note Loading...
Set Loading...
I used the following Python coding. I think it is simple.