What is the performance of this program? What should I do differently to optimize performance (O(n))? How would you grade it relative to what defines an optimal, elegantly-written program?
Input: A list l that has a length between 1 and 9 elements, consisting of the numbers from 0-9. The length of l and the values of the elements are both random. Output: The largest number that can be constructed from the list that is divisible by 3. If not possible, return(0).
Test Case: input: l = [3,1,4,1,5,9] output: 94311
def solution(l):
sum = 0
# Sum the elements of l
for elem in l:
sum += elem
# Determine whether l contains a number divisible
# by 3, using the modulo operator. If sum modulo
# 3 is equivalent to 1 or 2, we split the elements
# into two separate lists, q1 and q2.
if (sum < 3):
return(0)
elif (sum % 3 == 0):
l.sort(reverse=True)
x = ''
for i in l:
x = x + str(i)
return(int(x))
else:
q1 = [x for x in l if x % 3 == 1]
q1.sort(reverse=False)
q2 = [x for x in l if x % 3 == 2]
q2.sort(reverse=False)
l = [x for x in l if x % 3 == 0]
# Remove proper elements such that the
# sum of l is divisible by 3.
if (sum % 3 == 1):
if (len(q1) != 0):
q1.pop(0)
elif (len(q2) >= 2):
q2.pop(0)
q2.pop(0)
elif (sum % 3 == 2):
if (len(q2) != 0):
q2.pop(0)
elif (len(q1) >= 2):
q1.pop(0)
q1.pop(0)
# Assemble largest number in l divisible
# by 3 by extending l to q1 and q2.
l.extend(q1)
l.extend(q2)
l.sort(reverse=True)
# Recheck sum of l and test for
# divisbility. If divisible by 3
# concatenate the elements of l into x.
sum2 = 0
if (len(l) > 0):
for elem in l:
sum2 += elem
if (sum2 % 3 == 0):
x = ''
for i in l:
x = x + str(i)
return(int(x))
else:
return(0)
else:
return(0)