I have written a code that gives me minimum , maximum and smallest number between the largest and the smallest number that is not in the list.so for few uses cases I do get the correct answer For example. for lt=[2, -4, 8, -5, 9, 7]
I got correct answer res=[-5, -3, 9]
but for another list pt=[1, 3, -3, -2, 8, -1]
is giving me res=[-3, -1, 8]
instead of giving res =[-3, 0, 8]
Below is my code
class Solution(object):
def minmax(self,nums):
nums.sort()
minimum_number = nums[0]
maximum_number = nums[-1]
res=[]
j=1
count = 0
for i in range(1,len(nums)):
while count!=1:
if minimum_number j == nums[i]:
pass
else:
res.append(minimum_number)
res.append(minimum_number j)
res.append(maximum_number)
count = 1
j = 1
return res
if __name__ == "__main__":
pt = [2, -4, 8, -5, 9, 7]
lt = [1, 3, -3, -2, 8, -1]
print(Solution().minmax(pt))
print(Solution().minmax(lt))
CodePudding user response:
Instead of if minimum_number j == nums[i]:
do if minimum_number j in nums:
Also i think no need of for loop..!
Code:
class Solution(object):
def minmax(self,nums):
nums.sort()
minimum_number = nums[0]
maximum_number = nums[-1]
res=[]
j=1
count = 0
while count!=1:
if minimum_number j in nums:
pass
else:
res.append(minimum_number)
res.append(minimum_number j)
res.append(maximum_number)
count = 1
j = 1
return res
if __name__ == "__main__":
pt = [2, -4, 8, -5, 9, 7]
lt = [1, 3, -3, -2, 8, -1]
print(Solution().minmax(lt))
print(Solution().minmax(pt))
Output:
[-3, 0, 8]
[-5, -3, 9]
CodePudding user response:
Currently, your code is only adding the minimum and maximum numbers to the result list, and it is not utilizing the 'i' you're generating.
res.append(minimum_number j)
should be
res.append(i)
also, the while loop is not necessary.
also, the for loop can start from the min number if you know it already.