简体   繁体   中英

How do I optimize this recursive function that counts the number of n-digit hexadecimal numbers whose digits equal a sum?

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM