简体   繁体   English

该代码并不总是给出不在列表中的最大和最小数字之间的正确最小数字

[英]The code doesn't always give correct smallest number between the largest and the smallest number that is not in the list

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] .对于lt=[2, -4, 8, -5, 9, 7]我得到了正确答案res=[-5, -3, 9]但对于另一个列表pt=[1, 3, -3, -2, 8, -1]给我res=[-3, -1, 8]而不是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))

Instead of if minimum_number+j == nums[i]:而不是if minimum_number+j == nums[i]:

do if minimum_number+j in nums:如果if minimum_number+j in nums:

Also i think no need of for loop..!我也认为不需要 for 循环..!

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: Output:

[-3, 0, 8]
[-5, -3, 9]

I actually have a hard time understanding what your code does.我实际上很难理解您的代码的作用。 To understand why your code is failing for the second test case, it can be helpful to add some print statements, like this:要理解为什么您的代码在第二个测试用例中失败,添加一些print语句可能会有所帮助,如下所示:

    def minmax(self, nums):
        nums.sort()
        minimum_number = nums[0]
        maximum_number = nums[-1]
        res = []
        j = 1
        count = 0
        print(f'nums = {nums}')  # added debug print statement
        for i in range(1, len(nums)):
            print(f'i={i}')  # added debug print statement
            while count != 1:
                print(f'i={i}, j={j}, count={count}')  # added debug print statement
                if minimum_number + j == nums[i]:
                    pass
                else:
                    print('result defined here!')  # added debug print statement
                    res.append(minimum_number)
                    res.append(minimum_number + j)
                    res.append(maximum_number)
                    count += 1
                j += 1
        return res

For your second test case, the output is as follows:对于您的第二个测试用例,output 如下所示:

nums = [-3, -2, -1, 1, 3, 8]
i=1
i=1, j=1, count=0
i=1, j=2, count=0
result defined here!
i=2
i=3
i=4
i=5

So the result (variable res ) is determined when i=1 and j=2 , because nums[1] != minimum_number + 2 (ie -2 != -3 + 2 ).所以结果(变量res )是在i=1j=2时确定的,因为nums[1] != minimum_number + 2 (即-2 != -3 + 2 )。 This logic seems flawed.这个逻辑似乎有问题。 It is probably pure luck (or bad luck) that the code gives correct results for the first testcase.代码为第一个测试用例给出正确的结果可能纯粹是运气(或运气不好)。

The code is supposed to find "the smallest number between the largest and the smallest number that is not in the list".该代码应该找到“不在列表中的最大和最小数字之间的最小数字”。 So in case the smallest number is -3 , you could compare the sorted list with [-3, -2, -1, 0, 1, ...] and find the first number that differs from that list.因此,如果最小的数字是-3 ,您可以将排序列表与[-3, -2, -1, 0, 1, ...]进行比较,并找到与该列表不同的第一个数字。 This can be done using only one index ( i ), which is much easier than using two indices ( i and j ).这可以仅使用一个索引 ( i ) 来完成,这比使用两个索引 ( ij ) 容易得多。 Also, the count variable is unneeded: you do not actually count anything, but are simply using it as a flag.此外,不需要count变量:您实际上不计算任何东西,而只是将其用作标志。 Maybe you are used to such constructs from other programming languages?也许您已经习惯了其他编程语言的这种构造? Using return avoids the need of such extra variables, which makes the code much shorter and clearer IMHO.使用return避免了对这些额外变量的需要,这使得代码更短更清晰恕我直言。

Taking the above into account would result in something like this:考虑到上述情况会导致这样的结果:

class Solution:

    def minmax(self, nums):
        nums.sort()
        for i, num in enumerate(nums):
            if nums[0] + i != num:
                return [nums[0], nums[0] + i, nums[-1]]
        return []

The last line is not really needed, but keeps the behavior similar to your original code.最后一行并不是真正需要的,但保持与原始代码相似的行为。 If the last line is removed, the function will return None if no valid solution is found.如果删除最后一行,如果未找到有效解决方案,function 将返回None

Another way to look at the problem is to find the first number that is not exactly 1 higher than the previous number in the list.另一种看待问题的方法是找到第一个不比列表中前一个数字大 1 的数字。 Following that logic, the inner loop could be written like this (which gives the same result):按照这个逻辑,内部循环可以这样写(结果相同):

        for i in range(len(nums) - 1):
            if nums[i + 1] - nums[i] != 1:
                return [nums[0], nums[i] + 1, nums[-1]]

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.目前,您的代码只是将最小和最大数字添加到结果列表中,并且没有使用您生成的“i”。

res.append(minimum_number + j)

should be应该

res.append(i)

also, the while loop is not necessary.此外,while 循环不是必需的。

also, the for loop can start from the min number if you know it already.此外,如果您已经知道,for 循环可以从最小值开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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