Question: Problem 3. Functional Code with Random Number Sequences Write a generator gen_rndtup ( n ) that creates an infinite sequence of tuples ( a ,

Problem 3. Functional Code with Random Number Sequences

Write a generator gen_rndtup(n) that creates an infinite sequence of tuples (a, b) where a and b are random integers, with 0 < a,b < n. If n == 7, then a and b could be the numbers on a pair of dice. Use the random module.

a) Use lambda expressions, the itertools.islice function (https://docs.python.org/3/library/itertools.html#itertools.islice), and the filter function to display the first 10 generated tuples (a, b) from gen_rndtup(7) that have a + b >= n // 2.

Example: with n==7 the output could be: (4,1), (2,6), (6,6),(3,5),...

b) Write code using generator expressions and one for loop that displays the first 10 random integer

tuples (a, b), with 0<

a,b<n

, where

a

+ b >= n // 2 and

n

being a positive integer local variable initialized with value 7. Do not use the gen_rndtup(n) generator from a). You may use other functions

Extra credit part, for 5 points:

c) Use lambda expressions, map(), the itertools.islice, functools.reduce(), and the filter function to display the sum of first 10 generated tuples (a, b) that have sum a + b >= n // 2.

The sum of tuples is done component-wise for each tuple element. E.g. if the sequence filtered is (4,1), (2,6), (6,6),(3,5), then the sum of these tuples that is displayed is (4+2+6+3, 1+6+6+5) = (15, 18).

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!