【问题标题】:Is there a way to write this code in a more succinct and proper way?有没有办法以更简洁和正确的方式编写此代码?
【发布时间】:2021-07-21 19:03:19
【问题描述】:

对于下面的 CodingBat 问题:

当松鼠聚在一起参加派对时,他们喜欢cigars。一种 当cigars的数量在40之间时松鼠派对成功 和60,包括在内。除非是周末,在这种情况下没有 雪茄数量的上限。返回True 如果一方有 给定的值是成功的,否则False

我写了以下答案:

def cigar_party(cigars, is_weekend):
  if is_weekend and cigars >= 40:
    return True
  if not is_weekend and (cigars >= 40 or cigars <= 60):
    return True
  else:
    return False

我的 asnwer 没有按预期使用以下输入:

cigar_party(30, False) 
cigar_party(61, False) 
cigar_party(39, False)

【问题讨论】:

  • 你能解释一下cigars &gt;= 40 or cigars &lt;= 60 什么时候不是真的吗?提示:你需要and 而不是or

标签: python python-3.x function boolean logic


【解决方案1】:

你的错误是你测试cigars &gt;= 40 or cigars &lt;= 60。对于整数输入,此条件始终为真——cigars 大于或等于 40,或者 cigars 小于或等于 60。我假设您要测试的是 cigars &gt;= 40 and cigars &lt;= 60。确实,如果您只进行该更改,您的代码将运行得非常好:Try it online!

但是,如果您要求“简洁和适当”,我建议您将问题分解为两个简单的情况:

def cigar_party(cigars, is_weekend):
  if is_weekend:
    return cigars >= 40
  else:
    return 40 <= cigars <= 60

Try it online!

或者使用一个单独的表达方式,它与规范的措辞非常相似:

def cigar_party(cigars, is_weekend):
  return cigars >= 40 and (is_weekend or cigars <= 60)

Try it online!

【讨论】:

    【解决方案2】:
    def cigar_party(cigars, is_weekend):
      if is_weekend and cigars >= 40:
        return True
      elif 40 <= cigars <= 60 and not is_weekend:
        return True
      return False
    
    def cigar_party(cigars, is_weekend):
      if cigars >= 40:
        if is_weekend or cigars <= 60:
          return True
      return False
    
    

    如果在复合谓词之前使用 not,则整个事情都会被否定。
    从技术上讲,它可能是使用三元运算符语法的单行,但该行的长度可能不符合 PEP8。

    根据您的用例,您还可以在技术上省略“返回 False”,因为 None 的布尔值是 False。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-08
      • 1970-01-01
      • 2023-04-04
      • 2012-09-12
      • 1970-01-01
      • 2018-06-05
      相关资源
      最近更新 更多