Optimizing code – Part 1

The first improvement we will make is to move away from int to string to int conversion in the previous code and implement integer only operations. We can do this by using the modulo and floor integer division.

Modulo

The modulo % operator gives you when dealing with whole base 10 (decimal) numbers, in other words the Natural numbers ( non-negative integers), the digit on the most right. The operation a mod b or a % b means divide a with b and whatever remains return that value.

Examples: – 15 % 10 = 5 – 124 % 10 = 4 – 40 % 10 = 0

Floor integer

Floor integer division given a and b is divide a with b and round that result off down to the nearest whole number or integer.

Examples: – 15 // 10 = 1 – 143 // 10 = 14 – 456 // 10 = 45

As might see, by using modulo we get the last digit and with floor integer we chop that number off so we can move through the numbers from right to left.

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

    s = sum([i ** len(digits) 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 on my laptop is: 0:07:53.349431

#code #python