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.
-
By length, do you mean the number of digits?doctorlove– doctorlove2019-12-23 09:31:33 +00:00Commented Dec 23, 2019 at 9:31
-
yes by length means no. of digitsChalla Sai Bhanu Teja– Challa Sai Bhanu Teja2019-12-23 09:32:24 +00:00Commented Dec 23, 2019 at 9:32
-
The number of digits would require converting them to a string. This will be an inherently slower operation.James– James2019-12-23 09:38:49 +00:00Commented Dec 23, 2019 at 9:38
Add a comment
|
1 Answer
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
10 Comments
Vaibhav Jadhav
Can you please explain it. It would be better for us to learn.
Challa Sai Bhanu Teja
The constraints of my problem are 1 <= N = 2x10^5 and 1 <= a[i] <= 10^(10^6)
Vaibhav Jadhav
lambda acts like a function parameter and can take any number of arguments.
martineau
Code only answers are generally disfavored here — place edit your answer and explain what it's doing.
Julian Chan
@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.
|