Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion digital_image_processing/convert_to_negative.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
2 changes: 1 addition & 1 deletion divide_and_conquer/convex_hull.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand Down
2 changes: 1 addition & 1 deletion dynamic_programming/catalan_numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 9 additions & 11 deletions graphs/depth_first_search_2.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,12 @@
0 1 2 3
"""
# visited array for storing already visited nodes
visited = [False] * len(self.vertex)
visited = {v: False for v in self.vertex}

Check failure on line 74 in graphs/depth_first_search_2.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (C420)

graphs/depth_first_search_2.py:74:19: C420 Unnecessary dict comprehension for iterable; use `dict.fromkeys` instead help: Replace with `dict.fromkeys(iterable)`)
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.

Expand All @@ -93,7 +91,7 @@
>>> 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
"""
Expand All @@ -103,10 +101,10 @@
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__":
Expand Down
2 changes: 1 addition & 1 deletion hashes/enigma_machine.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
28 changes: 26 additions & 2 deletions maths/area.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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"
Expand Down
4 changes: 3 additions & 1 deletion physics/newtons_second_law_of_motion.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion project_euler/problem_002/sol4.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Expand Down
2 changes: 1 addition & 1 deletion project_euler/problem_003/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Expand Down
2 changes: 1 addition & 1 deletion project_euler/problem_003/sol2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Expand Down
2 changes: 1 addition & 1 deletion project_euler/problem_003/sol3.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Expand Down
2 changes: 1 addition & 1 deletion project_euler/problem_005/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Expand Down
2 changes: 1 addition & 1 deletion project_euler/problem_007/sol2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Expand Down
11 changes: 6 additions & 5 deletions project_euler/problem_099/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
2 changes: 1 addition & 1 deletion web_programming/fetch_well_rx_price.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
2 changes: 1 addition & 1 deletion web_programming/instagram_crawler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading