0

I am currently working through a few sections of "Think Python" by Allen B. Downey and I am having trouble understanding the solution to the question in Section 16.1:

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.

His solution is the following:

def is_after(t1, t2):
"""Returns True if t1 is after t2; false otherwise."""
return (t1.hour, t1.minute, t1.second) > (t2.hour, t2.minute, t2.second)

Full solution code shown here.

Questions: Is this operator comparing on multiple values at once? How this this working? Where can I read more about this?

1
  • Thank you all! I knew this was a simple one it was just evading me there for a minute. Commented Feb 19, 2014 at 2:13

4 Answers 4

3

Read the docs here for an explanation

Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one.

To your specific case: t1.hour is compared against t2.hour. If they are equal, t1.minute is compared against t2.minute. If those are equal, t1.second is compared against t2.second. As soon as there's an inequality, that is returned.

Sign up to request clarification or add additional context in comments.

Comments

2

(t1.hour, t1.minute, t1.second) and (t2.hour, t2.minute, t2.second) are tuples. From the docs:

Tuples and lists are compared lexicographically using comparison of corresponding elements.

Meaning that first t1.hour and t2.hour are compared, then the minutes and then the seconds.

Comments

1

From the Python documentation: Sequence types also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements.

Comments

-1

Its just comparing tuples. Do a (2,3,4) > (1,2,3) on the terminal and youll understand. Play around with the tuple comparisons and the rules of tuple comparisons will become pretty evident.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.