Last active
November 23, 2019 02:38
-
-
Save nrchandan/7d6787dbd8b62eb05ccd7f6127ed44d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def largest_num(nums): | |
""" | |
Form the largest number by joining the given list of numbers. | |
>>> largest_num([0]) | |
0 | |
>>> largest_num([1, 2, 0]) | |
210 | |
>>> largest_num([1, 10, 100]) | |
110100 | |
>>> largest_num([9, 1, 10, 100]) | |
9110100 | |
>>> largest_num([9, 19, 199, 1999]) | |
9199919919 | |
>>> largest_num([9, 11, 22, 333]) | |
93332211 | |
>>> largest_num([1, 12, 134, 104]) | |
134121104 | |
>>> largest_num([1, 10, 110, 1110]) | |
1111011010 | |
""" | |
str_nums = [str(x) for x in nums] | |
sorted_str_nums = sorted(str_nums, cmp=literal_cmp, reverse=True) | |
return int(''.join(sorted_str_nums)) | |
def literal_cmp(x, y): | |
""" | |
>>> literal_cmp('22', '22') | |
0 | |
>>> literal_cmp('21', '22') | |
-1 | |
>>> literal_cmp('2', '22') | |
0 | |
>>> literal_cmp('1', '10') | |
1 | |
>>> literal_cmp('10', '100') | |
1 | |
>>> literal_cmp('12', '122') | |
-1 | |
>>> literal_cmp('12', '121') | |
1 | |
>>> literal_cmp('12', '1212') | |
0 | |
>>> literal_cmp('12', '1213') | |
-1 | |
""" | |
if int(x+y) > int(y+x): | |
return 1 | |
if int(x+y) < int(y+x): | |
return -1 | |
return 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment