[英]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.