From e482c2ccfedd2c6cb79f5ab28ced1602d6e6582b Mon Sep 17 00:00:00 2001 From: Kiana Date: Thu, 19 Jan 2023 15:44:04 -0800 Subject: [PATCH 1/2] updating with working solution passing all tests --- lib/newman_conway.py | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/lib/newman_conway.py b/lib/newman_conway.py index 7f5341a..b79a784 100644 --- a/lib/newman_conway.py +++ b/lib/newman_conway.py @@ -1,6 +1,34 @@ +nc_dict = { + 1: 1, + 2: 1 +} def newman_conway(num): """ Returns a list of the Newman Conway numbers for the given value. Time Complexity: ? Space Complexity: ? """ - pass + + if num <= 0: + raise ValueError + elif num == 1: + return str(nc_dict[1]) + + for i in range(3, num + 1): + nc_dict[i] = newman_conway_helper(nc_dict[i - 1]) + newman_conway_helper(i - nc_dict[i - 1]) + + output_string = "" + for n in nc_dict.keys(): + output_string += f"{str(nc_dict[n])} " + return output_string[:-1] + +def newman_conway_helper(n): + if n == 1: + return nc_dict[1] + elif n == 2: + return nc_dict[2] + elif n >= 3: + for i in range(3, n+1): + if i not in nc_dict: + nc_dict[i] = newman_conway_helper(nc_dict[i - 1]) + newman_conway_helper(i - nc_dict[i - 1]) + + return newman_conway_helper(nc_dict[n - 1]) + newman_conway_helper(n - nc_dict[n - 1]) \ No newline at end of file From 5580789bbac307e8662a3a849d41f6c1f76ae155 Mon Sep 17 00:00:00 2001 From: Kiana Date: Thu, 19 Jan 2023 16:30:57 -0800 Subject: [PATCH 2/2] refactored to be O(n) time complexity and use memo instead of global dictionary --- lib/newman_conway.py | 34 ++++++++++------------------------ 1 file changed, 10 insertions(+), 24 deletions(-) diff --git a/lib/newman_conway.py b/lib/newman_conway.py index b79a784..289588d 100644 --- a/lib/newman_conway.py +++ b/lib/newman_conway.py @@ -1,34 +1,20 @@ -nc_dict = { - 1: 1, - 2: 1 -} def newman_conway(num): """ Returns a list of the Newman Conway numbers for the given value. - Time Complexity: ? - Space Complexity: ? + Time Complexity: O(n) where n is the input + Space Complexity: O(n) where n is the input """ - if num <= 0: + if num < 1: raise ValueError elif num == 1: - return str(nc_dict[1]) + return "1" + + memo = [0, 1, 1] + output_string = "1 1 " for i in range(3, num + 1): - nc_dict[i] = newman_conway_helper(nc_dict[i - 1]) + newman_conway_helper(i - nc_dict[i - 1]) + new_number = memo[memo[i - 1]] + memo[i - memo[i - 1]] + memo.append(new_number) + output_string += f"{str(new_number)} " - output_string = "" - for n in nc_dict.keys(): - output_string += f"{str(nc_dict[n])} " return output_string[:-1] - -def newman_conway_helper(n): - if n == 1: - return nc_dict[1] - elif n == 2: - return nc_dict[2] - elif n >= 3: - for i in range(3, n+1): - if i not in nc_dict: - nc_dict[i] = newman_conway_helper(nc_dict[i - 1]) + newman_conway_helper(i - nc_dict[i - 1]) - - return newman_conway_helper(nc_dict[n - 1]) + newman_conway_helper(n - nc_dict[n - 1]) \ No newline at end of file