In: Computer Science
PleaSe write a GENERATOR function in Python: how to write it with yield ?
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Thanks in advance
Write /the/ generator /function/ genAccum(seq, fn), which takes in an iterable and a function fn and yields each accumulated value from applying fn to the running total and the next element. (Note: to convert an iterable into an iterator you use iter(iterable))
'''
>>> add = lambda x, y: x + y
>>> mul = lambda x, y: x * y
>>> list(genAccum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
add))
[1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
>>> list(genAccum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
mul))
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
'''
Program Code to Copy:
# genAccum function with yield def genAccum(seq, fn): # Initializing current value to first value curr = seq[0] # Yielding the current value yield curr # Running a loop from second value to last value for i in range(1, len(seq)): # Updating current value by applying fn to current value and element at current index curr = fn(curr, seq[i]) # Yielding the current value yield curr add = lambda x, y: x + y mul = lambda x, y: x * y print(list(genAccum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], add))) print(list(genAccum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], mul)))
Program Code Screenshot with Output: