From be41df53c14e4e607a8822be57a4acad104c0480 Mon Sep 17 00:00:00 2001 From: dendogg Date: Mon, 24 Mar 2025 05:44:54 -0700 Subject: [PATCH 1/2] Updated two_num.py ### Summary Refactored the `two_sum` function to enhance clarity, improve structure, and ensure compliance with Python best practices (PEP 8). This version prioritizes intuitive logic, robust error handling, and clear documentation. ### Key Changes - **Function Renaming:** Renamed `twoSum` to `two_sum` to adhere to PEP 8 standards for function naming. - **Improved Variable Naming:** Replaced ambiguous names (`chk_map`, `compl`) with more intuitive identifiers (`seen_values`, `complement`). - **Added Type Hints:** Introduced `from typing import List, Union` to improve code clarity and provide IDE/linter support. - **Enhanced Docstring:** Expanded the docstring to include detailed function descriptions, argument explanations, and return behavior. - **Robust Return Handling:** Ensured the function explicitly returns `False` if no valid pair is found, improving clarity in edge cases. - **Improved Output Structure:** Added a `__main__` block with structured output for cleaner and more informative result display. ### Rationale These changes improve: - **Readability:** Clearer variable names and enhanced documentation make the code easier to understand for future developers (and my future self). - **Maintainability:** Improved structure provides a stronger foundation for future feature enhancements or modifications. - **Compliance:** Aligns with Python's official best practices for formatting and style (PEP 8). --- two_num.py | 69 +++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 50 insertions(+), 19 deletions(-) diff --git a/two_num.py b/two_num.py index 5780845217f..5174457affb 100644 --- a/two_num.py +++ b/two_num.py @@ -1,26 +1,57 @@ -"""Author Anurag Kumar (mailto:anuragkumarak95@gmail.com) +""" +Author: Anurag Kumar (mailto:anuragkumarak95@gmail.com) -Given an array of integers, return indices of the two numbers -such that they add up to a specific target. -You may assume that each input would have exactly one solution, -and you may not use the same element twice. +Description: + This function finds two numbers in a given list that add up to a specified target. + It returns the indices of those two numbers. -Example: -Given nums = [2, 7, 11, 15], target = 9, -Because nums[0] + nums[1] = 2 + 7 = 9, -return [0, 1]. +Constraints: + - Each input will have exactly one solution. + - The same element cannot be used twice. +Example: + >>> two_sum([2, 7, 11, 15], 9) + [0, 1] """ +from typing import List, Union + +def two_sum(nums: List[int], target: int) -> Union[List[int], bool]: + """ + Finds indices of two numbers in 'nums' that add up to 'target'. + + Args: + nums (List[int]): List of integers. + target (int): Target sum. -def twoSum(nums, target): - chk_map = {} - for index, val in enumerate(nums): - compl = target - val - if compl in chk_map: - indices = [chk_map[compl], index] - print(indices) - return [indices] - else: - chk_map[val] = index + Returns: + List[int]: Indices of the two numbers that add up to the target. + False: If no such pair is found. + """ + # Dictionary to track seen values and their indices + seen_values = {} + + for index, value in enumerate(nums): + complement = target - value + + # Check if the complement exists in the dictionary + if complement in seen_values: + return [seen_values[complement], index] + + # Add current value to dictionary for future reference + seen_values[value] = index + + # Return False if no pair is found (explicit is better than implicit) return False + +# Example usage +if __name__ == "__main__": + example_nums = [2, 7, 11, 15] + example_target = 9 + result = two_sum(example_nums, example_target) + + # Clean, professional result display + if result: + print(f"Indices that add up to {example_target}: {result}") + else: + print(f"No combination found that adds up to {example_target}.") From 45bdaba263079a1c496f81aa143517dc50af761c Mon Sep 17 00:00:00 2001 From: dendogg Date: Mon, 24 Mar 2025 05:57:34 -0700 Subject: [PATCH 2/2] Update two_num.py refactor: improve two_sum function with enhanced error handling, type hinting, and output clarity - Replaced Union with Optional for clearer type hinting - Added input validation for empty lists and non-integer values - Improved error handling with informative exceptions - Enhanced result display to include matched values alongside indices - Applied PEP 8 style improvements for better readability --- two_num.py | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/two_num.py b/two_num.py index 5174457affb..45719e1ebe4 100644 --- a/two_num.py +++ b/two_num.py @@ -14,9 +14,9 @@ [0, 1] """ -from typing import List, Union +from typing import List, Optional -def two_sum(nums: List[int], target: int) -> Union[List[int], bool]: +def two_sum(nums: List[int], target: int) -> Optional[List[int]]: """ Finds indices of two numbers in 'nums' that add up to 'target'. @@ -25,33 +25,34 @@ def two_sum(nums: List[int], target: int) -> Union[List[int], bool]: target (int): Target sum. Returns: - List[int]: Indices of the two numbers that add up to the target. - False: If no such pair is found. + Optional[List[int]]: Indices of the two numbers that add up to the target, + or None if no such pair is found. """ + if len(nums) < 2: + raise ValueError("Input list must contain at least two numbers.") + + if not all(isinstance(num, int) for num in nums): + raise TypeError("All elements in the list must be integers.") + # Dictionary to track seen values and their indices seen_values = {} for index, value in enumerate(nums): complement = target - value - - # Check if the complement exists in the dictionary if complement in seen_values: return [seen_values[complement], index] - - # Add current value to dictionary for future reference seen_values[value] = index - # Return False if no pair is found (explicit is better than implicit) - return False + return None # Example usage if __name__ == "__main__": example_nums = [2, 7, 11, 15] example_target = 9 result = two_sum(example_nums, example_target) - - # Clean, professional result display + if result: - print(f"Indices that add up to {example_target}: {result}") + num1, num2 = example_nums[result[0]], example_nums[result[1]] + print(f"Indices that add up to {example_target}: {result} (Values: {num1} + {num2})") else: print(f"No combination found that adds up to {example_target}.")