我的合作伙伴和我正在研究一个问题,我们需要减少一个数组并对这些部分运行操作(在本例中为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]
答案 0 :(得分:0)
如果必须递归,请以更简单的方式进行。剥去你需要的元素,并通过其余元素进行递归。
x = [2,3,4,5,6,7,8,9]
def recurse_and_stuff(x):
if len(x) == 0:
# base case
return []
a, b, = x[:2], x[2:4]
m,n,o,p = [a[0]+a[1], a[0]-a[1], b[0]+b[1], b[0]-b[1]]
result = [[m+o, n+p, m-o, n-p]] + recurse_and_stuff(x[4:])
return result
>>> x = [2,3,4,5,6,7,8,9]
>>> recurse_and_stuff(x)
[[14, -2, -4, 0], [30, -2, -4, 0]]
>>> x = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
>>> recurse_and_stuff(x)
[[14, -2, -4, 0], [30, -2, -4, 0], [46, -2, -4, 0], [62, -2, -4, 0]]
# works for longer inputs as long as len(x) % 4 == 0
一直递减:
import itertools
def do_the_needful(a,b):
try:
zipped = zip(a,b)
except TypeError:
# a and b are ints, not lists of ints
zipped = [(a,b)]
return itertools.chain.from_iterable(zip(*[[aa+bb, aa-bb] for aa,bb in zipped]))
def recurse_and_stuff(x):
if len(x) == 1:
return list(x[0])
# if you only have to iterate through this, there's no
# need to call `list(...)` here.
return recurse_and_stuff([do_the_needful(x[i], x[i+1]) for i in range(0, len(x), 2)])