You have a sequence of numbered items and want to check if any are missing, which ones, how many gaps are found in the sequence, etc.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
missing/missing.py

88 lines
2.1 KiB

# main function
def missing(integers):
'''Return a list of missing numbers in a sequence of integers.'''
rangemin = min(integers)
rangemax = max(integers)
full_range_set = set(range(rangemin, rangemax))
integers_set = set(integers)
if integers_set.issubset(full_range_set):
missing_set = full_range_set.difference(integers_set))
return missing_set
else:
raise ValueError
# import data
def print_iccd(num):
n = int(num)
print('{}'.format(n))
def import_seq(source):
lines = open(source).readlines()
nums = []
for n in lines:
try:
nint = int(n.strip())
except ValueError:
print('Error: {}'.format(n))
else:
nums.append(nint)
nums = sorted(nums)
return nums
# plot what data we have
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8,1))
ax.get_yaxis().set_visible(False)
ax.plot(nctn, [0.0]*len(nctn), '|', color='k')
ax.plot(ftan, [0.1]*len(ftan), '|', color='b')
ax.margins(0.05, 1)
plt.grid()
plt.show()
# range functions
def ranges(nums):
'''Return a list of continuous ranges (min, max values) from a list of integers.'''
rgs = [[nums[0]]]
# these two make the code more readable and, incidentally, faster
FIRST, LAST = 0, -1
for n in nums:
if rgs[LAST][LAST] == n - 1:
if rgs[LAST][FIRST] == n -1:
rgs[LAST].append(n)
if rgs[LAST][FIRST] < n - 1:
rgs[LAST][LAST] = n
elif rgs[LAST][LAST] < n -1:
rgs.append([n])
return rgs
def seq_from_rgs(rgs):
'''Return a list of integers from a list of ranges.'''
seq = []
for rg in rgs:
if len(rg) == 1:
seq.extend(rg)
elif len(rg) == 2:
seq.extend(range(rg[0], rg[1] + 1))
else:
print('Error: {}'.format(rg))
def prt_rgs(rgs):
for r in rgs:
try:
print('{} - {}: {} schede'.format(r[0], r[1], r[1] - r[0] + 1))
except IndexError:
print('{}: 1 scheda'.format(r[0]))