From 5c417600e79ef462c6f8497e432c7ee48b9e9ce0 Mon Sep 17 00:00:00 2001 From: Alexander Ou Date: Tue, 8 Aug 2023 18:33:24 -0700 Subject: [PATCH] more exercises --- exercises.py | 33 +++++++++++++++++++++++++++++++++ solutions.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/exercises.py b/exercises.py index 931047e..bbf08f6 100644 --- a/exercises.py +++ b/exercises.py @@ -23,6 +23,14 @@ def dict_comprehension(l1: list): return None +def generator(l1: list, l2: list): + """For input lists l1 and l2 of integers, return a generator + that gives all pairings (e1, e2) of element e1 from l1 and + element e2 of l2.""" + + raise NotImplementedError("Not implemented") + + if __name__ == "__main__": l1 = [1, 2, 3, 4] l2 = [2, 4, 6, 8] @@ -47,3 +55,28 @@ if __name__ == "__main__": print("Desired output: {1: 1, 2: 4, 3: 9, 4: 16}") print(f"Output: : {dict_comprehension(l1)}") print("\n-------------------\n") + + print("generator:\n") + print("Desired output:") + print(" (1, 2)") + print(" (1, 4)") + print(" (1, 6)") + print(" (1, 8)") + print(" (2, 2)") + print(" (2, 4)") + print(" (2, 6)") + print(" (2, 8)") + print(" (3, 2)") + print(" (3, 4)") + print(" (3, 6)") + print(" (3, 8)") + print(" (4, 2)") + print(" (4, 4)") + print(" (4, 6)") + print(" (4, 8)") + print("Output: :") + try: + for pair in generator(l1, l2): + print(f" {pair}") + except NotImplementedError as e: + print(e) diff --git a/solutions.py b/solutions.py index 971924e..8655b0e 100644 --- a/solutions.py +++ b/solutions.py @@ -34,6 +34,16 @@ def dict_comprehension(l1: list): return result +def generator(l1: list, l2: list): + """For input lists l1 and l2 of integers, return a generator + that gives all pairings (e1, e2) of element e1 from l1 and + element e2 of l2.""" + + for e1 in l1: + for e2 in l2: + yield (e1, e2) + + if __name__ == "__main__": l1 = [1, 2, 3, 4] l2 = [2, 4, 6, 8] @@ -58,3 +68,25 @@ if __name__ == "__main__": print("Desired output: {1: 1, 2: 4, 3: 9, 4: 16}") print(f"Output: : {dict_comprehension(l1)}") print("\n-------------------\n") + + print("generator:\n") + print("Desired output:") + print(" (1, 2)") + print(" (1, 4)") + print(" (1, 6)") + print(" (1, 8)") + print(" (2, 2)") + print(" (2, 4)") + print(" (2, 6)") + print(" (2, 8)") + print(" (3, 2)") + print(" (3, 4)") + print(" (3, 6)") + print(" (3, 8)") + print(" (4, 2)") + print(" (4, 4)") + print(" (4, 6)") + print(" (4, 8)") + print("Output: :") + for pair in generator(l1, l2): + print(f" {pair}")