sorting - largest fromed number in a list python -
question: given list of non negative integers, arrange them such form largest number.
so given [1, 20, 23, 4, 8], largest formed number 8423201.
i couldn't understand following solution:
what num.sort(cmp=lambda x, y: cmp(y + x, x + y))
do?
and why have 2 parameters x , y? if input list, x , y represent in list?
class solution: # @param num, list of integers # @return string def largestnumber(self, num): num = [str(x) x in num] num.sort(cmp=lambda x, y: cmp(y + x, x + y)) largest = ''.join(num) return largest.lstrip('0') or '0' if __name__ == "__main__": num = [3, 30, 34, 5, 9] print solution().largestnumber(num)
can explain code solution? thanks.
python 2.x sort functions allowed cmp
function comparing 2 items. cmp(a, b)
returns -1 if < b, 0 if == b, or 1 if > b.
this code uses cmp
"creatively" needed sort order solve problem; sort "8" before "80" because "880" > "808".
the problem want reverse alphabetical sort, want short strings before long ones (if prefixes identical).
a more general solution reverse-sort alphabetically, right-pad strings same length - @ least long longest string sorting - character sorts "greater 9".
how choose such character? well,
ord("9") # -> 57 print("".join(chr(ch) ch in range(57, 75)) # "9:;<=>?@abcdefghij"
so "a"
looks choice, , it's easy remember because it's 10 in hexadecimal.
then
def largest_number(nums): # convert strings nums = [str(i) in nums] # find length of longest string longest = max(len(s) s in nums) # create function pad strings length def padded(s, pad_char="a", length=longest): return s + pad_char * (length - len(s)) # sort strings greatest-to-least according padded values nums.sort(key=padded, reverse=true) # nums ["9", "5", "3", "34", "30"] # resulting output-string num = "".join(nums) # remove leading 0s # (this should ever occur if input nums 0) num = num.lstrip("0") if num: return num else: # string 0s - return single 0 return "0" if __name__ == "__main__": nums = [3, 30, 34, 5, 9] print(largest_number(nums)) # -> "9533430"
Comments
Post a Comment