I’m trying to find the most pythonic way to find out if numbers in a list are sequential. To give some background, I have a list of numbers gathered that exist in a folder, and I need to find out which numbers are missing.
I gather all of the numbers, and then make another list from the range(beginning, end+1) of what numbers should be there. I very easily made something to show me all of the numbers missing:
missing = [x for x in existingNumbers if x not in shouldBeNumbers]
The problem is that if I print out all of those, there are a lot of numbers that could be condensed (i.e. 1, 2, 3, 4, 7, 10 could be printed as 1-4, 7, 10) because there could be massive amounts of numbers missing.
I’ve tried two approaches:
For both ways, frameRange is range(startFrame, endFrame+1) and frameList is a list generated from what exists currently.
1)
for x in frameRange:
if x not in frameList:
if originalFrame == None:
originalFrame = x
elif originalFrame:
if lastFrame == None:
lastFrame = x
elif lastFrame:
if lastFrame == x-1:
lastFrame = x
else:
if originalFrame != lastFrame:
missingFrames.append(str(originalFrame)+"-"+str(lastFrame))
originalFrame = x
lastFrame = x
else:
missingFrames.append(str(originalFrame))
originalFrame = x
lastFrame = x
if x == endFrame:
if originalFrame != lastFrame:
missingFrames.append(str(originalFrame)+"-"+str(lastFrame))
originalFrame = x
lastFrame = x
else:
missingFrames.append(str(originalFrame))
originalFrame = x
lastFrame = x
2)
i = 0
while i < len(frameRange):
if frameRange[i] in frameList:
i += 1
else:
if i + 1 < len(frameRange):
if frameRange[i + 1] in frameList:
missingFrames.append(str(frameRange[i]))
i += 1
else:
j = 1
while frameRange[i+j] not in frameList:
aheadFrameNumber = int(str(j))
if i + j + 1 < len(frameRange):
j += 1
else:
break
missingFrames.append(str(frameRange[i])+"-"+str(frameRange[aheadFrameNumber]))
if i + aheadFrameNumber + 1 < len(frameRange):
i += aheadFrameNumber + 1
else:
missingFrames.append(str(frameRange[i]))
The first way was working, but since it happens on the current frame checking the last, whenever the last frame was gone it wouldn’t append the last missing section to the list. For the second way I had to keep wrapping everything in if statements because I kept getting index exceptions when moving forwards.
I think I have to step back, re-think, and approach it differently. I’m wondering if there is a much better way to do this in python that I haven’t thought about yet because I don’t know the function. Both ways started to get a little out of hand.
Try something like this
which for
numbers = [1,4,6,10, 12,]and numbers should be present are from 1 to 40 you will have :