我正在嘗試設計一個名為“distinct_summands”的函式,它接受一個正整數 n,輸出 k 個不同整數 a1,..., ak 的串列,使得 a1 ... ak= n 和 k 與可能的。
測驗用例的一些示例如下:distinct_summands(8)=[1,2,5]、distinct_summands(2)=[2]、distinct_summands(14)=[1,2,3,8]。我自己測驗了 n=1,2,3...,100K 的代碼。到目前為止我沒有發現任何錯誤。但是,當我將代碼提交給黑盒代碼測驗器時,出現“索引外”錯誤。
我嘗試了我所知道的一切以找出問題所在。但我仍然不知道出了什么問題。我在下面附上了我的代碼。有人可以讓我知道我做錯了什么嗎?
def distinct_summands(n):
if n <=2:
return [n]
remainder = n
number_list = list(range(1, n 1))
prev_pos, curr_pos = 0, 0
summands = []
while remainder > number_list[prev_pos]:
remainder = remainder - number_list[curr_pos]
prev_pos = curr_pos
summands.append(number_list[prev_pos])
if remainder > 2* number_list[curr_pos 1]:
curr_pos = 1
else:
curr_pos = remainder -1
return summands
uj5u.com熱心網友回復:
如果 n 很大,則number_list = list(range(1, n 1))需要大量記憶體(可能是導致out of index錯誤)。但是你用number_list陣列只得到元素,所以我想你可以替換number_list[index],以index 1解決您的問題:
def distinct_summands(n):
if n <= 2:
return [n]
remainder = n
prev_pos, curr_pos = 0, 0
summands = []
while remainder > prev_pos 1:
remainder = remainder - (curr_pos 1)
prev_pos = curr_pos
summands.append(prev_pos 1)
if remainder > 2 * (curr_pos 2):
curr_pos = 1
else:
curr_pos = remainder - 1
return summands
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/402256.html
上一篇:子串數
