Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Explaining the solutions so I understand them solution in Clear category for Missing Number by BootzenKatzen
def missing_number(items: list[int]) -> int:
items.sort()
for i in range(len(items) - 2): # length in example is 4, so range is (4-2) range of 2 - so it will loop twice
f, s, t = items[i: i + 3] # f, s, t = items[0:3] example - f = 1 s = 2 t = 4 2nd loop f=2 s=4 t=5
if t - s != s - f: #first loop t - s = 2, s-f = 1 and 2 != 1 so it will trigger
return t - (s - f) # = 4 - (2-1) or 3
# What boggles my mind about these next examples is how they figured out how to do the math.
# I think that's why I struggled with this one
# Because I didn't know how to think about how to find "x" in this situation
# I can figure it out the missing number myself, but I don't know how to give the computer that logic
def missing_number2(items: list[int]) -> int:
first, *_, last = sorted(items) #sorts the items and puts the first and last items on the list into variables
step = (last - first) // len(items) #example 1 would be step = (5-1)/4 = 1
for i in range(first+step, last, step): # range = (1+1, 5, 1) so range 2-5 in increments of 1 = 2,3,4
if i not in items: # 3 is not in the original list
return i # returns the missing value of 3
def missing_number3(items: list[int]) -> int:
first, *_, last = sorted(items) # same as the previous
total = (first + last) * (len(items) + 1) // 2 #first example total = (1+5)*(4+1)//2 =6*5/2 =15
return total - sum(items) # = 15 - (1+2+4+5) = 15 - 12 = 3 so it returns the missing number of 3
print("Example:")
print(missing_number([1, 4, 2, 5]))
# These "asserts" are used for self-checking
assert missing_number([1, 4, 2, 5]) == 3
assert missing_number([2, 6, 8]) == 4
print("The mission is done! Click 'Check Solution' to earn rewards!")
March 31, 2023
Comments: