educative.io

Problem with the condition in Line 12 & 13

A user asked us the following question:

I have problem in understanding the condition used in the two lines

The conditions on lines 12 and 13 are examples of Python’s way of using ternary expressions.

The code on lines 12-13 is as follows:

mid_left = A[mid - 1] if mid - 1 > 0 else float("-inf")
mid_right = A[mid + 1] if mid + 1 < len(A) else float("inf")

The general syntax is as follows:

variable = value_when_true if condition else value_when_false

This implies that if (mid - 1) is greater than 0, then mid_left is set to A[mid -1]. Otherwise, it will be set to float("-inf"). Similarly, if (mid+1) is less than the length of A, mid_right is set to A[mid + 1]; otherwise, it is set to float("inf"). I hope this answers your question.

Best Regards,
Alina Fatima | Developer Advocate
Educative.io

1 Like