我和我的搭档正在解决一个问题,在这个问题中,我们需要减少一个数组,并在片段上运行操作(在本例中为2),我们使用递归进行减少,并将数组的左右两侧返回到函数中。你知道吗
我们可以很好地工作,例如,使用数组[2,3,4,5,6,7,8,9],我们可以得到所有需要的片段。你知道吗
问题是,我们需要这些片段中的每一个来运行下一个片段的数学运算。你知道吗
例如,我们回到[2,3],然后把它转换成[5,-1]。然后我们回到[4,5],把它变成[9,-1],把它们合并成[14,-2,-4,0]。这是我们阵法的左边。这很有效。然后它在右手边,得到了我们想要的答案。这很有效。你知道吗
问题是,我们现在需要将这两个部分放在一起(不能使用全局变量)。我们已经被困在这里好几个小时了。我们只能通过递归传递简化的数组,如果我们初始化一个数组以容纳这两部分,那么当右侧开始时,它将被重置。你知道吗
谢谢
编辑:代码:H是给定的起始矩阵,但这无关紧要,因为它不相关,它只是在那里,所以单元测试通过(我们可以使用它,但我们真的不知道如何使用)
x的输入是[2,3,4,5,6,7,8,9]
def hadmatmult(H, x):
d = 0
n = len(x)
first = 0
last = len(x)
a = [0] * math.floor(n/2)
b = [0] * math.floor(n/2)
if n == 2:
temp1 = x[0]
x[0] = temp1 + x[1]
x[1] = temp1 - x[1]
else:
mid = math.floor((first+last)/2)
for i in range(first, mid):
a[i] = x[i]
hadmatmult(H, a)
for j in range(mid, last):
b[d] = x[j]
d = d + 1
hadmatmult(H, b)
if(len(a) == 2:
adds = [0] * len(a)
subs = [0] * len(a)
for t in range(0, len(a)):
adds[t] = a[t] + b[t]
subs[t] = a[t] - b[t]
#alladds = alladds + adds
#allsubs = allsubs + subs
print(adds)
print(subs)
输出:输出部件[14,-2,-4,0]和[30,-2,-4,0]
如果必须递归,请以更简单的方式进行。去掉你需要的元素,然后在其余的元素中递归。你知道吗
一路递归:
相关问题 更多 >
编程相关推荐