繁体   English   中英

需要计算偶数位的数字之和。 可能是什么错误?

[英]It is necessary to calculate the sum of the digits on the even positions. What could be the mistake?

有必要计算偶数位置上的数字。 我写了一个function,但我不知道是什么错误? 比如在数字55443352中,5+4+3+5=17。本来就应该得到这个。

`def cnt_sum(one):
sum = 0
tmp = one
i=0
while tmp //= 10:
    i = i + 1 
while one:
    if (i==%2 == 0)
        sum +=one%10
        one/=10
return sum

cnt_sum(55443352)`

请帮我弄清楚..

while tmp // = 10:
           ^
  SyntaxError: invalid syntax

除非您使用海象运算符(3.8+),否则您不能在那里分配 temp:

In [98]: while temp = temp // 10:
    ...:     print(temp)
    ...:
  File "<ipython-input-98-38590cf2c5e0>", line 1
    while temp = temp // 10:
               ^
SyntaxError: invalid syntax

使用海象运算符:

In [99]: while temp := temp // 10:
    ...:     print(temp)
    ...:
10
1

否则你可以这样做:

In [99]: while temp:
    ...:     print(temp)
    ...:     temp //= 10
    ...:
100
10
1

根据您放置楼层运算符的位置,将取决于您是否还获得temp的第一个值。

发布的代码中有很多错误。

代码可以简化为:

def cnt_sum(number):
    sum_ = 0                  # don't use sum as a variable name (conflicts with built-in function(
    str_number = str(number)  # number as string
    for i, v in enumerate(str_number):
        # enumerate is Pythonic method for iterating through a list of values with the index
        if i % 2 == 0:
            # We're on an even index
            sum_ += int(v)   # add digit at this index (need int since we have a lit of character digits)
    return sum_

可以进一步简化为

def cnt_sum(number):
    return sum(int(v) for i, v in enumerate(str(number)) if i % 2 == 0)

Output

cnt_sum(55443352)# result is 17

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM