简体   繁体   中英

Specific digit occurence counter for a given integer from 0 to given integer in Python

I want to write a function that counts a given number n's digits occurrence. I have the following code:

def count_number(n):
    c = 0
    for i in range(0,n):         # To parse from 0 to given number n
        for digit in str(n):     # To parse given n's digits
            if digit == '9':     # Let's say we want to count 9 occurrences
                c = c + 1        # 9 counter
    return c

Some expected outputs would be:

Given n - Return c:

n = 8 - c = 0 (0 nines in 8)// n = 100 - c = 20 (20 nines in 100) // n = 909 - c = 191 (191 nines in 909)

Instead most of my return are 0.

Please help.

You've just made a tiny typo in the your code and fallen foul of for loops stopping before the final number.

Your loop looks like this:

for i in range(0,n): 

But it should be like to account for the loop starting from 0 not 1:

for i in range(0,n+1): 

In your code you are iterating on n not on i so you just need to switch this line:

 for digit in str(n):

to

 for digit in str(i):

So your final code should look like this:

def count_number(n):
    c = 0
    for i in range(0,n+1):         # To parse from 0 to given number n
        for digit in str(i):     # To parse given n's digits
            if digit == '9':     # Let's say we want to count 9 occurrences
                c = c + 1        # 9 counter
    return c

print(count_number(8))
#0
print(count_number(100))
#20
print(count_number(909))
#191

It can be easily done with the "count" function

A=int(input())
s=""
for i in range(A):
    s=s+str(i)
print(s.count("9"))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM