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? For example, in the number 55443352, 5 + 4 + 3 + 5 = 17. It was expected to get this.
`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+):
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
.
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
cnt_sum(55443352)# result is 17
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.