# iterative left & right reducer functions

def iReduce(li, fn, acc=0):
  for x in li:
    acc = fn(acc, x)
  return acc 

def iReduceRight(li, fn, acc=0):
  for x in reversed(li):
    acc = fn(acc, x)
  return acc 

# recursive left & right reducer functions

def rReduce(li, fn, acc=0):
  if len(li) == 0: return acc 
  head, *tail = li 
  acc = fn(acc, head)
  return rReduce(tail, fn, acc)

def rReduceRight(li, fn, acc=0):
  if len(li) == 0: return acc 
  *init, last = li 
  acc = fn(acc, last)
  return rReduceRight(init, fn, acc)
    
nums = [1,2,3,4,5]
print(nums)

# using iterative left reducer
total = iReduce(nums, (lambda a, c: a + c), 0)
print(total)

# using iterative right reducer
total = iReduceRight(nums, (lambda a, c: a + c), 0)
print(total)

# using recursive left reducer
total = rReduce(nums, (lambda a, c: a + c), 0)
print(total)

# using recursive right reducer
total = rReduceRight(nums, (lambda a, c: a + c), 0)
print(total)

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: