This code snippet is designed to find the missing number in a sequence of integers with python 2.7.
I’ve tested it with several lists in python which are commented at the start of the script.
#!/usb/bin/python #miguel.ortiz #s=[-1, -4, -7, -10, -13, -16, -19, -25, -28] #s=[1, 4, 7, 10, 13, 16, 19, 25, 28] s=[1.1,2,3,4,5,6,7,8,10] #s=[1, 3, 4, 5, 6, 7, 8, 9] #s=[-1, 2, 5, 8, 11, 14, 17, 20,26] diff=[] for i,j in zip(s,s[1:]): diff.append(i - j) for x,y in zip(diff,diff[1:]) : if not x == y : pointer=s[diff.index(y)] if pointer < 0 : number= s[diff.index(y) -1] + -(y) break else : number= s[diff.index(y) -1] + abs(y) break print number
The next snippet do the same thing in less code:
#!/usb/bin/python #s=[-1, -4, -7, -10, -13, -16, -19, -25, -28] s=[1,2,3,4,5,6,7,8,10] return (s[0] + t[-s]) * (len(s) + 1) / 2 - sum(s)
Or this one:
#!/usb/bin/python #s=[-1, -4, -7, -10, -13, -16, -19, -25, -28] s=[1,2,3,4,5,6,7,8,10] step = int((max(s)-min(s))/len(s)) return sum(range(min(s),max(s)+1,step))-sum(s)