Python 2.7:带有负整数的最大位数总和

时间:2019-10-07 15:58:13

标签: python arrays python-2.7

我正在构建一个程序,其中它接受n(数组的大小)和数组A作为输入。 输出应为最大位数总和的整数的索引

我能够正确打印正数,但是我也很难在其中包含负数。任何指针将不胜感激!

我想保留负号,以便-81的数字总和为-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

以前的3张纸很好

[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

但最后一个抛出错误

    new = sorted(A, key = lambda x:(sum(map(int, str(x)))))
ValueError: invalid literal for int() with base 10: '-'

2 个答案:

答案 0 :(得分:1)

所以我基本上创建了自定义telephoneNumber函数来处理第一个负数:

str

答案 1 :(得分:1)

不需要将数字转换为str,例如,您可以传递一个可迭代的元组:

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

输出:

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