0
Find the missing elements in the list - i have 1to n?array= [1, 2, 3, 4, 5, 6, 8, 9, 10]
Example array= [1, 2, 3, 4, 5, 6, 8, 9, 10] find the missing elements any ideas
3 Antworten
+ 2
We know that the sum of the first n natural no. can be computed using the formula 1 + 2 + … + n = n×(n+1)/2. We can use this formula to find the missing no.
The idea is to find the sum of integers b/w 1 and n+1 using the above formula where n is the array’s size. Also calculate the actual sum of integers in the array. Now the missing no. would be the diff b/w the two.
Here is your code 👇
# Find the missing number in a given list
def getMissingNumber(arr):
# get the array's length
n = len(arr)
# actual size is `n+1` since a number is missing from the list
m = n + 1
# get a sum of integers between 1 and `n+1`
total = m * (m + 1) // 2
# the missing number is the difference between the expected sum and
# the actual sum of integers in the list
return total - sum(arr)
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5, 7, 8, 9, 10]
print('The missing number is', getMissingNumber(arr))
Here in the code i have brought the ans for 7 you have to get ans 6
+ 1
Hi! If you are comparing your_list with the missing numbers, with positive ordered integers, you can to assume that max of your_list is the highest number. So you can use range(max(your_list + 1)) and make a for loop where the number in the range are used to compare with the number in your_list. Use ’in’ to find out if a a number is a member in your_list. Use a if statement to, for example, print out the number if it isn’t a member in the list.
+ 1
You can also use list comprehension
# the list
lst = [ 1, 2, 3, 5, 6, 8, 9, 10 ]
# smallest and largest number in <lst>
first, last = min( lst ), max( lst ) + 1
# generate a list of missing numbers
result = [ n for n in range( first, last ) if n not in lst ]
print( result )