Soumyadeep Chatterjee
Soumyadeep Chatterjee

Reputation: 83

Getting wrong output for some test cases

PART BELOW IS THE PROBLEM STATEMENT: We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return True if we are in trouble.

TEST-CASES: parrot_trouble(True, 6) → True parrot_trouble(True, 7) → False parrot_trouble(False, 6) → False

CODE:(I TRIED/WROTE)

def parrot_trouble(talking, hour):
  if talking and hour<7 or hour>20:
    return True
  if not talking and hour>7 or hour<=20:
    return False

TEST CASES NOT RUNNING: parrot_trouble(False, 21) → False, but i am getting True parrot_trouble(False, 23) → False, but i am getting True

Upvotes: 0

Views: 76

Answers (2)

blueharen
blueharen

Reputation: 126

The problem here is with the if talking and hour<7 or hour>20: statement.

What you are really saying with this is if (talking and hour<7) or hour>20. This means that, if the hour is over 20, this will always return True no matter what.

Try something like this:

def parrot_talking(talking, hour):
    if (talking and hour<7) or (talking and hour>20):
        return True
    else: return False

Upvotes: 1

JMoravitz
JMoravitz

Reputation: 782

Two things:

First, remember that (P and Q) or R is different than P and (Q or R). You intended the latter, but Python interpreted it as the first. In python and several other programming languages, stringing together ands and ors, it will apply these from left to right. I am of the opinion that parentheses will help keep your thoughts organized and should be used even if leaving them out would mean the same thing. In your case, forgetting the parentheses caused the error in your code. When you ran parrot_trouble(False, 21) it returned true since hour>20 was true.

Second, rather than having a second if statement to return false, it is much cleaner here to either use an else statement or no statement at all. Even better, don't use an if statement to begin with and instead simplify all of this into a single return statement. Further, your negation of your if statement was incorrect. The negation of talking and (hour<7 or hour>20) is actually not talking or (hour >= 7 and hour <= 20)

   def parrot_trouble(talking, hour):
      return (talking and (hour<7 or hour>20))

Upvotes: 0

Related Questions