0

I am trying to make a more efficient method of going though an array of numbers, and finding what number is missing. I have an array of numbers from 1 to 20, but one is missing, and the numbers aren't ordered in a chronological order (they're shuffled):

array = [16, 11, 4, 6, 14, 8, 5, 13, 10, 2, 9, 15, 3, 18, 20, 12, 19, 7, 1]

The method I have thought about is:

for x in range(1, len(array) + 1):
    if x not in array:
        print(x)

The problem with this method is that it's slow and inefficient, and if I need to analyze a very big array (with thousands of numbers), it will take a long time.

E. Epstein
  • 739
  • 2
  • 11
  • 26

1 Answers1

3

You can find the set.difference

>>> set(range(1, 21)).difference(array)
{17}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • the question looks like a duplicate of https://stackoverflow.com/questions/20718315/how-to-find-a-missing-number-from-a-list but no answer mentions the `set` method. – Jean-François Fabre Mar 23 '18 at 16:07
  • @Jean-FrançoisFabre Decent dupe target, but in that case the initial list is sorted; also at least 1 answer uses sets https://stackoverflow.com/a/34045983/6260170 – Chris_Rands Mar 23 '18 at 16:08
  • okay, so question matches, and same answer applies. Dupe it is. Cory keep your rep, the answer is good. – Jean-François Fabre Mar 23 '18 at 16:13