在python中查找交替的总和

时间:2014-11-20 20:03:07

标签: python indexing

我试图编写一个代码,找到一个长的一定数量(d)的交替和(例如,对于45678 ---> 4-5 + 6-7 + 8)数字,并找出哪个总和是最大的 我的想法是拆分字符串,这样列表中的每个对象都将在长度d中,并且对于每个对象,从索引[0]中的数字中减去索引[1]中的数字,再次执行直到索引[d- 2]和索引[d-1]在每次总结结果时,然后将其与列表对象交换,以便我能够在最后比较它们的大小。

我已经走到了这一步:

def altsum_digits(n,d):
    sum = 0
    my_num = "n"
    list_lend = [my_num[x:x+d] for x in range(0, len(my_num),d)]

    pos = 0
    total = 0

    for i in list_lend:

        total = int(i[pos])- int(i[pos+1])
        pos = pos + 2

但是我一直收到错误,比如基数为10的int()的无效文字错误:' n'或索引超出范围......

感谢任何帮助,我只是一个初学者,所以要温柔[:

1 个答案:

答案 0 :(得分:0)

这个怎么样:

def altsum( n ):
   # convert n to a string
   s = str( n )
   # build a tuple with all the even index entries converted to int
   evn = map( int, tuple( s[0::2] ))
   # build a tuple with all the odd index entries converted to int
   odd = map( int, tuple( s[1::2] ))
   # compute the cumulative sum for both tuples and return the difference
   return sum( evn ) - sum( odd )

例如:n = 45678

  • evn< - ( 4, 6, 8 )
  • odd< - ( 5, 7 )

sum( evn ) - sum( odd ) = ( 18 - 12 ) = 6