Big sort: how are strings of equal length sorted with a keyed lambda?

Here is my code:

def SortingBigIntegers(arr):
    arr.sort(key = lambda x: (len(x), x))

arr = ["54", "724523015759812365462",
        "870112101220845", "8723","6","9","3"]

SortingBigIntegers(arr)

print " ".join(arr)

      

How are same length strings sorted in this code?

+3


source to share


2 answers


key

:

lambda x: (len(x), x)

      

So this means it converts to a tuple. The tuple is sorted first by the first element, then by the second element . So if the length of the two strings is equal, it sorts the strings line by line. Strings are in Python sorted lexicographically . In case the strings are integers (no decimal point and no leading zeros , etc.) and they are the same length, then they are sorted as if we would be sorting them numerically.



If the values โ€‹โ€‹still remain the same for both criteria , the order will be the same as the original order : sorting in Python is stable.

That being said, in python-3.x , can handle arbitrary size . So you don't need to use strings, you can just use s. int

int

+3


source


In the function SortingBigIntegers(arr, n)

you used n

, but you only pass arr

. Therefore, you must avoid this n

.

Then follow the next process:

def SortingBigIntegers(arr):
  arr.sort(key=lambda x: (len(x), x))


arr = ["54", "724523015759812365462","870112101220845", "8723", "6", "9", "3"]

SortingBigIntegers(arr)

print(" ".join(arr))

      




Output:

3 6 9 54 8723 870112101220845 724523015759812365462

      

+1


source







All Articles