I promise I’ve tried searching, but every single question I find ends up having some criteria unstated or violated that makes the answer insufficient for me.
I’m sending a list to a Python script. That list will be stored somewhere, but I want to minimize writes (this is on a remote service and I get charged for each write).
listNew = ["some", "list", "sent", "in", "that", "may", "be", "different", "later", "some"]
listPrevious = ["some", "some", "list", "that", "was", "saved", "previously"]
(Please don’t get distracted by their being strings; my list actually contains ints.)
The simple, basic algorithm is to iterate both lists on an index-by-index basis. If the items are the same, I don’t need to write; boom, money saved. The data ultimately saved, however, should be listNew.
In other languages, I could directly reference elements by index.
for (int i = 0; i < listNew.length; i++) {
// Have we exceeded the previous list's length? Time to just write data in.
if (listPrevious[i] == null)
listPrevious.append(listNew[i]);
continue;
if (listNew[i] != listPrevious[i])
listPrevious[i] = listNew[i]
}
Unfortunately, what I’ve found in looping techniques and list methods doesn’t provide:
-
the means to get elements by index without removing it (pop method), nor
-
the means to get the index of an element by exact value and positioning, since I have duplicates (in the above code, using
list.index(“some”) would return the first index in listPrevious
though I’m actually looking at the last element in listNew), nor -
the means to iterate through my lists beyond the length of one of the lists (zip() doesn’t iterate beyond the length of the smaller list, it seems).
Any ideas on how I should handle this? One of those three criteria were always violated in some way when I searched through previous questions.
I’m trying to avoid a solution like the following, by the way, which is also among the marked solutions in other questions.
for newitem in listNew
for olditem in listPrevious
if newitem != olditem
# save the newitem
That compares the element from listNew with every single element in listPrevious, which is inefficient. I just need to know if it matches at the same index in the other list.
——- By Comment Request
Input: 2 lists, listNew and listPrevious. Another example
- listNew = [100, 500, 200, 200, 100, 50, 700]
- listPrevious = [100, 500, 200, 400, 400, 50]
Output: listPrevious is now listNew without having to overwrite elements that were the same.
listPrevious = [100, 500, 200, 200, 100, 50, 700]
-
did not require writes: [100, 500, 200, _, , 50, __] <- 4 writes saved
-
did require writes : [_, , __, 200, 100, __, 700] <- 3 writes executed, not .length writes executed!
From you C code I have created the following. Hopefully it does what you want: