I have a list I
arranged in order of increasing j
. I want to find the missing j
values. (To clarify, for [[8, 1]]
, i=8,j=1
). The desired output is attached.
I=[[[8, 1]],
[[1, 2]],
[[0, 3]],
[[15, 7]],
[[7, 8]],
[[2, 9], [8, 9]],
[[9, 10]]]
The desired output is:
Missing=[4,5,6]
How can I produce the desired output?
CodePudding user response:
Generate a set of numbers that do appear in the list, and then identify the missing numbers by determining whether or not they appear in the set:
minimum = I[0][0][1]
maximum = I[-1][0][1]
included_numbers = {entry for sublist in I for _, entry in sublist}
[i for i in range(minimum, maximum) if i not in included_numbers]
This outputs:
[4, 5, 6]
CodePudding user response:
The easiest would be to use sets. One set with the expected j
values and one with the actual values. Then you can subtract the sets and print the missing ones.
items = [[[8, 1]],
[[1, 2]],
[[0, 3]],
[[15, 7]],
[[7, 8]],
[[2, 9], [8, 9]],
[[9, 10]]]
expected = set(range(1, 11))
actual = set([item[0][1] for item in items])
print(expected - actual)
If you need the output as a list, simply cast to a list like so:
missing = list(expected - actual)
CodePudding user response:
Assuming the value starts at 1, the following code can solve the problem"
def find_missing(I):
current_max = 1
missing = []
for row in I:
for i,j in row:
if j > current_max:
missing.extend(list(range(current_max,j)))
current_max = j 1
return missing