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
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