I have a list of numbers like so (randomly generated, numbers sorted within each sub-group. The groups are disjoint, meaning you won’t find a given number in more than one group):
L=[[19,18,14,9,4],[15,12,11,10,6,5],[8],[16,13,3,2],[17,7,1]]
I am trying to count the number of ways I can create a decreasing-triplet.
A decreasing-triplet is a triplet where we scan the list from left to right and pluck out element 1 from a group, then element 2 from another group, then element 3 from another group where the end result should be in decreasing order naturally.
For instance, (19,11,7) is a valid decreasing triplet because these numbers come from different sub-lists and are in decreasing, natural order (19 comes before 11 which comes before 7 in the master list).
To clarify with a counter-example: (15, 9, 8) would not be a decreasing triplet because the 9 is coming from an earlier sublist than 15.
I am trying to count the number of decreasing triplets using dynamic programming or memoization of some sort. It is easy enough to set up a loop structure like so:
for i in xrange(0,len(L)-2):
for j in xrange(i+1, len(L)-1):
for k in xrange(j+1, len(L)):
for item1 in L[i]:
for item2 in L[j]:
if item1>item2:
for item3 in L[k]:
if item2>item3:
count+=1
But it does not scale very well for larger lists. I feel like there should be some way to count triplets by going through the list once. For instance, if I know one number is larger than another (or if I know how many numbers it’s larger than), I feel like I should be able to re-use that information later.
For instance, I know 16 can come before 7 or 1 in a valid triplet. That’s 2 “pairs.” Therefore, if I am looking to create a triplet as I go backward in the list, and I look at, say, 19, I should be able to say “It’s bigger than 16, therefore you can create two triplets from this because we know 16 is larger than 2 numbers.” and so on.
I am just thinking out loud but would appreciate some insight.
Use an index
ibetween0andninstead of nested loops.Keep track of the last element of the current triplet.
And use a memo to make it efficient.