2014-11-20 28 views
-1

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

我这个地步得到:

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 

,但我一直喜欢无效字面得到错误的INT()基数为10: 'N',或索引超出范围......

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

+1

你的意思'my_num = N'? – jonrsharpe 2014-11-20 20:08:25

+0

请修正您的缩进错误,以便代码可以真正运行并展示您尝试修复的错误,如果您希望人们修复这些错误。此外,使用1,2和4空格的混杂缩进使得代码难以阅读;无处不在,并且让自己成为一个编辑器,使缩进更容易。 – abarnert 2014-11-20 20:14:46

+0

另外,您可能需要考虑将其分解为更简单的功能。例如,首先编写一个函数,它返回一个完整字符串的完整交替和,然后得到它的工作。然后你可以编写一个函数,将每个“d”数字组放在一个更大的字符串中。然后把它们放到一个函数中,获得每组数字并获得它们的交替和,并找到最大值。 – abarnert 2014-11-20 20:17:13

回答

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) 

Ë X:为n = 45678

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

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