Необходимо игнорировать ведущие нули для функции подсчета цифр в Python - PullRequest
0 голосов
/ 31 мая 2018

.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) 

Ответы [ 3 ]

0 голосов
/ 31 мая 2018
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)
0 голосов
/ 27 июня 2019

как насчет такого решения для 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));
0 голосов
/ 31 мая 2018

Одно хакерское решение:

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)
...