CP_nate
CP_nate

Reputation: 41

how to make a function that checks a list of 20 digits

So i currently have a function that generates at random 20 digits shown below. Now i need to create another function that takes the first functions 20 digit number and counts the number of 0's within it. So far i have my first function:

What are my first steps into creating a function that counts the amount of 0's within the first function. I know i have to pass (random_number) over to my function as a parameter and then maybe a while loop to count the number of 0's?

Thanks for your help!

import random

def random_digits(n):

    range_start = 10**(n-1)
    range_end = (10**n)-1
    random_number= random.randint (range_start, range_end)
    print (random_number)

random_digits(20)

Upvotes: 0

Views: 82

Answers (2)

Saksham Varma
Saksham Varma

Reputation: 2130

def zeros(num):
    return str(num).count('0')

print zeros(random_digits(20))

Another way could be this:

def zeros(num):
    ctr = 0
    while num > 0:
        if num % 10 == 0:
            ctr += 1
        num = num/10
    return ctr

Upvotes: 2

koukouviou
koukouviou

Reputation: 820

You can do something like this to count the number of a specific character appears in a string (after converting your 20-digit number to string):

import random
def random_digits(n):
  range_start = 10**(n-1)
  range_end = (10**n)-1
  random_number= random.randint (range_start, range_end)
  print(random_number)
  return (random_number)

def countzeros(n):
  print(len([c for c in str(n) if c == '0']))

countzeros(random_digits(20))

which e.g. returns:

22031776701742051347
3

Upvotes: 1

Related Questions