0

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.

3 Answers3

0

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
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

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.

C.Nivs
  • 12,353
  • 2
  • 19
  • 44
0

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.

Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43