SpartanHero
SpartanHero

Reputation: 107

python how to form highest possible number from a list using only a function

I need to create a program which only has functions in it. No main code (!). We need to create the largest possible number from a list. so in [50,9,2,1] the outcome must be 95021.

I've tried using this code:

def max_out(l):
    new_num = ""
    if(len(l) == 0):
        print("")
        exit()
    numb = []
    for numbers in l:
        numbers = str(numbers)
        nummer = numbers[0:1]
        numb.append(nummer)
    t = len(numb)
    while t > 0:
        t = len(numb)
        mx = numb.index(max(numb))
        new_num += str(l[mx])
        numb.remove(mx)
        l.remove(mx)
    return new_num

print(max_out([50,9,2,1]))

but it keeps giving the error:

numb.remove(mx) ValueError: list.remove(x): x not in list

l.remove(mx) ValueError: list.remove(x): x not in list

can someone please help me?

Upvotes: 2

Views: 139

Answers (1)

Stuart
Stuart

Reputation: 9868

As noted in @AlexHall's comments, the previous answers fail in a case such as [90, 9]. This is one solution that I think works properly. In sorting the list, the function repeats the final digit until the number is as long as the longest in the list, e.g. [90, 9] gets sorted as if it were [90, 99].

def highest_comb(L):
    max_length = len(str(max(L)))
    L = map(str, L)  
    def sort_key(s):
        return s + s[-1] * (max_length - len(s))

    sorted_list = sorted(L, key=sort_key, reverse=True)
    return ''.join(sorted_list)

print(highest_comb([50, 9, 2, 1]))             # 95021
print(highest_comb([90, 9]))                   # 990
print(highest_comb([115, 15, 7, 905, 904]))    # 905904715115

On your original code, the error occurs because mx is the index of the highest digit in your list but the remove method takes a value rather than an index as its argument. Instead, you should use pop or del. However, even if you fix this, your code will not work with an example such as [84, 87] because it only examines the first digit of each number.

Upvotes: 1

Related Questions