【问题标题】:Given two non-zero integers, print "YES" if exactly one of them is positive and print "NO" otherwise (Python) [duplicate]给定两个非零整数,如果其中一个是正数,则打印“YES”,否则打印“NO”(Python)[重复]
【发布时间】:2019-07-13 11:51:48
【问题描述】:

第一次在stackoverflow上提问。我被困在试图解决这个问题。这是我的代码:

a = int(input()) 
b = int(input())

给定两个非零整数,如果其中一个为正数,则打印“YES”,否则打印“NO”。

if (a > 0) or (b > 0):
    print('YES') 
else:
    print('NO')

【问题讨论】:

  • (a>0) != (b>0)
  • @Blacksilver 那条评论,扩大一点,会比这个问题的其他答案更好。

标签: python python-2.7


【解决方案1】:
if (a>0) != (b>0):
    print("YES")
else:
    print("NO")

How do you get the logical xor of two variables in Python?

【讨论】:

    【解决方案2】:

    您可以使用更复杂的布尔运算来做到这一点,但拥有多个条件是最简单的方法:

    a = int(input())
    b = int(input())
    
    if (a > 0 and b < 0) or (a < 0 and b > 0):
        print('YES')
    else:
        print('NO')
    

    【讨论】:

    • 太棒了。谢谢
    【解决方案3】:
    print('YES' if a * b < 0 else 'NO')
    

    【讨论】:

    • 这会打印是的,不幸的是他们都是负面的。
    • 我的 python 解释器说不。我用 pythonista 和 a=-1 b=-2 测试了它
    【解决方案4】:

    Tomothy32 的答案是确保简单易用且更重要的是可理解性的最佳方法。但这里有另一种做同样事情的方法,只是为了说明另一个程序员可能如何做到这一点:

    onePositive = ( (a > 0 and b < 0) or (a < 0 and b > 0) )
    
    print('yes' if onePositive else 'no' )
    

    【讨论】:

      【解决方案5】:

      不是最快的解决方案或 1-liner,但会帮助您了解我在解决问题时的思考过程,正好给出 2 个非零整数,如果其中一个是正数,则打印 yes,否则打印 no。

      解决方案 - 如果两个整数都非零,您需要一个正数,另一个必须是负数

      a = int(input())
      b = int(input())
      
      #if a is positive and b and negative
      if (a > 0) and (b < 0) :
          print('YES')
      #if a is negative and b is positive
      elif (a < 0) and (b > 0) :
          print('YES')
      else :
          print('NO')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-18
        • 1970-01-01
        • 2022-11-04
        • 2016-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多