Skip to content

Commit

Permalink
Merge branch 'main' into fake-news-detect
Browse files Browse the repository at this point in the history
  • Loading branch information
Dharun235 authored Nov 6, 2024
2 parents 0ecc5f4 + f5231bf commit 5a5eb2f
Show file tree
Hide file tree
Showing 606 changed files with 630,578 additions and 53 deletions.
70 changes: 70 additions & 0 deletions .github/ISSUE_TEMPLATE/Custom.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
name: "⚙️ Custom Issue"
description: "Submit a custom issue or suggestion for PyVerse."
title: "[Custom]: <Brief description of the issue>"
labels: ["custom", "status: needs triage"]
body:
- type: markdown
attributes:
value: |
Thank you for submitting a custom issue for **PyVerse**! This template is intended for any requests or suggestions that don't fit into the bug report, feature request, or documentation categories.
- type: input
id: issue_summary
attributes:
label: "Issue Summary"
description: "Provide a summary of the custom issue."
placeholder: "E.g., Enhancement suggestion for search functionality"
validations:
required: true

- type: textarea
id: issue_description
attributes:
label: "Issue Description"
description: "Describe the issue or suggestion in detail."
placeholder: "Provide a detailed description of the custom issue, including the context, use case, or scenario in which this issue occurs or would be relevant..."
validations:
required: true

- type: textarea
id: proposed_solution
attributes:
label: "Proposed Solution (Optional)"
description: "If you have any ideas or suggestions for how to address this issue, describe them here."
placeholder: "Describe your proposed solution or approach..."

- type: dropdown
id: priority
attributes:
label: "Priority"
description: "How important is this issue to you?"
options:
- "High - Requires urgent attention"
- "Medium - Should be addressed soon"
- "Low - Can be addressed later"
validations:
required: true

- type: checkboxes
id: category
attributes:
label: "Category"
description: "Select the category that best describes the issue."
options:
- label: "Enhancement"
- label: "Refactor"
- label: "Security"
- label: "Design"
- label: "Other"

- type: textarea
id: additional_context
attributes:
label: "Additional Context (Optional)"
description: "Add any other context or information that might be relevant to this issue."
placeholder: "Provide any extra details, screenshots, or references that could help with understanding the issue..."

- type: markdown
attributes:
value: |
**Thank you for your suggestion!** We appreciate your input and will review your custom issue promptly. 📝
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ share/
pyvenv.cfg
__pycache__\

# API Key for PDF-Analyzer
/Generative-AI/PDF-Analyzer/config.py

# Name of my Virtual environment
aiml

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,26 @@ The **N-Queens Problem** is a classic puzzle where the goal is to place \(N\) qu

- **Use Case**: Resource allocation and optimization problems, where multiple entities must be placed in non-conflicting positions (e.g., server load balancing).

### 6. **Rat in a Maze**

The **Rat in a Maze** problem involves finding a path for a rat from the source to the destination in a maze represented by a binary matrix.

- **Backtracking Approach**: Start from the source and explore possible moves (usually up, down, left, right). If a move leads to a valid path, continue; otherwise, backtrack and try another direction.

- **Time Complexity**: \(O(4^{n^2})\) in the worst case, where \(n\) is the size of the maze.

- **Use Case**: Pathfinding algorithms, robot navigation in constrained environments.

### 7. **Kth Permutation**

The **Kth Permutation** problem involves finding the kth permutation of a set of n numbers in lexicographic order.

- **Backtracking Approach**: Generate permutations in lexicographic order until the kth permutation is reached. Alternatively, use a more efficient factorial number system approach.

- **Time Complexity**: \(O(n!)\) for naive approach, \(O(n^2)\) for optimized factorial number system approach.

- **Use Case**: Combinatorial problems, generating specific arrangements in lexicographic order.

---

## Key Differences Between Backtracking Applications:
Expand All @@ -83,12 +103,14 @@ The **N-Queens Problem** is a classic puzzle where the goal is to place \(N\) qu
| **Knight's Tour** | \(O(8^n)\) | Chess puzzle solvers, Pathfinding |
| **Maze Solving** | \(O(4^n)\) | Robotics, Navigation Systems |
| **N-Queens** | \(O(N!)\) | Resource allocation, Server optimization |
| **Rat in a Maze** | \(O(4^{n^2})\) | Pathfinding, Robot navigation |
| **Kth Permutation** | \(O(n^2)\) | Combinatorial problems, Lexicographic ordering |

