Compare commits

...

7 Commits

Author SHA1 Message Date
Julien Richard
9359e55087
Merge aa5a8858ea into fcf82a1eda 2024-10-05 10:38:38 -07:00
Vineet Kumar
fcf82a1eda
Implemented Exponential Search with binary search for improved perfor… (#11666)
* Implemented Exponential Search with binary search for improved performance on large sorted arrays.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Added type hints and doctests for binary_search and exponential_search functions. Improved code documentation and ensured testability.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update and rename Exponential_Search.py to exponential_search.py

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2024-10-05 10:34:48 -07:00
Andrey Ivanov
ad6395d340
Update ruff usage example in CONTRIBUTING.md (#11772)
* Update ruff usage example

* Update CONTRIBUTING.md

Co-authored-by: Tianyi Zheng <tianyizheng02@gmail.com>

---------

Co-authored-by: Tianyi Zheng <tianyizheng02@gmail.com>
2024-10-05 10:24:58 -07:00
Jeel Rupapara
50aca04c67
feat: increase test coverage of longest_common_subsequence to 75% (#11777) 2024-10-05 10:21:43 -07:00
1227haran
5a8655d306
Added new algorithm to generate numbers in lexicographical order (#11674)
* Added algorithm to generate numbers in lexicographical order

* Removed the test cases

* Updated camelcase to snakecase

* Added doctest

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Added descriptive name for n

* Reduced the number of letters

* Updated the return type

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Updated import statement

* Updated return type to Iterator[int]

* removed parentheses

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2024-10-05 10:19:58 -07:00
Julien RICHARD
aa5a8858ea
fix: too much characters in line 2024-10-01 19:36:58 +02:00
Julien RICHARD
2e67da3a7b
chore: improve comments and add tests to trapezoidal rule 2024-10-01 19:28:17 +02:00
5 changed files with 238 additions and 13 deletions

View File

@ -96,7 +96,7 @@ We want your work to be readable by others; therefore, we encourage you to note
```bash
python3 -m pip install ruff # only required the first time
ruff .
ruff check
```
- Original code submission require docstrings or comments to describe your work.

View File

@ -0,0 +1,38 @@
from collections.abc import Iterator
def lexical_order(max_number: int) -> Iterator[int]:
"""
Generate numbers in lexical order from 1 to max_number.
>>> " ".join(map(str, lexical_order(13)))
'1 10 11 12 13 2 3 4 5 6 7 8 9'
>>> list(lexical_order(1))
[1]
>>> " ".join(map(str, lexical_order(20)))
'1 10 11 12 13 14 15 16 17 18 19 2 20 3 4 5 6 7 8 9'
>>> " ".join(map(str, lexical_order(25)))
'1 10 11 12 13 14 15 16 17 18 19 2 20 21 22 23 24 25 3 4 5 6 7 8 9'
>>> list(lexical_order(12))
[1, 10, 11, 12, 2, 3, 4, 5, 6, 7, 8, 9]
"""
stack = [1]
while stack:
num = stack.pop()
if num > max_number:
continue
yield num
if (num % 10) != 9:
stack.append(num + 1)
stack.append(num * 10)
if __name__ == "__main__":
from doctest import testmod
testmod()
print(f"Numbers from 1 to 25 in lexical order: {list(lexical_order(26))}")

View File

@ -28,6 +28,24 @@ def longest_common_subsequence(x: str, y: str):
(2, 'ph')
>>> longest_common_subsequence("computer", "food")
(1, 'o')
>>> longest_common_subsequence("", "abc") # One string is empty
(0, '')
>>> longest_common_subsequence("abc", "") # Other string is empty
(0, '')
>>> longest_common_subsequence("", "") # Both strings are empty
(0, '')
>>> longest_common_subsequence("abc", "def") # No common subsequence
(0, '')
>>> longest_common_subsequence("abc", "abc") # Identical strings
(3, 'abc')
>>> longest_common_subsequence("a", "a") # Single character match
(1, 'a')
>>> longest_common_subsequence("a", "b") # Single character no match
(0, '')
>>> longest_common_subsequence("abcdef", "ace") # Interleaved subsequence
(3, 'ace')
>>> longest_common_subsequence("ABCD", "ACBD") # No repeated characters
(3, 'ABD')
"""
# find the length of strings

View File

@ -1,17 +1,35 @@
"""
Numerical integration or quadrature for a smooth function f with known values at x_i
This method is the classical approach of suming 'Equally Spaced Abscissas'
This method is the classical approach of summing 'Equally Spaced Abscissas'
method 1:
"extended trapezoidal rule"
Method 1:
"Extended Trapezoidal Rule"
"""
def method_1(boundary, steps):
# "extended trapezoidal rule"
# int(f) = dx/2 * (f1 + 2f2 + ... + fn)
"""
This function implements the extended trapezoidal rule for numerical integration.
The function f(x) is provided below.
:param boundary: List containing the lower and upper bounds of integration [a, b]
:param steps: The number of steps (intervals) used in the approximation
:return: The numerical approximation of the integral
>>> abs(method_1([0, 1], 10) - 0.33333) < 0.01
True
>>> abs(method_1([0, 1], 100) - 0.33333) < 0.01
True
>>> abs(method_1([0, 2], 1000) - 2.66667) < 0.01
True
>>> abs(method_1([1, 2], 1000) - 2.33333) < 0.01
True
"""
h = (boundary[1] - boundary[0]) / steps
a = boundary[0]
b = boundary[1]
@ -19,29 +37,67 @@ def method_1(boundary, steps):
y = 0.0
y += (h / 2.0) * f(a)
for i in x_i:
# print(i)
y += h * f(i)
y += (h / 2.0) * f(b)
return y
def make_points(a, b, h):
"""
Generates the points between a and b with spacing h for trapezoidal integration.
:param a: The lower bound of integration
:param b: The upper bound of integration
:param h: The step size
:yield: The next x-value in the range (a, b)
>>> list(make_points(0, 1, 0.1))
[0.1, 0.2, 0.30000000000000004, \
0.4, 0.5, 0.6, 0.7, \
0.7999999999999999, \
0.8999999999999999]
"""
x = a + h
while x < (b - h):
yield x
x = x + h
def f(x): # enter your function here
y = (x - 0) * (x - 0)
def f(x):
"""
This is the function to integrate, f(x) = (x - 0)^2 = x^2.
:param x: The input value
:return: The value of f(x)
>>> f(0)
0.0
>>> f(1)
1.0
>>> f(0.5)
0.25
"""
y = float((x - 0) * (x - 0))
return y
def main():
a = 0.0 # Lower bound of integration
b = 1.0 # Upper bound of integration
steps = 10.0 # define number of steps or resolution
boundary = [a, b] # define boundary of integration
"""
Main function to test the trapezoidal rule.
:a: Lower bound of integration
:b: Upper bound of integration
:steps: define number of steps or resolution
:boundary: define boundary of integration
>>> main()
y = 0.3349999999999999
"""
a = 0.0
b = 1.0
steps = 10.0
boundary = [a, b]
y = method_1(boundary, steps)
print(f"y = {y}")

View File

@ -0,0 +1,113 @@
#!/usr/bin/env python3
"""
Pure Python implementation of exponential search algorithm
For more information, see the Wikipedia page:
https://en.wikipedia.org/wiki/Exponential_search
For doctests run the following command:
python3 -m doctest -v exponential_search.py
For manual testing run:
python3 exponential_search.py
"""
from __future__ import annotations
def binary_search_by_recursion(
sorted_collection: list[int], item: int, left: int = 0, right: int = -1
) -> int:
"""Pure implementation of binary search algorithm in Python using recursion
Be careful: the collection must be ascending sorted otherwise, the result will be
unpredictable.
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item value to search
:param left: starting index for the search
:param right: ending index for the search
:return: index of the found item or -1 if the item is not found
Examples:
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 0, 0, 4)
0
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 15, 0, 4)
4
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 5, 0, 4)
1
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 6, 0, 4)
-1
"""
if right < 0:
right = len(sorted_collection) - 1
if list(sorted_collection) != sorted(sorted_collection):
raise ValueError("sorted_collection must be sorted in ascending order")
if right < left:
return -1
midpoint = left + (right - left) // 2
if sorted_collection[midpoint] == item:
return midpoint
elif sorted_collection[midpoint] > item:
return binary_search_by_recursion(sorted_collection, item, left, midpoint - 1)
else:
return binary_search_by_recursion(sorted_collection, item, midpoint + 1, right)
def exponential_search(sorted_collection: list[int], item: int) -> int:
"""
Pure implementation of an exponential search algorithm in Python.
For more information, refer to:
https://en.wikipedia.org/wiki/Exponential_search
Be careful: the collection must be ascending sorted, otherwise the result will be
unpredictable.
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item value to search
:return: index of the found item or -1 if the item is not found
The time complexity of this algorithm is O(log i) where i is the index of the item.
Examples:
>>> exponential_search([0, 5, 7, 10, 15], 0)
0
>>> exponential_search([0, 5, 7, 10, 15], 15)
4
>>> exponential_search([0, 5, 7, 10, 15], 5)
1
>>> exponential_search([0, 5, 7, 10, 15], 6)
-1
"""
if list(sorted_collection) != sorted(sorted_collection):
raise ValueError("sorted_collection must be sorted in ascending order")
if sorted_collection[0] == item:
return 0
bound = 1
while bound < len(sorted_collection) and sorted_collection[bound] < item:
bound *= 2
left = bound // 2
right = min(bound, len(sorted_collection) - 1)
return binary_search_by_recursion(sorted_collection, item, left, right)
if __name__ == "__main__":
import doctest
doctest.testmod()
# Manual testing
user_input = input("Enter numbers separated by commas: ").strip()
collection = sorted(int(item) for item in user_input.split(","))
target = int(input("Enter a number to search for: "))
result = exponential_search(sorted_collection=collection, item=target)
if result == -1:
print(f"{target} was not found in {collection}.")
else:
print(f"{target} was found at index {result} in {collection}.")