Skip to content

Instantly share code, notes, and snippets.

@radzhome
Created September 27, 2016 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radzhome/2779c5b3215ec418cfa83ae9481e3f3c to your computer and use it in GitHub Desktop.
Save radzhome/2779c5b3215ec418cfa83ae9481e3f3c to your computer and use it in GitHub Desktop.
"""
Write a function that given a list of non negative integers, arranges them such that they form the largest possible number. For example, given [50, 2, 1, 9], the largest formed number is 95021.
You application should be run from the command line using a single command. For example:
# $ python ./largest.py 100 3 67 9
# $ sbt "run 100 3 67 9"
"""
#!/usr/bin/env python
import sys
def generate_largest_integer(integer_list, max_length):
"""Generates the largest int based on an int list &
the length of the largest str(int) in the list"""
integer_tuple_list = [] # array of tuples
for integer in integer_list: # 2nd item in tuple is left justified string with 9's up to max length
integer_tuple_list.append((integer, integer.ljust(max_length, '9')))
integer_tuple_list.sort(key=lambda x: x[1], reverse=True) # Sort the list by 2nd (mask) value
new_list = [seq[0] for seq in integer_tuple_list]
print ''.join(new_list)
def main():
integer_list = []
args = sys.argv[1:]
if len(args) == 0:
print "Sorry no positive integers passed."
print "usage: generate_largest.py positive_integer [N_positive_integers ...]"
else:
max_length = 0
for arg in args:
if arg.isdigit() and int(arg) > 0: # Validate positive integers
max_length = max(max_length, len(arg)) # Get max arg length
integer_list.append(arg)
else:
raise Exception("Sorry only positive integers should be passed.")
generate_largest_integer(integer_list, max_length)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment