Skip to content

Instantly share code, notes, and snippets.

@abdulmuneer
Last active August 29, 2015 14:04
Show Gist options
  • Save abdulmuneer/a78767cadb510abe0fde to your computer and use it in GitHub Desktop.
Save abdulmuneer/a78767cadb510abe0fde to your computer and use it in GitHub Desktop.
function to find the number of occurrences of '2' in first 'n' numbers.
#one easy solution:
def get_digit_count(n):
count = 0
for numbers in range(n):
count = count + str(numbers).count('2')
return count
# in the above program:
# 'def' defines a function. so we can call later like 'get_digit_count(1000)'
# 'range' is a python function that gives a list of numbers.
# range(5) = [0, 1, 2, 3, 4]
# one liner solution:
sum(str(numbers).count('2') for numbers in range(n))
# we can explain this later step by step
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment