0

I want to sort this list a = [31415926535897932384626433832795, 1, 3, 10, 3, 5]. To reduce time complexity I want to first check whether the 2 elements are of same length or not. If both are of not same length I will swap them according to their length otherwise I will check which number is bigger and swap them. I want to implement this using .sort() function which have a parameter called key. I can use a.sort(key=len) but it will only work for the test cases with different length inputs. Please help me regarding this.

3
  • By length, do you mean the number of digits? Commented Dec 23, 2019 at 9:31
  • yes by length means no. of digits Commented Dec 23, 2019 at 9:32
  • The number of digits would require converting them to a string. This will be an inherently slower operation. Commented Dec 23, 2019 at 9:38

1 Answer 1

6

When you are using sort() in Python, you can provide a function or anonymous (lambda) function to it as a basis for sorting.

In this case, you can use lambda x where x are the elements in a.

Subsequently, providing a tuple as a return result in the function allows the sort to prioritize in sorting, thus what you need is this:

a.sort(key=lambda x: (len(str(x)), x))

In the above code, a sorts first by len(str(x)) then by the value of x

Edit: Added explanation

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

10 Comments

Can you please explain it. It would be better for us to learn.
The constraints of my problem are 1 <= N = 2x10^5 and 1 <= a[i] <= 10^(10^6)
lambda acts like a function parameter and can take any number of arguments.
Code only answers are generally disfavored here — place edit your answer and explain what it's doing.
@ChallaSaiBhanuTeja I've edited my answer to add an explanation, sorry for the delay, posted the answer in a rush ytd and have been busy since.
|

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.