0
def fold2(op, term, a, next, b, base): 
    if a > b:
        return base
    else:
        return op (term(a), fold2(op, term, next(a), next, b, base))



def geometric_series(a, r, n):
    return fold2(lambda x,y: x+y, lambda x: a*(r**(n-1)), 1, lambda n: n+1, n, a)

Can someone help me with this code. It's suppose to give a geometric series but i am only allowed to change the part def geometric_series(a, r, n). What's wrong with it?

a) geometric_series(1/2, 1/2, 3) = 0.875 (correct)

b) geometric_series(1, 2, 4) = 33 (wrong) correct answer is 15

user3234828
  • 61
  • 3
  • 8

3 Answers3

0

There's a mistake in the second lambda of your code:

lambda x: a*(r**(n-1))

I think n and x should actually be the same variable here:

lambda t: a*(r**(t-1))

In addition to that I changed the third argument of fold2 from 1 to 2 and everything is working as expected.

Waldir Leoncio
  • 10,853
  • 19
  • 77
  • 107
Marko Knöbl
  • 447
  • 2
  • 9
0

Third argument of fold2 should should have the same variable. Either both n or both x. Also, Your final argument, which is the base case, should be 0

Charles
  • 1
  • 1
0

Just to add on, the base should be 0 and not a, if not for your test case there will additional 1.

def geometric_series(a, r, n): return fold2(lambda x, y: x+y, lambda n: a*(r**(n-1)), 1, lambda n: n+1, n, 0)