Jenkins
Jenkins

Reputation: 71

Writing Conditionals without using 'if' in python

I came across this problem statement in 'Think Python' book by Allan Downey:

Write a boolean function called is_after that takes two Time objects, t1 and t2, and returns True if t1 follows t2 chronologically and False otherwise. Challenge: don't use an if statement.

I wrote this code which seems to work fine:

class Time:
    def __init__(self , hour , min , sec):
        self.hour = hour
        self.min = min
        self.sec = sec

def is_after(t1 , t2):
    if t1.hour > t2.hour:
        return True
    elif t1.hour == t2.hour:
        if t1.min > t2.min:
            return True
        elif t1.min == t2.min:
            if t1.sec > t2.sec:
                return True
            else:
                return False
        else:
            return False
    else:
        return False

But the author challenges the reader to accomplish the comparison without using a conditional operator. I can't imagine how can a comparison even be done without using if/else statements.

Upvotes: 0

Views: 547

Answers (3)

DarrylG
DarrylG

Reputation: 17166

Taking advantage of how tuple compare works, the following would be equivalent to your posted code.

def is_after(t1, t2):
    return (t1.hour, t1.minute, t1.second) > (t2.hour, t2.minute, t2.second)

Upvotes: 3

3LexW
3LexW

Reputation: 395

You can calculate the total seconds of the time, and return if t1 > t2

def is_after(t1, t2):
  t1_sec = 3600 * t1.hour + 60 * t1.min + t1.sec
  t2_sec = 3600 * t2.hour + 60 * t2.min + t2.sec
  return t1_sec > t2_sec

Upvotes: 4

Ryan Rau
Ryan Rau

Reputation: 148

What about Ternary operators? More info

Something like:

return (false, true)[t1.hour < t2.hour]

Upvotes: -2

Related Questions