---

## Conclusion

**Backtracking** is a versatile and powerful technique for solving constraint-based problems. By exploring all possibilities and eliminating invalid paths through backtracking, this approach enables the efficient solving of complex combinatorial problems. Applications like **Graph Coloring**, **Hamiltonian Cycle**, **Knight's Tour**, **Maze Solving**, and the **N-Queens Problem** showcase the wide applicability of backtracking, from puzzle-solving to real-world optimization tasks.
**Backtracking** is a versatile and powerful technique for solving constraint-based problems. By exploring all possibilities and eliminating invalid paths through backtracking, this approach enables the efficient solving of complex combinatorial problems. Applications like **Graph Coloring**, **Hamiltonian Cycle**, **Knight's Tour**, **Maze Solving**,**N-Queens Problem** ,**Rat in a Maze** and **Kth Permutation** showcase the wide applicability of backtracking, from puzzle-solving to real-world optimization tasks.

Mastering backtracking is essential for understanding and solving a range of computational problems, making it a critical tool in algorithmic design.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
class Solution:
def getPermutation(self, n: int, k: int) -> str:
# Initialize the list of numbers from 1 to n
numbers = list(range(1, n + 1))
# Initialize the result string
result = []
# Decrement k by 1 to convert to 0-based index
k -= 1

def backtrack(nums, k, path):
if not nums:
# If no numbers left, we've found the kth permutation
return True

# Calculate the factorial of the remaining numbers
factorial = 1
for i in range(1, len(nums)):
factorial *= i

for i in range(len(nums)):
if k >= factorial:
# Skip this number, as it's not part of the kth permutation
k -= factorial
else:
# Add the current number to the path
path.append(str(nums[i]))
# Remove the used number from the list
nums.pop(i)
# Recursively build the rest of the permutation
if backtrack(nums, k, path):
return True
# If not successful, backtrack
nums.insert(i, int(path.pop()))

# Move to the next number
k %= factorial

return False

# Start the backtracking process
backtrack(numbers, k, result)

# Join the result list into a string and return
return ''.join(result)

# Example usage
if __name__ == "__main__":
solution = Solution()
n = 4
k = 9
print(f"The {k}th permutation of {n} numbers is: {solution.getPermutation(n, k)}")
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
def print_solution(solution):
"""
Print the solution matrix.
"""
for row in solution:
print(row)

def is_safe(maze, x, y):
"""
Check if the given position (x, y) is safe to move to.
Returns True if the position is within the maze and is not blocked.
"""
n = len(maze)
return 0 <= x < n and 0 <= y < n and maze[x][y] == 1

def solve_maze(maze):
"""
Main function to solve the maze using backtracking.
Returns the solution matrix if a path is found, otherwise returns None.
"""
n = len(maze)
# Create a solution matrix initialized with zeros
solution = [[0 for _ in range(n)] for _ in range(n)]

if solve_maze_util(maze, 0, 0, solution):
return solution
else:
print("No solution exists.")
return None

def solve_maze_util(maze, x, y, solution):
"""
Recursive utility function to solve the maze.
"""
n = len(maze)

# Base case: if we've reached the destination
if x == n - 1 and y == n - 1 and maze[x][y] == 1:
solution[x][y] = 1
return True

# Check if the current position is safe to move
if is_safe(maze, x, y):
# Mark the current cell as part of the solution path
solution[x][y] = 1

# Move forward in x direction
if solve_maze_util(maze, x + 1, y, solution):
return True

# If moving in x direction doesn't work, move down in y direction
if solve_maze_util(maze, x, y + 1, solution):
return True

# If none of the above movements work, backtrack
solution[x][y] = 0
return False

return False

# Example usage
if __name__ == "__main__":
# 1 represents open path, 0 represents blocked path
maze = [
[1, 0, 0, 0],
[1, 1, 0, 1],
[0, 1, 0, 0],
[1, 1, 1, 1]
]

solution = solve_maze(maze)

if solution:
print("Solution found:")
print_solution(solution)
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Python code to perform 2x2 matrix multiplication using Strassen's method
import numpy as np

