需要计算偶数位置上的数字。我写了一个函数,但我不知道错误是什么?例如,在数字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)
输出
cnt_sum(55443352)# result is 17