Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

[pull] master from TheAlgorithms:master #73

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Dec 30, 2024
Merged
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
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@
* [Prefix Conversions](conversions/prefix_conversions.py)
* [Prefix Conversions String](conversions/prefix_conversions_string.py)
* [Pressure Conversions](conversions/pressure_conversions.py)
* [Rectangular To Polar](conversions/rectangular_to_polar.py)
* [Rgb Cmyk Conversion](conversions/rgb_cmyk_conversion.py)
* [Rgb Hsv Conversion](conversions/rgb_hsv_conversion.py)
* [Roman Numerals](conversions/roman_numerals.py)
Expand Down
62 changes: 62 additions & 0 deletions computer_vision/intensity_based_segmentation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Source: "https://www.ijcse.com/docs/IJCSE11-02-03-117.pdf"

# Importing necessary libraries
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image


def segment_image(image: np.ndarray, thresholds: list[int]) -> np.ndarray:
"""
Performs image segmentation based on intensity thresholds.

Args:
image: Input grayscale image as a 2D array.
thresholds: Intensity thresholds to define segments.

Returns:
A labeled 2D array where each region corresponds to a threshold range.

Example:
>>> img = np.array([[80, 120, 180], [40, 90, 150], [20, 60, 100]])
>>> segment_image(img, [50, 100, 150])
array([[1, 2, 3],
[0, 1, 2],
[0, 1, 1]], dtype=int32)
"""
# Initialize segmented array with zeros
segmented = np.zeros_like(image, dtype=np.int32)

# Assign labels based on thresholds
for i, threshold in enumerate(thresholds):
segmented[image > threshold] = i + 1

return segmented


if __name__ == "__main__":
# Load the image
image_path = "path_to_image" # Replace with your image path
original_image = Image.open(image_path).convert("L")
image_array = np.array(original_image)

# Define thresholds
thresholds = [50, 100, 150, 200]

# Perform segmentation
segmented_image = segment_image(image_array, thresholds)

# Display the results
plt.figure(figsize=(10, 5))

plt.subplot(1, 2, 1)
plt.title("Original Image")
plt.imshow(image_array, cmap="gray")
plt.axis("off")

plt.subplot(1, 2, 2)
plt.title("Segmented Image")
plt.imshow(segmented_image, cmap="tab20")
plt.axis("off")

plt.show()
32 changes: 32 additions & 0 deletions conversions/rectangular_to_polar.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import math


def rectangular_to_polar(real: float, img: float) -> tuple[float, float]:
"""
https://en.wikipedia.org/wiki/Polar_coordinate_system

>>> rectangular_to_polar(5,-5)
(7.07, -45.0)
>>> rectangular_to_polar(-1,1)
(1.41, 135.0)
>>> rectangular_to_polar(-1,-1)
(1.41, -135.0)
>>> rectangular_to_polar(1e-10,1e-10)
(0.0, 45.0)
>>> rectangular_to_polar(-1e-10,1e-10)
(0.0, 135.0)
>>> rectangular_to_polar(9.75,5.93)
(11.41, 31.31)
>>> rectangular_to_polar(10000,99999)
(100497.76, 84.29)
"""

mod = round(math.sqrt((real**2) + (img**2)), 2)
ang = round(math.degrees(math.atan2(img, real)), 2)
return (mod, ang)


if __name__ == "__main__":
import doctest

doctest.testmod()
5 changes: 3 additions & 2 deletions data_structures/arrays/sudoku_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def cross(items_a, items_b):
+ [cross(rs, cs) for rs in ("ABC", "DEF", "GHI") for cs in ("123", "456", "789")]
)
units = {s: [u for u in unitlist if s in u] for s in squares}
peers = {s: set(sum(units[s], [])) - {s} for s in squares} # noqa: RUF017
peers = {s: {x for u in units[s] for x in u} - {s} for s in squares}


def test():
Expand Down Expand Up @@ -172,7 +172,8 @@ def unitsolved(unit):

def from_file(filename, sep="\n"):
"Parse a file into a list of strings, separated by sep."
return open(filename).read().strip().split(sep)
with open(filename) as file:
return file.read().strip().split(sep)


def random_puzzle(assignments=17):
Expand Down
7 changes: 4 additions & 3 deletions dynamic_programming/all_construct.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@

def all_construct(target: str, word_bank: list[str] | None = None) -> list[list[str]]:
"""
returns the list containing all the possible
combinations a string(target) can be constructed from
the given list of substrings(word_bank)
returns the list containing all the possible
combinations a string(`target`) can be constructed from
the given list of substrings(`word_bank`)

>>> all_construct("hello", ["he", "l", "o"])
[['he', 'l', 'l', 'o']]
>>> all_construct("purple",["purp","p","ur","le","purpl"])
Expand Down
23 changes: 12 additions & 11 deletions dynamic_programming/combination_sum_iv.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
"""
Question:
You are given an array of distinct integers and you have to tell how many
different ways of selecting the elements from the array are there such that
the sum of chosen elements is equal to the target number tar.
You are given an array of distinct integers and you have to tell how many
different ways of selecting the elements from the array are there such that
the sum of chosen elements is equal to the target number tar.

Example

Input:
N = 3
target = 5
array = [1, 2, 5]
* N = 3
* target = 5
* array = [1, 2, 5]

Output:
9
9

