[英]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.这段代码的作用是找到位数等于某个和的 n 位十六进制数的个数。 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).
例如,如果给定的十六进制数是 0x12,则 function 将返回 3(意味着有 3 个十六进制数的数字和为三,不包括 0x12,即 0x03 0x30 和 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?问题是给定的约束是 1 > 1 > 10,一旦长度 l 超过 6,代码就会停止运行。我该如何优化它? (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.
@functools.cache(user_function) 简单的轻量级无界 function 缓存。 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.
返回与 lru_cache(maxsize=None) 相同,为 function arguments 的字典查找创建一个薄包装器。因为它永远不需要驱逐旧值,所以它比具有大小限制的 lru_cache() 更小更快。
https://docs.python.org/dev/library/functools.html#functools.cached_property 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.