优化下列python代码中的递归函数:def words_divi(words, n): division_words = words / n print(division_words) if division_words <= words_max: if isinstance(division_words, int): for i in range(n): sram_list.append(str(division_words) + 'x' + str(bits_max)) else: round(division_words) if division_words in words_list: for i in range(n): sram_list.append(str(division_words) + 'x' + str(bits_max)) else: while division_words < words_max: division_words = division_words + 1 if division_words in words_list: for i in range(n): sram_list.append(str(division_words) + 'x' + str(bits_max)) else: n = n + 1 print(n) words_divi(words, n) if __name__ == "__main__": words_list = [] bits_list = [] words_list.append(list(range(32, 1025, 16)) + list(range(1056, 8193, 16))) bits_list.append(list(range(16, 145, 1))) words = 16388 bits = 148 words_max = max(words_list[0]) bits_max = max(bits_list[0]) words_min = min(words_list[0]) bits_min = min(bits_list[0]) sram_list = [] num = 2 words_divi(words, num) print(sram_list)
时间: 2023-04-10 13:02:56 浏览: 158
可以使用尾递归优化来优化该递归函数,避免栈溢出的问题。具体实现方法是将递归函数中的参数改为可变参数,并将递归调用改为参数的更新,直到满足递归终止条件。以下是优化后的代码:
def words_divi(words, n, sram_list):
division_words = words / n
print(division_words)
if division_words <= words_max:
if isinstance(division_words, int):
for i in range(n):
sram_list.append(str(division_words) + 'x' + str(bits_max))
else:
round(division_words)
if division_words in words_list:
for i in range(n):
sram_list.append(str(division_words) + 'x' + str(bits_max))
else:
while division_words < words_max:
division_words = division_words + 1
if division_words in words_list:
for i in range(n):
sram_list.append(str(division_words) + 'x' + str(bits_max))
return sram_list
else:
return words_divi(words, n+1, sram_list)
if __name__ == "__main__":
words_list = []
bits_list = []
words_list.append(list(range(32, 1025, 16)) + list(range(1056, 8193, 16)))
bits_list.append(list(range(16, 145, 1)))
words = 16388
bits = 148
words_max = max(words_list[0])
bits_max = max(bits_list[0])
words_min = min(words_list[0])
bits_min = min(bits_list[0])
sram_list = []
num = 2
sram_list = words_divi(words, num, sram_list)
print(sram_list)
阅读全文