0

Below is an easy level coding problem, based on string manipulation:-

Question

I was able to solve it using a for loop by defining conditions for positive and negative numbers.

But while going through other solutions, I found this interesting solution in Python for the same question.

I have been working in Python for the past year but this is my first time coming across the below syntax for if else block

if [str(x) > A[i], str(x) < A[i]][A[0] == '-']:

Below is the complete code :

def maxValue(self, A, x):
        for i in xrange(len(A)):
            if [str(x) > A[i], str(x) < A[i]][A[0] == '-']:
                return A[:i] + str(x) + A[i:]
        return A + str(x)

How can I interpret this block? Where can I find documentation for it?

5
  • 1
    It's not any kind of new syntax, it's just unconventional use of something you already know. What does [] in term position do? What does [] in postfix position do? What do booleans do when coerced to int? Commented May 30, 2021 at 6:03
  • Sorry didn't get you exactly Commented May 30, 2021 at 6:09
  • 2
    That's an old style: X if C else Y which is written as [Y, X][C]. Note that in this form both X and Y are evaluated which does not occur in the if expression. Commented May 30, 2021 at 6:09
  • So basically X if C else Y and [Y, X][C]` are functionally different when it comes to execution? First expression is much more safer then, right? Commented May 30, 2021 at 6:14
  • Thanks DanD and hobbs for your insights. I completely understood the scenarios and even got some additional info on how can this be different for python 2.x and python 3.x Commented May 30, 2021 at 6:56

1 Answer 1

2

The less hacky way to write it:

def maxValue(self, A, x):
    for i in xrange(len(A)):        
        if (A[0] == '-' and str(x) < A[i]) or (A[0] != '-' and str(x) > A[i]):
            return A[:i] + str(x) + A[i:]
    return A + str(x)

Explanation: if checks one of [str(x) > A[i], str(x) < A[i]] array values depending on condition A[0] == '-'.

If A[0] == '-' is False, it turns into 0, thus gets [str(x) > A[i], str(x) < A[i]][0] and checks str(x) > A[i] condition.

If (A[0] == '-') == True, True turns to 1 and checks [str(x) > A[i], str(x) < A[i]][1] or str(x) < A[i].

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

3 Comments

Will it be same for python 2.x and python 3.x
@AlokRaj Yes, you can test with print([2, 3][False] == 2 and [2, 3][True] == 3)
Got the solution, but thanks for insights :) In python 2.x, True and False can be reassigned but In Python 3.x True and False are keywords and will always be equal to 1 and 0. It's a really small but awesome concept :D

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.