Search code examples
pythonsumnumberssequencedigits

How to find a specific number in a sequence of number with a constant sum of digit equal to 9 python?


Enter the natural number N (1 <= N <= 1,000,000). Print to the screen the Nth number of the sequence: 9 18 27 36 45 54 63 72 81 90 108 117 (they all have their sum of digit equal to 9)

N = 9+(int(input())-1)*9
def sumnum(N):
    sum = 0
    while N > 0:
        d = N%10
        N = N//10
        sum += d
sumnum(N)
while sum != 9:
    N+=1
    sumnum(N)
print(N)

Here's my code and it got this error

TimeLimitError: Stopped on Line 4

Solution

  • Your sumnum function doesn't return anything, so it never changes sum (or any other value) outside of the function. Normally you'd get an error trying to compare an undefined variable, but sum is actually the name of a builtin function, so that's what you're comparing 9 to.

    Here's a simple approach: iterate through all numbers in a while loop, and check the sum of each one's digits by converting it to a string and summing the int values of its characters. Each time you find one whose sum is 9, decrement N by one. When it hits zero, print the current number.

    >>> N = 12
    >>> i = 0
    >>> while True:
    ...     i += 1
    ...     if sum(int(d) for d in str(i)) == 9:
    ...         N -= 1
    ...     if N == 0:
    ...         print(i)
    ...         break
    ...
    117
    

    Here's a more code-golf-y approach using a filtered generator with itertools.count() (less efficient for big numbers because it builds a list of the sequence up to N instead of just printing the last element):

    >>> import itertools
    >>> list(zip(range(N), (i for i in itertools.count() if sum(int(d) for d in str(i)) == 9)))[-1][-1]
    117