Skip to content

Commit

Permalink
Merge pull request #368 from yashksaini-coder/fix-360
Browse files Browse the repository at this point in the history
✅ Revamped Searching code snippets seperately from sorting
  • Loading branch information
UTSAVS26 authored Nov 7, 2024
2 parents 1491cba + f341cac commit c8f3d9c
Show file tree
Hide file tree
Showing 24 changed files with 555 additions and 2,098 deletions.
92 changes: 0 additions & 92 deletions Tests/Searching/test_searching.py

This file was deleted.

36 changes: 18 additions & 18 deletions pysnippets/Mathematics/vector_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,31 @@
from typing import List

# Configure logging
logging.basicConfig(level=logging.DEBUG)

def vector_addition(v1: List[float], v2: List[float]) -> List[float]:
"""
Add two vectors v1 and v2.
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(levelname)s - %(message)s"
)

def vector_addition(vec1: List[int], vec2: List[int]) -> List[int]:
"""Add two vectors element-wise.
Args:
v1 (list of float): First vector.
v2 (list of float): Second vector.
vec1 (List[int]): The first vector.
vec2 (List[int]): The second vector.
Returns:
list of float: The resulting vector after addition.
Raises:
ValueError: If the dimensions of the two vectors are not the same.
List[int]: The resultant vector after addition.
"""
if len(v1) != len(v2):
raise ValueError("The dimensions of the two vectors must be the same.")

result = [v1[i] + v2[i] for i in range(len(v1))]
logging.debug(f"Added vectors {v1} and {v2} to get {result}")
if len(vec1) != len(vec2):
logging.error("Vectors must be of the same length.")
raise ValueError("Vectors must be of the same length.")

result = [a + b for a, b in zip(vec1, vec2)]
logging.debug(f"Vector addition result: {result}")
return result

# Additional vector operations with similar refactoring...

# Example usage
if __name__ == "__main__":
v1 = [1, 2, 3]
v2 = [4, 5, 6]
print("Vector Addition:", vector_addition(v1, v2))
print("Vector Addition:", vector_addition(v1, v2))
57 changes: 43 additions & 14 deletions pysnippets/Searching/Exponential_search.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,68 @@
def binary_search(arr, target, low, high):
import logging
from typing import List

logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(levelname)s - %(message)s"
)

def binary_search(arr: List[int], target: int, low: int, high: int) -> int:
"""Perform a binary search on a sorted array.
Args:
arr (List[int]): Sorted list of elements to search through.
target (int): The element to search for.
low (int): Lower index of the search range.
high (int): Higher index of the search range.
Returns:
int: The index of the target if found, else -1.
"""
logging.debug(f"Binary search called with low={low}, high={high}")
if high >= low:
mid = (high + low) // 2
logging.debug(f"Checking middle index {mid}")
if arr[mid] == target:
logging.info(f"Target {target} found at index {mid}")
return mid
elif arr[mid] > target:
return binary_search(arr, target, low, mid - 1)
else:
return binary_search(arr, target, mid + 1, high)
else:
return -1
logging.warning(f"Target {target} not found in the array.")
return -1

def exponential_search(arr, target):
"""
Exponential search algorithm.
:param arr: Sorted list of elements to search through.
:param target: The element to search for.
:return: The index of the element if found, else -1.
def exponential_search(arr: List[int], target: int) -> int:
"""Exponential search algorithm.
Args:
arr (List[int]): Sorted list of elements to search through.
target (int): The element to search for.
Returns:
int: The index of the target if found, else -1.
"""
if not arr: # Check for empty array
logging.info("Starting exponential search")
if not arr:
logging.error("Empty array provided for search.")
return -1
if arr[0] == target:
logging.info("Target found at index 0")
return 0
n = len(arr)
i = 1
while i < n and arr[i] <= target:
logging.debug(f"Exponential search checking index {i}")
i *= 2
result = binary_search(arr, target, i // 2, min(i, n - 1))
if result != -1:
logging.info(f"Element {target} found at index {result}")
else:
logging.info(f"Element {target} is not present in array")
return result

return binary_search(arr, target, i // 2, min(i, n - 1))

# Driver Code
if __name__ == "__main__":
arr = [2, 3, 4, 10, 40]
target = 10
result = exponential_search(arr, target)
if result == -1:
print("Element is not present in array")
logging.info("Element is not present in array")
else:
print("Element is present at index", result)
logging.info(f"Element is present at index {result}")
17 changes: 4 additions & 13 deletions pysnippets/Searching/Fibonacci_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,20 @@ def fibonacci_search(arr, target):
if not arr: # Check for empty array
return -1
n = len(arr)
fib_mm2 = 0 # (m-2)'th Fibonacci number
fib_mm1 = 1 # (m-1)'th Fibonacci number
fib_m = fib_mm2 + fib_mm1 # m'th Fibonacci number
fib_mm2, fib_mm1, fib_m = 0, 1, 1 # (m-2)'th, (m-1)'th, m'th Fibonacci numbers

while fib_m < n:
fib_mm2 = fib_mm1
fib_mm1 = fib_m
fib_m = fib_mm2 + fib_mm1
fib_mm2, fib_mm1, fib_m = fib_mm1, fib_m, fib_mm2 + fib_mm1

offset = -1

while fib_m > 1:
i = min(offset + fib_mm2, n - 1)

if arr[i] < target:
fib_m = fib_mm1
fib_mm1 = fib_mm2
fib_mm2 = fib_m - fib_mm1
offset = i
fib_m, fib_mm1, fib_mm2, offset = fib_mm1, fib_mm2, fib_m - fib_mm1, i
elif arr[i] > target:
fib_m = fib_mm2
fib_mm1 -= fib_mm2
fib_mm2 = fib_m - fib_mm1
fib_m, fib_mm1, fib_mm2 = fib_mm2, fib_mm1 - fib_mm2, fib_m - fib_mm1
else:
return i

Expand Down
36 changes: 25 additions & 11 deletions pysnippets/Searching/Interpolation.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,40 @@
def interpolation_search(arr, target):
"""
Interpolation search algorithm.
:param arr: Sorted list of elements to search through (with uniformly distributed values).
:param target: The element to search for.
:return: The index of the element if found, else -1.
import logging
from typing import List

logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(levelname)s - %(message)s"
)

def interpolation_search(arr: List[int], target: int) -> int:
"""Interpolation search algorithm.
Args:
arr (List[int]): Sorted list of elements to search through (with uniformly distributed values).
target (int): The element to search for.
Returns:
int: The index of the target if found, else -1.
"""
logging.info("Starting interpolation search")
low, high = 0, len(arr) - 1
while low <= high and arr[low] <= target <= arr[high]:
if low == high:
if arr[low] == target:
logging.info(f"Target {target} found at index {low}")
return low
logging.warning(f"Target {target} not found in array.")
return -1

pos = low + ((target - arr[low]) * (high - low) // (arr[high] - arr[low]))

logging.debug(f"Interpolated position: {pos}")
if arr[pos] == target:
logging.info(f"Target {target} found at index {pos}")
return pos
if arr[pos] < target:
low = pos + 1
logging.debug(f"Target greater than {arr[pos]}, new low={low}")
else:
high = pos - 1
logging.debug(f"Target less than {arr[pos]}, new high={high}")
logging.warning(f"Element {target} is not present in array")
return -1

# Driver Code
Expand All @@ -28,7 +43,6 @@ def interpolation_search(arr, target):
target = 10
result = interpolation_search(arr, target)
if result == -1:
print("Element is not present in array")
logging.info("Element is not present in array")
else:
print("Element is present at index", result)

logging.info(f"Element is present at index {result}")
36 changes: 23 additions & 13 deletions pysnippets/Searching/Jump_search.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,40 @@
import logging
import math
from typing import List

def jump_search(arr, target):
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")

def jump_search(arr: List[int], target: int) -> int:
"""
Jump search algorithm.
:param arr: Sorted list of elements to search through.
:param target: The element to search for.
:return: The index of the element if found, else -1.
Args:
arr (List[int]): Sorted list of elements to search through.
target (int): The element to search for.
Returns:
int: The index of the target if found, else -1.
"""
if not arr: # Check for empty array
logging.info("Starting jump search")
if not arr:
logging.error("Empty array provided for search.")
return -1
n = len(arr)
step = int(math.sqrt(n))
prev = 0

while arr[min(step, n) - 1] < target:
while prev < n and arr[min(step, n) - 1] < target:
logging.debug(f"Jumping from index {prev} to {step}")
prev = step
step += int(math.sqrt(n))
if prev >= n:
logging.warning(f"Element {target} is not present in array")
return -1

for i in range(prev, min(step, n)):
logging.debug(f"Checking index {i}, value={arr[i]}")
if arr[i] == target:
logging.info(f"Target {target} found at index {i}")
return i
logging.warning(f"Element {target} is not present in array")
return -1

# Driver Code
Expand All @@ -30,9 +43,6 @@ def jump_search(arr, target):
target = 10
result = jump_search(arr, target)
if result == -1:
print("Element is not present in array")
logging.info("Element is not present in array")
else:
print("Element is present at index", result)



logging.info(f"Element is present at index {result}")
Loading

0 comments on commit c8f3d9c

Please sign in to comment.