简体   繁体   English

有没有办法以更简洁和正确的方式编写此代码?

[英]Is there a way to write this code in a more succinct and proper way?

For the following CodingBat problem:对于以下 CodingBat 问题:

When squirrels get together for a party, they like to have cigars .当松鼠聚在一起参加聚会时,它们喜欢cigars A squirrel party is successful when the number of cigars is between 40 and 60, inclusive.cigars的数量在 40 到 60 之间时,松鼠派对就成功了。 Unless it is the weekend, in which case there is no upper bound on the number of cigars.除非是周末,否则雪茄的数量没有上限。 Return True if the party with the given values is successful, or False otherwise.如果具有给定值的一方成功,则返回True ,否则返回False

I wrote the following answer:我写了以下答案:

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

And my asnwer is not working as expected with the following inputs:我的 asnwer 没有按预期使用以下输入:

cigar_party(30, False) 
cigar_party(61, False) 
cigar_party(39, False)
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

If you use a not before a compound predicate, the whole thing is negated.如果在复合谓词之前使用 not,则整个事情都被否定了。
Technically it could be a one liner using ternary operator syntax but that line would probably not be PEP8 compliant in terms of length.从技术上讲,它可能是使用三元运算符语法的单行,但该行的长度可能不符合 PEP8。

Depending on your use case, you could also technically omit the "return False" because the bool of None is False.根据您的用例,您还可以在技术上省略“返回 False”,因为 None 的布尔值是 False。

Your error is that you test for cigars >= 40 or cigars <= 60 .您的错误是您测试cigars >= 40 or cigars <= 60 For an integer input, this condition is always true--either cigars is greater than or equal to 40, or cigars is less than or equal to 60. What I assume you meant to test is that cigars >= 40 and cigars <= 60 .对于 integer 输入,此条件始终为真—— cigars大于或等于 40,或cigars小于或等于 60。我假设您要测试的是cigars >= 40 and cigars <= 60 . Indeed, if you make just that change, your code functions perfectly well: Try it online!确实,如果您只进行该更改,您的代码就会运行良好:在线试用!

However, if you're asking for "succinct and proper", I would suggest that you either break the problem down into two simple cases:但是,如果您要求“简洁和适当”,我建议您将问题分解为两个简单的情况:

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

Try it online! 在线尝试!

or use a single expression, which parallels the wording of the specification quite pleasantly:或使用单个表达式,它与规范的措辞非常相似:

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

Try it online! 在线尝试!

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

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