[英]It is necessary to calculate the sum of the digits on the even positions. What could be the mistake?
It is necessary to count the numbers on the even positions.有必要计算偶数位置上的数字。 I wrote a function, but I can't figure out what is the error?我写了一个function,但我不知道是什么错误? For example, in the number 55443352, 5 + 4 + 3 + 5 = 17. It was expected to get this.比如在数字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)`
Please help me figure it out..请帮我弄清楚..
while tmp // = 10:
^
SyntaxError: invalid syntax
You can't assign temp there unless you're using the walrus operator (3.8+):除非您使用海象运算符(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
With walrus operator:使用海象运算符:
In [99]: while temp := temp // 10:
...: print(temp)
...:
10
1
Otherwise you can do this:否则你可以这样做:
In [99]: while temp:
...: print(temp)
...: temp //= 10
...:
100
10
1
Depending where you place the floor operator will depend on whether or not you also get the first value of temp
.根据您放置楼层运算符的位置,将取决于您是否还获得temp
的第一个值。
Lots of errors in posted code.发布的代码中有很多错误。
Code can be simplfied to:代码可以简化为:
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_
Can be further simplified to可以进一步简化为
def cnt_sum(number):
return sum(int(v) for i, v in enumerate(str(number)) if i % 2 == 0)
Output Output
cnt_sum(55443352)# result is 17
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.