【问题标题】:Default function in Python using minPython中使用min的默认函数
【发布时间】:2019-11-26 12:31:08
【问题描述】:

对于我的问题,我必须编写一个 min 函数,该函数最多可以接受 4 个数字参数,但必须至少有 2 个。如果没有传递值,则必须将第三个和第四个参数设置为 None。该函数应返回传递的最小值,并且必须使用 2、3 或 4 个值。 这就是我所拥有的:

def min(num1, num2, num3=None, num4=None):
   if num1<num2:
     result=num1
   elif num2<num1:
     result=num2
   elif num3>None:
     if num3<num1 and num3<num2:
       result=num3
   else:
     min_num=num4
   return result

当我在 python 中运行它并输入 4 个值时,它不会返回最小数字。它只是从我输入的四个参数中返回一个随机数。谁能帮我吗?

【问题讨论】:

  • 所以你只需要返回(最多)4个数字中的最小值吗?
  • 是的,我只需要返回最多4个数字中的最小值

标签: python function min


【解决方案1】:

您正在使用elif,它仅在if 条件为假时执行。因此,您可以使用所有if 条件来修复。此外,您的默认值为None,您可以使用!= None 进行比较。您可以尝试以下方法:

def minimum(num1, num2, num3=None, num4=None):
    # this first  if else will check with num1 and num2 only  
    if num1 < num2:
        result = num1
    else:
        result = num2

    # after checking between num1 and num2
    # the result will be checked with num3
    # if num3 is provided
    if num3 is not None and num3 < result:
        result = num3

    # if num4 also provided then the result will be compared with it
    if num4 is not None and num4 < result:
        result = num4
    return result

【讨论】:

  • 最好使用is而不是==来检查None。
【解决方案2】:

您的逻辑在几个方面存在缺陷。画出你想要的逻辑树,就像用数字列表做的那样,并实现那个,而不是你在这里发布的。

   if num1<num2:
      result=num1
   elif num2<num1:
      result=num2
   elif ...

看看这里的逻辑:获得最后两个参数的唯一方法是如果 num1 == num2。如果你输入你的函数(5, 7, 1, 0),它将返回 5。

   elif num3>None:

你想在这里做什么? None 不是一个有效的数值;这是非法的比较。试试

    if num3 is not None and ...

建议的逻辑:在一个单独的变量中记录迄今为止最小的数字;将每个值与那个进行比较。

【讨论】:

    【解决方案3】:

    这可以是避免 if 和使用内置函数的解决方案。

    def my_min(num1, num2, num3=None, num4=None):
      my_numbers = [num1, num2, num3, num4]
      return min(my_numbers)
    
    
    print(my_min(4, 3, 2, 1))
    

    【讨论】:

      【解决方案4】:

      首先,你不应该使用min()作为你的函数名,因为它是python的关键字。

      其次,“if-else”条件的数量应该最少,太多了,您可能需要考虑其他选项。

      def custom_min(num1, num2, num3=None, num4=None):
          min_value = num1
          for num in [num2, num3, num4]:
              if !(num is None) and min_value>num:
                  min_value = num
          return min_value
      
      print(custom_min(1, 2))
      print(custom_min(2, 1, 4))
      print(custom_min(2, 1, 4, 0))
      

      输出是:

      1
      1
      0
      

      【讨论】:

      • 最好使用is而不是==来检查None。
      猜你喜欢
      • 2023-03-06
      • 2020-02-12
      • 2015-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-19
      • 2022-01-03
      • 1970-01-01
      相关资源
      最近更新 更多