Optimizing code – Part 2

A small mini optimization is to move the call to len out as the length of the number does not change.

import sys
from datetime import datetime

def is_narcissistic(x: int) -> bool:
    org = x
    digits = []
    while x > 0:
        _, x = digits.append(x % 10), x // 10
    power = len(digits)
    s = sum([i ** power for i in digits])
    return s == org

def find_narcissistic_numbers(desired: int) -> None:
    for x in range(sys.maxsize):
        if is_narcissistic(x):
            desired -= 1
        if desired == 0:
            return

start = datetime.utcnow()
find_narcissistic_numbers(28)
print(datetime.utcnow() - start)

The time for this code to run on my laptop is: 0:07:14.172538

#code #python