diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index aa6bff3ad1da..176dfaa76723 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,7 +2,7 @@ ## Before contributing -Welcome to [TheAlgorithms/Python](https://github.com/TheAlgorithms/Python)! Before submitting your pull requests, please ensure that you __read the whole guidelines__. If you have any doubts about the contributing guide, please feel free to [state it clearly in an issue](https://github.com/TheAlgorithms/Python/issues/new) or ask the community on [Gitter](https://gitter.im/TheAlgorithms/community). +Welcome to [TheAlgorithms/Python](https://github.com/TheAlgorithms/Python)! Before submitting your pull requests, please ensure that you __read the whole guidelines carefully__. If you have any doubts about the contributing guide, please feel free to [state it clearly in an issue](https://github.com/TheAlgorithms/Python/issues/new) or ask the community on [Gitter](https://gitter.im/TheAlgorithms/community). ## Contributing @@ -21,7 +21,7 @@ __Improving comments__ and __writing proper tests__ are also highly welcome. ### Contribution -We appreciate any contribution, from fixing a grammar mistake in a comment to implementing complex algorithms. Please read this section if you are contributing your work. +We appreciate any contribution, from fixing a grammatical mistake in a comment to implementing complex algorithms. Please read this section if you are contributing your work. Your contribution will be tested by our [automated testing on GitHub Actions](https://github.com/TheAlgorithms/Python/actions) to save time and mental energy. After you have submitted your pull request, you should see the GitHub Actions tests start to run at the bottom of your submission page. If those tests fail, then click on the ___details___ button to read through the GitHub Actions output to understand the failure. If you do not understand, please leave a comment on your submission page and a community member will try to help. diff --git a/digital_image_processing/convert_to_negative.py b/digital_image_processing/convert_to_negative.py index 9bf2d8f2c075..227aab51bc54 100644 --- a/digital_image_processing/convert_to_negative.py +++ b/digital_image_processing/convert_to_negative.py @@ -25,6 +25,6 @@ def convert_to_negative(img): neg = convert_to_negative(img) # show result image - imshow("negative of original image", img) + imshow("negative of original image", neg) waitKey(0) destroyAllWindows() diff --git a/divide_and_conquer/convex_hull.py b/divide_and_conquer/convex_hull.py index b1ab33cc9415..93f6daf1f88c 100644 --- a/divide_and_conquer/convex_hull.py +++ b/divide_and_conquer/convex_hull.py @@ -124,7 +124,7 @@ def _construct_points( else: try: points.append(Point(p[0], p[1])) - except IndexError, TypeError: + except (IndexError, TypeError): print( f"Ignoring deformed point {p}. All points" " must have at least 2 coordinates." diff --git a/dynamic_programming/catalan_numbers.py b/dynamic_programming/catalan_numbers.py index a62abe36d670..7b74f2763d43 100644 --- a/dynamic_programming/catalan_numbers.py +++ b/dynamic_programming/catalan_numbers.py @@ -71,7 +71,7 @@ def catalan_numbers(upper_limit: int) -> "list[int]": print(f"The Catalan numbers from 0 through {N} are:") print(catalan_numbers(N)) print("Try another upper limit for the sequence: ", end="") - except NameError, ValueError: + except (NameError, ValueError): print("\n********* Invalid input, goodbye! ************\n") import doctest diff --git a/graphs/depth_first_search_2.py b/graphs/depth_first_search_2.py index 8fe48b7f2b42..e352ffdcb90a 100644 --- a/graphs/depth_first_search_2.py +++ b/graphs/depth_first_search_2.py @@ -71,14 +71,12 @@ def dfs(self) -> None: 0 1 2 3 """ # visited array for storing already visited nodes - visited = [False] * len(self.vertex) + visited = {v: False for v in self.vertex} + for vertex in self.vertex: + if not visited[vertex]: + self.dfs_recursive(vertex, visited) - # call the recursive helper function - for i in range(len(self.vertex)): - if not visited[i]: - self.dfs_recursive(i, visited) - - def dfs_recursive(self, start_vertex: int, visited: list) -> None: + def dfs_recursive(self, start_vertex: int, visited: dict) -> None: """ Perform a recursive depth-first search (DFS) traversal on the graph. @@ -93,7 +91,7 @@ def dfs_recursive(self, start_vertex: int, visited: list) -> None: >>> g.add_edge(2, 0) >>> g.add_edge(2, 3) >>> g.add_edge(3, 3) - >>> visited = [False] * len(g.vertex) + >>> visited = {v: False for v in g.vertex} >>> g.dfs_recursive(0, visited) 0 1 2 3 """ @@ -103,10 +101,10 @@ def dfs_recursive(self, start_vertex: int, visited: list) -> None: print(start_vertex, end="") # Recur for all the vertices that are adjacent to this node - for i in self.vertex: - if not visited[i]: + for neighbor in self.vertex[start_vertex]: + if not visited[neighbor]: print(" ", end="") - self.dfs_recursive(i, visited) + self.dfs_recursive(neighbor, visited) if __name__ == "__main__": diff --git a/hashes/enigma_machine.py b/hashes/enigma_machine.py index 0da8e4113de9..d51b0f443abc 100644 --- a/hashes/enigma_machine.py +++ b/hashes/enigma_machine.py @@ -46,7 +46,7 @@ def engine(input_character): try: token = int(input("Please set token:(must be only digits)\n")) break - except Exception as error: + except ValueError as error: print(error) for _ in range(token): rotator() diff --git a/maths/area.py b/maths/area.py index e14cc0aa7195..5bccc74ee899 100644 --- a/maths/area.py +++ b/maths/area.py @@ -50,6 +50,10 @@ def surface_area_cuboid(length: float, breadth: float, height: float) -> float: Traceback (most recent call last): ... ValueError: surface_area_cuboid() only accepts non-negative values + >>> surface_area_cuboid(1, -1, 1) + Traceback (most recent call last): + ... + ValueError: surface_area_cuboid() only accepts non-negative values """ if length < 0 or breadth < 0 or height < 0: raise ValueError("surface_area_cuboid() only accepts non-negative values") @@ -539,14 +543,34 @@ def area_reg_polygon(sides: int, length: float) -> float: Traceback (most recent call last): ... ValueError: area_reg_polygon() only accepts integers greater than or equal to \ +three as number of sides + >>> area_reg_polygon(True, 5) + Traceback (most recent call last): + ... + ValueError: area_reg_polygon() only accepts integers greater than or equal to \ +three as number of sides + >>> area_reg_polygon(3.0, 5) + Traceback (most recent call last): + ... + ValueError: area_reg_polygon() only accepts integers greater than or equal to \ three as number of sides """ - if not isinstance(sides, int) or sides < 3: + # bool is a subclass of int in Python, so we must reject it explicitly. + # Without this, area_reg_polygon(True, 5) would silently pass the + # isinstance(sides, int) check (because True IS an int) and compute + # cot(pi/1) for a "1-sided regular polygon", which is geometrically + # meaningless but mathematically defined. A count of polygon sides + # should never be a bool. + if ( + not isinstance(sides, int) + or isinstance(sides, bool) + or sides < 3 + ): raise ValueError( "area_reg_polygon() only accepts integers greater than or \ equal to three as number of sides" ) - elif length < 0: + if length < 0: raise ValueError( "area_reg_polygon() only accepts non-negative values as \ length of a side" diff --git a/physics/newtons_second_law_of_motion.py b/physics/newtons_second_law_of_motion.py index 4149e2494f31..58e18dffcdd0 100644 --- a/physics/newtons_second_law_of_motion.py +++ b/physics/newtons_second_law_of_motion.py @@ -70,11 +70,13 @@ def newtons_second_law_of_motion(mass: float, acceleration: float) -> float: 100 >>> newtons_second_law_of_motion(2.0, 1) 2.0 + >>> newtons_second_law_of_motion(None, 10) + -0.0 """ force = 0.0 try: force = mass * acceleration - except Exception: + except TypeError: return -0.0 return force diff --git a/project_euler/problem_002/sol4.py b/project_euler/problem_002/sol4.py index 3341aa1d4569..a13d34fd760e 100644 --- a/project_euler/problem_002/sol4.py +++ b/project_euler/problem_002/sol4.py @@ -56,7 +56,7 @@ def solution(n: int = 4000000) -> int: try: n = int(n) - except TypeError, ValueError: + except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") diff --git a/project_euler/problem_003/sol1.py b/project_euler/problem_003/sol1.py index dbf9a84f68bb..d1c0e61cf1a6 100644 --- a/project_euler/problem_003/sol1.py +++ b/project_euler/problem_003/sol1.py @@ -80,7 +80,7 @@ def solution(n: int = 600851475143) -> int: try: n = int(n) - except TypeError, ValueError: + except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") diff --git a/project_euler/problem_003/sol2.py b/project_euler/problem_003/sol2.py index 4c4f88220514..0af0daceed06 100644 --- a/project_euler/problem_003/sol2.py +++ b/project_euler/problem_003/sol2.py @@ -44,7 +44,7 @@ def solution(n: int = 600851475143) -> int: try: n = int(n) - except TypeError, ValueError: + except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") diff --git a/project_euler/problem_003/sol3.py b/project_euler/problem_003/sol3.py index 1a454b618f75..e13a0eb74ec1 100644 --- a/project_euler/problem_003/sol3.py +++ b/project_euler/problem_003/sol3.py @@ -44,7 +44,7 @@ def solution(n: int = 600851475143) -> int: try: n = int(n) - except TypeError, ValueError: + except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") diff --git a/project_euler/problem_005/sol1.py b/project_euler/problem_005/sol1.py index f889c420c61d..01cbd0e15ff7 100644 --- a/project_euler/problem_005/sol1.py +++ b/project_euler/problem_005/sol1.py @@ -47,7 +47,7 @@ def solution(n: int = 20) -> int: try: n = int(n) - except TypeError, ValueError: + except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") diff --git a/project_euler/problem_007/sol2.py b/project_euler/problem_007/sol2.py index d63b2f2d86ec..fd99453c1100 100644 --- a/project_euler/problem_007/sol2.py +++ b/project_euler/problem_007/sol2.py @@ -87,7 +87,7 @@ def solution(nth: int = 10001) -> int: try: nth = int(nth) - except TypeError, ValueError: + except (TypeError, ValueError): raise TypeError("Parameter nth must be int or castable to int.") from None if nth <= 0: raise ValueError("Parameter nth must be greater than or equal to one.") diff --git a/project_euler/problem_099/sol1.py b/project_euler/problem_099/sol1.py index bf5621c6583c..edde788562b2 100644 --- a/project_euler/problem_099/sol1.py +++ b/project_euler/problem_099/sol1.py @@ -24,11 +24,12 @@ def solution(data_file: str = "base_exp.txt") -> int: """ largest: float = 0 result = 0 - for i, line in enumerate(open(os.path.join(os.path.dirname(__file__), data_file))): - a, x = list(map(int, line.split(","))) - if x * log10(a) > largest: - largest = x * log10(a) - result = i + 1 + with open(os.path.join(os.path.dirname(__file__), data_file)) as file: + for i, line in enumerate(file): + a, x = list(map(int, line.split(","))) + if x * log10(a) > largest: + largest = x * log10(a) + result = i + 1 return result diff --git a/web_programming/fetch_well_rx_price.py b/web_programming/fetch_well_rx_price.py index 680d7444bd1c..e34a89c19cc8 100644 --- a/web_programming/fetch_well_rx_price.py +++ b/web_programming/fetch_well_rx_price.py @@ -67,7 +67,7 @@ def fetch_pharmacy_and_price_list(drug_name: str, zip_code: str) -> list | None: return pharmacy_price_list - except httpx.HTTPError, ValueError: + except (httpx.HTTPError, ValueError): return None diff --git a/web_programming/instagram_crawler.py b/web_programming/instagram_crawler.py index 0b91db01ca09..68271c1c4643 100644 --- a/web_programming/instagram_crawler.py +++ b/web_programming/instagram_crawler.py @@ -53,7 +53,7 @@ def get_json(self) -> dict: scripts = BeautifulSoup(html, "html.parser").find_all("script") try: return extract_user_profile(scripts[4]) - except json.decoder.JSONDecodeError, KeyError: + except (json.decoder.JSONDecodeError, KeyError): return extract_user_profile(scripts[3]) def __repr__(self) -> str: