arrays - Retaining information through recursion under strict conditions (Python) -
my partner , working on problem in need reduce array , run operations on pieces (in case, of 2), reducing recursion , sending left-right hand sides of array function.
we have working fine, , example, using array [2, 3, 4, 5, 6, 7, 8, 9] pieces need.
the problem is, need each of these pieces run math operation on next piece get.
so, example recur down [2, 3] , transform [5, -1]. recur down [4, 5] , change [9, -1] , combine them [14, -2, -4, 0]. left hand side of our array. , works great. , right hand side, , gets answer want. works great.
the problem, need both parts (can't use global variables). , have been stuck here several hours. can pass simplified array through recursion, , if initialize array hold both parts reset when right-hand side starts.
thanks
edit: code: h starting matrix given, doesn't matter, no relevance there unit test goes through (we use it, don't know how)
the imput x [2,3,4,5,6,7,8,9]
def hadmatmult(h, x): d = 0 n = len(x) first = 0 last = len(x) = [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) in range(first, mid): a[i] = x[i] hadmatmult(h, a) 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) 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)
output: outputs parts, [14, -2, -4, 0] , [30, -2, -4, 0]
if must recurse, in simpler way. strip off elements need , recurse through rest.
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 longer inputs long len(x) % 4 == 0
to recurse way down:
import itertools def do_the_needful(a,b): try: zipped = zip(a,b) except typeerror: # , b ints, not lists of ints zipped = [(a,b)] return itertools.chain.from_iterable(zip(*[[aa+bb, aa-bb] aa,bb in zipped])) def recurse_and_stuff(x): if len(x) == 1: return list(x[0]) # if have iterate through this, there's no # need call `list(...)` here. return recurse_and_stuff([do_the_needful(x[i], x[i+1]) in range(0, len(x), 2)])
Comments
Post a Comment