Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count occurrences of digit 'x' in range (0,n]

So I'm trying to write a python function that takes in two arguments, n and num, and counts the occurrences of 'n' between 0 and num. For example,

countOccurrences(15,5) should be 2.

countOccurrences(100,5) should be 20.

I made a simple iterative solution to this problem:

def countOccurrences(num,n):
  count=0
  for x in range(0,num+1):
    count += countHelper(str(x),n)
  return count

def countHelper(number,n):
  count=0
  for digit in number:
    if digit==n:
      count += 1
  return count

This ran into obvious problems if I tried to call countOccurrences(100000000000,5). What my question is is how can I make this more efficient? I want to be able to handle the problem "fairly" fast, and avoid out of memory errors. Here is my first pass at a recursive solution trying to do this:

def countOccurence(num, n):
  if num[0]==n:
    return 1
  else:
    if len(num) > 1:
      return countOccurence(num[1:],n) + countOccurence(str((int(num)-1)),n)
    else:
      return 0
like image 658
catagon87 Avatar asked Jun 29 '15 15:06

catagon87


People also ask

How do you count occurrences of a digit in a number?

Approach: Take out the digits one by one in N and check if this digit is equal to D. If equal, then increment the count by 1. In the end, print the count.

How many occurrences of the digit 4 are seen in the range of numbers 1 to 200?

Hence, assuming we are counting only whole numbers, we can conclude that the digit 4 is used 40 times between 1 and 200.

How can you count the occurrence of 1 from 1 to 99999999 in C#?

Count(c=>c=='1'); You could even one-line it with a pure Linq solution: var count = Enumerable. Range(1,99999999).

How many times does the digit 0 appear from 1 100?

So "0" appears 11 times.


1 Answers

This won't hit into any memory problems, until max_num is small enough to fit in a C long. Basically it's still a brute-force algorithm, though significantly optimized for Python.

def count_digit(max_num, digit):
    str_digit = str(digit)
    return sum(str(num).count(str_digit) for num in xrange(max_num+1))
like image 171
Eli Korvigo Avatar answered Oct 02 '22 15:10

Eli Korvigo