I'm building a program where it takes in n, the size of the array, and an array, A as input. The output should be the index of the integer with largest digit sum
I was able to get it to print correctly for positive numbers, but im having trouble including negative numbers in there as well. Any pointers would be appreciated!
i would like to keep the negative sign, so that -81 's digit sum evaluates to -7
#Calculating the maximum sum of a digit, and returns its index
def digitSum(n,A):
new = sorted(A, key = lambda x:(sum(map(int, str(x)))))
ans = new[n-1]
return A.index(ans)
#Test
D = [12,17,19,33,69,91,20]
E = [0,0,0]
F = [65346,654234,788899656,999999]
G = [-8,-9,-20,-30,-387]
print D,E,F,G
a1 = digitSum(7,D)
a2 = digitSum(3,E)
a3 = digitSum(4,F)
a4 = digitSum(5,G)
print 'index of the number with max digit sum: ', a1
print 'index of the number with max digit sum: ', a2
print 'index of the number with max digit sum: ', a3
print 'index of the number with max digit sum: ', a4
The previous 3 print just fine
[12, 17, 19, 33, 69, 91, 20] [0, 0, 0] [65346, 654234, 788899656, 999999]
index of the number with max digit sum: 4
index of the number with max digit sum: 0
index of the number with max digit sum: 2
but the last one throws an error
new = sorted(A, key = lambda x:(sum(map(int, str(x)))))
ValueError: invalid literal for int() with base 10: '-'