Approach:
The basic idea is to go over recursively to find the way such that the sum
of chosen elements is “tar”. For every element, we have two choices
1. Include the element in our set of chosen elements.
2. Don't include the element in our set of chosen elements.
The basic idea is to go over recursively to find the way such that the sum
of chosen elements is `target`. For every element, we have two choices

1. Include the element in our set of chosen elements.
2. Don't include the element in our set of chosen elements.
"""


Expand Down
11 changes: 6 additions & 5 deletions dynamic_programming/fizz_buzz.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@

def fizz_buzz(number: int, iterations: int) -> str:
"""
Plays FizzBuzz.
Prints Fizz if number is a multiple of 3.
Prints Buzz if its a multiple of 5.
Prints FizzBuzz if its a multiple of both 3 and 5 or 15.
Else Prints The Number Itself.
| Plays FizzBuzz.
| Prints Fizz if number is a multiple of ``3``.
| Prints Buzz if its a multiple of ``5``.
| Prints FizzBuzz if its a multiple of both ``3`` and ``5`` or ``15``.
| Else Prints The Number Itself.

>>> fizz_buzz(1,7)
'1 2 Fizz 4 Buzz Fizz 7 '
>>> fizz_buzz(1,0)
Expand Down
40 changes: 21 additions & 19 deletions dynamic_programming/knapsack.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def mf_knapsack(i, wt, val, j):
"""
This code involves the concept of memory functions. Here we solve the subproblems
which are needed unlike the below example
F is a 2D array with -1s filled up
F is a 2D array with ``-1`` s filled up
"""
global f # a global dp table for knapsack
if f[i][j] < 0:
Expand Down Expand Up @@ -45,22 +45,24 @@ def knapsack_with_example_solution(w: int, wt: list, val: list):
the several possible optimal subsets.

Parameters
---------
----------

W: int, the total maximum weight for the given knapsack problem.
wt: list, the vector of weights for all items where wt[i] is the weight
of the i-th item.
val: list, the vector of values for all items where val[i] is the value
of the i-th item
* `w`: int, the total maximum weight for the given knapsack problem.
* `wt`: list, the vector of weights for all items where ``wt[i]`` is the weight
of the ``i``-th item.
* `val`: list, the vector of values for all items where ``val[i]`` is the value
of the ``i``-th item

Returns
-------
optimal_val: float, the optimal value for the given knapsack problem
example_optional_set: set, the indices of one of the optimal subsets
which gave rise to the optimal value.

* `optimal_val`: float, the optimal value for the given knapsack problem
* `example_optional_set`: set, the indices of one of the optimal subsets
which gave rise to the optimal value.

Examples
-------
--------

>>> knapsack_with_example_solution(10, [1, 3, 5, 2], [10, 20, 100, 22])
(142, {2, 3, 4})
>>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4, 4])
Expand Down Expand Up @@ -104,19 +106,19 @@ def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set):
a filled DP table and the vector of weights

Parameters
---------

dp: list of list, the table of a solved integer weight dynamic programming problem
----------

wt: list or tuple, the vector of weights of the items
i: int, the index of the item under consideration
j: int, the current possible maximum weight
optimal_set: set, the optimal subset so far. This gets modified by the function.
* `dp`: list of list, the table of a solved integer weight dynamic programming
problem
* `wt`: list or tuple, the vector of weights of the items
* `i`: int, the index of the item under consideration
* `j`: int, the current possible maximum weight
* `optimal_set`: set, the optimal subset so far. This gets modified by the function.

Returns
-------
None

``None``
"""
# for the current item i at a maximum weight j to be part of an optimal subset,
# the optimal value at (i, j) must be greater than the optimal value at (i-1, j).
Expand Down
14 changes: 9 additions & 5 deletions dynamic_programming/longest_common_substring.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
"""
Longest Common Substring Problem Statement: Given two sequences, find the
longest common substring present in both of them. A substring is
necessarily continuous.
Example: "abcdef" and "xabded" have two longest common substrings, "ab" or "de".
Therefore, algorithm should return any one of them.
Longest Common Substring Problem Statement:
Given two sequences, find the
longest common substring present in both of them. A substring is
necessarily continuous.

Example:
``abcdef`` and ``xabded`` have two longest common substrings, ``ab`` or ``de``.
Therefore, algorithm should return any one of them.
"""


def longest_common_substring(text1: str, text2: str) -> str:
"""
Finds the longest common substring between two strings.

>>> longest_common_substring("", "")
''
>>> longest_common_substring("a","")
Expand Down
13 changes: 8 additions & 5 deletions dynamic_programming/longest_increasing_subsequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
This is a pure Python implementation of Dynamic Programming solution to the longest
increasing subsequence of a given sequence.

The problem is :
Given an array, to find the longest and increasing sub-array in that given array and
return it.
Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return
[10, 22, 33, 41, 60, 80] as output
The problem is:
Given an array, to find the longest and increasing sub-array in that given array and
return it.

Example:
``[10, 22, 9, 33, 21, 50, 41, 60, 80]`` as input will return
``[10, 22, 33, 41, 60, 80]`` as output
"""

from __future__ import annotations
Expand All @@ -17,6 +19,7 @@
def longest_subsequence(array: list[int]) -> list[int]: # This function is recursive
"""
Some examples

>>> longest_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80])
[10, 22, 33, 41, 60, 80]
>>> longest_subsequence([4, 8, 7, 5, 1, 12, 2, 3, 9])
Expand Down
Loading