在严格条件下通过递归保留信息(Python)

2024-09-30 22:22:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我和我的搭档正在解决一个问题,在这个问题中,我们需要减少一个数组,并在片段上运行操作(在本例中为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]


Tags: inforlenifrangemath数组first
1条回答
网友
1楼 · 发布于 2024-09-30 22:22:00

如果必须递归,请以更简单的方式进行。去掉你需要的元素,然后在其余的元素中递归。你知道吗

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)])

相关问题 更多 >