【问题标题】:Finding alternating sum in python在python中查找交替总和
【发布时间】:2014-11-20 20:03:07
【问题描述】:

我正在尝试编写一个代码来查找长数字中一定数量的数字(d)的交替总和(例如,对于 45678 ---> 4-5+6-7+8),并且找出最大的总和。
我的想法是拆分字符串,以便列表中的每个对象的长度为 d,并且对于每个对象,从 index[0] 中的数字中减去 index[1] 中的数字,再次执行直到 index[d- 2] 和 index[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

但我不断收到错误,例如 int() 以 10 为底的无效文字:'n',或索引超出范围...

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

【问题讨论】:

  • 你的意思是my_num = n?!
  • 如果您希望人们修复这些错误,请修复您的缩进错误,以便代码可以实际运行并演示您尝试修复的错误。此外,随意混合使用 1、2 和 4 个空格进行缩进会使您的代码难以阅读;到处都坚持 4,让自己成为一个让缩进更容易的编辑器。
  • 另外,您可能需要考虑将其分解为更简单的函数。例如,首先编写一个函数,该函数返回一个完整字符串的完整交替和,然后让它工作。然后,您可以编写一个函数,将每组d 数字放入一个较大的字符串中。然后将它们组合成一个函数,获取每组数字并得到它们的交替和,并找到最大值。
  • 我的意思是 my_num = "n",因为我想使用列表将 num 拆分为字符串。
  • 我改变了缩进我希望现在可以了 [:

标签: python indexing


【解决方案1】:

这个呢:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 2020-06-16
    • 2018-05-17
    • 1970-01-01
    • 2011-09-25
    • 2019-07-30
    • 1970-01-01
    相关资源
    最近更新 更多