简体   繁体   中英

Find lost number in number sequence

Okay so basically all i have to do is find a lost number in sequence.

For the input data:

5
2 3 1 5

The correct answer is

4
def findMissing(n):
    
    tempList = []
    for i in range(0, n-1):
        tempList.append(str(input()))
    return [x for x in range(tempList[0], tempList[-1]+1) if x not in tempList] 
    

findMissing(5)

Output:

---> 11     return [x for x in range(tempList[0], tempList[-1]+1) if x not in tempList]

TypeError: must be str, not int

I've tried something like that, i wanted to create a list, and input would be appearing into that list, then i will return the missing value from that list, but it's not working.

You could generate a set of the "full" sequence using range then take the set.difference with your given list of data, then that should contain the missing item.

def findMissing(n, data):
    return set(range(1, n+1)).difference(data).pop()

>>> findMissing(5, [2, 3, 1, 5])
4

Since you know the sequence is contiguous, you can also do this arthimetically

def findMissing(n, data):
    return sum(range(1,n+1)) - sum(data)

>>> findMissing(5, [2, 3, 1, 5])
4

This error actually comes from this step:

tempList[-1]+1

The way to reproduce this would be:

'1' + 1
TypeError: must be str, not int

You need to add like types. You can fix it by doing int(input()) which will convert the string type to an int.

range will also throw an error on str arguments:

range('1', '3')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer

So make sure you are giving it integer arguments.

Another variant of @Cory Kramer answer using set symmetric difference :

def find_missing(number, data):
    return (set(data) ^ set(range(1, number + 1))).pop()

find_missing(5, [2, 3, 1, 5])

>> 4

Check the official documentation for more informations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM