Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Problem 3. Functional Code with Random Number Sequences Write a generator gen_rn

ID: 3818036 • Letter: P

Question

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 that does the same thing using generator expressions and one for loop. Place all the code in file p3.py and paste that in h6.doc.

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

Explanation / Answer

>>> def function_1(a,b):
... yield a,b
...
>>> def function_2(a,b):
... yield a
... yield b
...
>>> a = 1
>>> b = 2
>>>
>>> function_1(a,b)
<generator question function_1 at 0x1007931b0>
>>> function_2(a,b)
<generator protest function_2 at 0x1007931f8>
>>> tuple(function_1(a,b))
((1, 2),)
>>> tuple(function_2(a,b))
(1, 2)
>>> for thing in function_1(a,b):
... print(item)
...
(1, 2)
>>> for thing in function_2(a,b):
... print(item)
...
1
2

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote