.123
以字符串的形式转换为0.123
,因此我的计数结果是(0,0,1)
而不是(0,0,0)
。我需要忽略前导0,但是我不知道是如何。
def digit_count(n):
n=str(int(n))
even_count=0
odd_count=0
zero_count=0
for i in n:
if int(i)%10 ==0:
zero_count +=1
elif int(i) % 2 ==0:
even_count += 1
elif int(i) %2 !=0:
odd_count +=1
return(even_count,odd_count,zero_count)
发布于 2018-05-31 08:44:52
一个老生常谈的解决方案:
def digit_count(n):
if isinstance(n, float) and str(n).split('.')[0]=='0':
return (0,0,0)
else:
n=str(int(n))
even_count=0
odd_count=0
zero_count=0
for i in n:
if int(i)%10 ==0:
zero_count +=1
elif int(i) % 2 ==0:
even_count += 1
elif int(i) %2 !=0:
odd_count +=1
return(even_count,odd_count,zero_count)
发布于 2018-05-31 18:57:04
def digit_count( n ) :
## convert number to string
n = str( int(n))
## declare counts
even_count, zero_count = 0,0
for i in n :
i = int(i)
## case when n = 0.1231
if len(n) == 1 and i == 0:
return (0,0,0)
## case when n contains 0
elif i == 0:
zero_count += 1
## case when n contains even
elif i != 0 and i%2 == 0 :
even_count += 1
return ( even_count, len(n) - even_count- zero_count, zero_count )
digit_count( 123059.9 )
>> (1,4,1)
digit_count( 0.123 )
>> (0,0,0)
发布于 2019-06-27 09:12:22
对于python 3解决方案来说,像这样的东西怎么样?
def digit_count(n):
n=list(str(int(n))); #turn into a list array
if n[-1] == "0": #get the first item (leading zeroes).
n[-1] = ""; #delete it.
n=''.join(n); #rejoin as a new string.
even_count = odd_count = zero_count = 0; #I cleaned this up too.
for i in n:
if int(i)%10 == 0:
zero_count += 1
elif (int(i) % 2 == 0) ^ (int(i) %2 == 0): #I cleaned this up I hope you don't mind.
even_count += 1
return(even_count,odd_count,zero_count)
print(digit_count(.123));
https://stackoverflow.com/questions/50615031
复制相似问题