.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)
答案 0 :(得分:0)
一个hacky解决方案:
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)
答案 1 :(得分:0)
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)
答案 2 :(得分:0)
对于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));