Home > Mobile >  Calculate the sequence of continuous numbers
Calculate the sequence of continuous numbers

Time:01-31

I'm trying to find a way to calculate the amount of continuous digits on a given number. IE Number 7 has 7 continuous digits, while number 10 has 11 continuous digits. Here's an image to depict the problem

enter image description here

The first row shows the sequence and the second one shows the amount of numbers this has.

This has to be on python, but any ideas will help

CodePudding user response:

Here is my attempt at understanding your question.


def continuous_digits(x):
    count = 0
    for i in range(1,x 1):
        s = str(i)
        count  = len(s)
    return count

# Test the function
for i in range(7,12):
    print(f'Number: {i}: Continuous Digit Length: {continuous_digits(i)}')

The output:

Number: 7: Continuous Digit Length: 7
Number: 8: Continuous Digit Length: 8
Number: 9: Continuous Digit Length: 9
Number: 10: Continuous Digit Length: 11
Number: 11: Continuous Digit Length: 13

CodePudding user response:

You could build a string with all the digits and get its length (but that's not very efficient):

n = 103
r = len("".join(map(str,range(1,n 1))))  # 201

Alternatively what you can do it compute the number of 1-digit, 2-digit, ... x-digit values that are below n. You can figure out these numbers starting with the largest number of digit (which you can obtain using the base 10 logarithm).

from math import log

d = int(log(n,10))
r = (d 1)*(n 1-10**d)   sum((i 1)*9*10**i for i in range(d)) # 201
  •  Tags:  
  • Related