def main():
x = np.zeros((2, 2), dtype=int)
y = np.zeros((2, 2), dtype=int)
z = np.zeros((2, 2), dtype=int)

print("Enter the elements of the first matrix (2x2):")
for i in range(2):
for j in range(2):
x[i][j] = int(input())

print("Enter the elements of the second matrix (2x2):")
for i in range(2):
for j in range(2):
y[i][j] = int(input())

print("\nThe first matrix is:")
for i in range(2):
for j in range(2):
print(f"{x[i][j]}\t", end="")
print()

print("\nThe second matrix is:")
for i in range(2):
for j in range(2):
print(f"{y[i][j]}\t", end="")
print()

m1 = (x[0][0] + x[1][1]) * (y[0][0] + y[1][1])
m2 = (x[1][0] + x[1][1]) * y[0][0]
m3 = x[0][0] * (y[0][1] - y[1][1])
m4 = x[1][1] * (y[1][0] - y[0][0])
m5 = (x[0][0] + x[0][1]) * y[1][1]
m6 = (x[1][0] - x[0][0]) * (y[0][0] + y[0][1])
m7 = (x[0][1] - x[1][1]) * (y[1][0] + y[1][1])

z[0][0] = m1 + m4 - m5 + m7
z[0][1] = m3 + m5
z[1][0] = m2 + m4
z[1][1] = m1 - m2 + m3 + m6

print("\nResultant matrix:")
for i in range(2):
for j in range(2):
print(f"{z[i][j]}\t", end="")
print()

if __name__ == "__main__":
main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""
Problem: You are tasked with painting houses. Each house can be painted in one of k colors,
and no two adjacent houses can have the same color. Find the minimum cost to paint all houses.
"""
def paint_house(costs):
if not costs:
return 0

n = len(costs)
k = len(costs[0])
dp = costs[0][:]

for i in range(1, n):
prev_dp = dp[:]
for j in range(k):
dp[j] = costs[i][j] + min(prev_dp[m] for m in range(k) if m != j)

return min(dp)

# Example usage
costs = [[17, 2, 17], [16, 16, 5], [14, 3, 19]]
print(f"Minimum cost to paint all houses: {paint_house(costs)}") # Output: Minimum cost to paint all houses: 10
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Problem: Given a set of integers, find if there is a subset with sum equal to a given number.


def subset_sum(nums, target):
dp = [False] * (target + 1)
dp[0] = True

for num in nums:
for i in range(target, num - 1, -1):
dp[i] = dp[i] or dp[i - num]

return dp[target]

# Example usage
nums = [3, 34, 4, 12, 5, 2]
target = 9
print(f"Is there a subset with sum {target}? {'Yes' if subset_sum(nums, target) else 'No'}") # Output: Yes
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""
Problem: Similar to the Fibonacci sequence, the Tribonacci sequence is defined as:
dp[n] = dp[n-1] + dp[n-2] + dp[n-3].
Given n, find the N-th Tribonacci number.
"""

def tribonacci(n):
if n == 0:
return 0
elif n == 1 or n == 2:
return 1

dp = [0] * (n + 1)
dp[0], dp[1], dp[2] = 0, 1, 1

for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]

return dp[n]

# Example usage
n = 10
print(f"The {n}-th Tribonacci number is: {tribonacci(n)}") # Output: The 10-th Tribonacci number is: 149
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# 0/1 Knapsack Problem Solution

# Problem: Given n items with weight and value, find the maximum value you can carry in a knapsack of capacity W.

def knapsack(weights, values, W):
n = len(weights)
# Create a 2D array to store maximum values
dp = [[0] * (W + 1) for _ in range(n + 1)]

# Fill the dp array
for i in range(1, n + 1):
for w in range(W + 1):
if weights[i - 1] <= w:
# Maximize value for the current item
dp[i][w] = max(dp[i - 1][w], values[i - 1] + dp[i - 1][w - weights[i - 1]])
else:
dp[i][w] = dp[i - 1][w]

return dp[n][W]

# Example usage
weights = [1, 2, 3]
values = [10, 20, 30]
W = 5
print(f"Maximum value in Knapsack: {knapsack(weights, values, W)}") # Output: Maximum value in Knapsack: 50
Loading

0 comments on commit 5a5eb2f

Please sign in to comment.