Question
Python Question a) Write a generator every_nth ( seq , n ) that yields a sequence with every n th element from the sequence seq
Python Question
a) Write a generator every_nth(seq, n) that yields a sequence with every nth element from the sequence seq, starting with the first element.
Example: expression every_nth(range(0, 20), 3) returns a sequence with every third elements in range(0,20).
Thus this program:
for x in every_nth(range(0, 20), 3): print(x, end=", ")
prints 0, 3, 6, 9, 12, 15, 18,
b) Write a generator accumulate(seq, fun, val0) that returns the sequence of the values constituting the successive accumulation of elements starting with val0 (the initial value), using the given binary function fun for accumulation.
For illustration, accumulate([a,b,c], f, val0), for some function f and initial value val0 should return sequence val0, f(val0,a), f(f(val0,a), b), f(f(f(val0,a), b), c).
For example, expression accumulate(range(1,6), lambda x,y:x+y, 0) yields sequence 0, 1, 3, 6, 10, 15 since range(1,6) yields sequence 1, 2, 3, 4, 5, actual argument val0 is 0 and the accumulation function is simple addition:
0, (0+1), (2+(0+1)), (3+(2+(0+1))), (4+(3+(2+(0+1)))), (5+(4+(3+(2+(0+1))))).
c) Write an expression using the accumulate generator that displays the sequence of factorials 0!, 1!, 2!, ..., 6!.
d) Write an expression using the accumulate generator and the every_nth generator that displays the sequence of factorials 0!, 2!, 4!, ..., 10!.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started