fork download
  1. #/usr/bin/env python3
  2.  
  3. def fold(function, value, iterable, /, *, reverse = None):
  4. it = (reversed if reverse else iter)(iterable)
  5. args = lambda value, element: (value, element) if reverse == False else \
  6. (element, value)
  7. for element in it:
  8. value = function(*args(value, element))
  9. return value
  10.  
  11. if __name__ == '__main__':
  12. from operator import add
  13. z = 'z'
  14. print(f'{fold(add, z, ["a", "b", "c", "d"])}\n{fold(add, z, ["a", "b", "c", "d"], reverse = True)}\n{fold(add, z, ["a", "b", "c", "d"], reverse = False)}')
  15.  
Success #stdin #stdout 0.04s 9752KB
stdin
Standard input is empty
stdout
dcbaz
abcdz
zabcd