Home > Software engineering >  How do I optimize this recursive function that counts the number of n-digit hexadecimal numbers whos
How do I optimize this recursive function that counts the number of n-digit hexadecimal numbers whos

Time:03-14

def hexify(summ, l, count = 0):
    if sum == 0:
        return 1
    for i in range(16):
        if i < summ and l > 1:
            count  = hexify(summ-i, l-1)
        elif i == summ and l > 0:
            count  = 1
    return count 
            
hexa = str(input())[2:] #input tag eg. 0x0121
summ = sum(int(digit, 16) for digit in hexa)
print(hexify(summ, len(hexa)) - 1)

What this code does is find the number of n-digit hexadecimal numbers whose digits equal to a certain sum. For example, if the given hexadecimal number is 0x12, the function would return 3 (meaning there are 3 hex numbers whose digits sum to three, excluding 0x12, which are 0x03 0x30 and 0x21).

The problem is the given constraints are 1 > 1 > 10, and the code stops functioning once the length l exceeds 6. How do I optimize this? (Recursion is required)

CodePudding user response:

If you want to speed up your code you can use the cache decorator

@functools.cache(user_function) Simple lightweight unbounded function cache. Sometimes called “memoize”.

Returns the same as lru_cache(maxsize=None), creating a thin wrapper around a dictionary lookup for the function arguments. Because it never needs to evict old values, this is smaller and faster than lru_cache() with a size limit.

https://docs.python.org/dev/library/functools.html#functools.cached_property

from functools import cache

@cache
def hexify(summ, l, count = 0):
    if sum == 0:
        return 1
    for i in range(16):
        if i < summ and l > 1:
            count  = hexify(summ-i, l-1)
        elif i == summ and l > 0:
            count  = 1
    return count 
            
hexa = str(input())[2:] #input tag eg. 0x0121
summ = sum(int(digit, 16) for digit in hexa)
print(hexify(summ, len(hexa)) - 1)
  • Related