Efficient way to find missing elements in an integer sequence

前端 未结 16 1360
鱼传尺愫
鱼传尺愫 2020-12-01 04:32

Suppose we have two items missing in a sequence of consecutive integers and the missing elements lie between the first and last elements. I did write a code that does accomp

16条回答
  •  再見小時候
    2020-12-01 05:14

    With this code you can find any missing values in a sequence, except the last number. It in only required to input your data into excel file with column name "numbers".

    import pandas as pd
    import numpy as np
    
    data = pd.read_excel("numbers.xlsx")
    
    data_sort=data.sort_values('numbers',ascending=True)
    index=list(range(len(data_sort)))
    data_sort['index']=index
    data_sort['index']=data_sort['index']+1
    missing=[]
    
    for i in range (len(data_sort)-1):
        if data_sort['numbers'].iloc[i+1]-data_sort['numbers'].iloc[i]>1:
            gap=data_sort['numbers'].iloc[i+1]-data_sort['numbers'].iloc[i]
            numerator=1
            for j in range (1,gap):          
                mis_value=data_sort['numbers'].iloc[i+1]-numerator
                missing.append(mis_value)
                numerator=numerator+1
    print(np.sort(missing))
    

提交回复
热议问题