1

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: '-'

2 Answers 2

1

So I basically created my custom str function, to handle the first negative digit:

sign = lambda x: (1, -1)[x < 0]

def my_to_str(int_):
    sign_ = sign(int_)
    int_c = abs(int_)
    str_int_c = list(str(int_c))
    if sign_ < 0:
        str_int_c[0] = "-"+str_int_c[0]
    # print(str_int_c)
    return str_int_c

def digitSum(n,A):
    new = sorted(A, key = lambda x:(sum(map(int, my_to_str(x)))))
    ans = new[n-1]
    return A.index(ans)
Sign up to request clarification or add additional context in comments.

Comments

1

There is no need to convert the numbers to str, you could just pass an iterable tuple for example:

def digitSum(n,A):
    new = sorted(A, key = lambda x:(sum(map(int, (x,))))) 
    ans = new[n-1]
    return A.index(ans)

Output:

[12, 17, 19, 33, 69, 91, 20] [0, 0, 0] [65346, 654234, 788899656, 999999] [-8, -9, -20, -30, -387]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.