Hacktoberfest2023 - Feel free to create a new file, and do not hesitate to pull your code, the most important thing is that the file name here must match your nickname so that the file does not conflict with other people. If you have multiple project files just make a folder in your nickname and add those files there.
def swap(arr, index1 , index2):
  temp=arr[index1]
  arr[index1]=arr[index2]
  arr[index2]=temp


def pivot(arr, pivot_index , end_index):
  swap_index=pivot_index
  for i in range(pivot_index+1,end_index+1):
    if arr[i] < arr[pivot_index]:
      swap_index+=1
      swap(arr,swap_index,i)
  swap(arr,pivot_index,swap_index)
  return swap_index

def quick_sort(arr,left,right):
  if left < right:
    pivot_index=pivot(arr,left,right)
    quick_sort(arr,left,pivot_index)
    quick_sort(arr,pivot_index+1,right)
  return arr
  
arr=[1,2,6,87,9,45]
print(arr)

arr=quick_sort(arr,0,len(arr)-1)

print(arr)

007DSJ/quick_sort.py
JosephLahiru/Hacktoberfest2023-Python-Projects
def bubbleSort(arr):
	n = len(arr)
	swapped = False
	for i in range(n-1):
		for j in range(0, n-i-1):
			if arr[j] > arr[j + 1]:
				swapped = True
				arr[j], arr[j + 1] = arr[j + 1], arr[j]
		
		if not swapped:
			return
      
arr = [64, 34, 25, 12, 22, 11, 90]

bubbleSort(arr)

print("Sorted Array: ")
for i in range(len(arr)):
	print("% d" % arr[i], end=" ")

AlphaArchangel/bubblesort.py
JosephLahiru/Hacktoberfest2023-Python-Projects
def selectionSort(array, size):
     
    for s in range(size):
        min_idx = s
         
        for i in range(s + 1, size):
            
            if array[i] < array[min_idx]:
                min_idx = i

        (array[s], array[min_idx]) = (array[min_idx], array[s])
 
data = [ 7, 2, 1, 6 ]
size = len(data)
selectionSort(data, size)
 
print('Sorted Array in Ascending Order is :')
print(data)

CaptainPerera/SelectionSort.py
JosephLahiru/Hacktoberfest2023-Python-Projects
def radix_sort(arr):
    max_num = max(arr)
    exp = 1  

    while max_num // exp > 0:
        counting_sort(arr, exp)
        exp *= 10

def counting_sort(arr, exp):
    n = len(arr)
    output = [0] * n
    count = [0] * 10 

    for i in range(n):
        index = arr[i] // exp
        count[index % 10] += 1

    for i in range(1, 10):
        count[i] += count[i - 1]

    i = n - 1
    while i >= 0:
        index = arr[i] // exp
        output[count[index % 10] - 1] = arr[i]
        count[index % 10] -= 1
        i -= 1

    for i in range(n):
        arr[i] = output[i]

arr = [170, 45, 75, 90, 802, 24, 2, 66]
radix_sort(arr)
print("Sorted array:", arr)

KoshikaDul1999/radixSort.py
JosephLahiru/Hacktoberfest2023-Python-Projects
class Solution:
    def romanToInt(self, s: str) -> int:
        roman_values = {
            'I': 1,
            'V': 5,
            'X': 10,
            'L': 50,
            'C': 100,
            'D': 500,
            'M': 1000
        }

        total = 0
        prev_value = 0

        for char in s:
            current_value = roman_values[char]

            if current_value > prev_value:
                total += current_value - 2 * prev_value
            else:
                total += current_value

            prev_value = current_value

        return total

LeetCode Problems/12. Integer to Roman.py
JosephLahiru/Hacktoberfest2023-Python-Projects
"""Given an integer num, return the number of steps to reduce it to zero.

In one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.

https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/
"""

class Solution:
    def numberOfSteps(self, num: int) -> int:
        count = 0
        while num:
            if num % 2 == 0:
                num /= 2
            else:
                num -= 1
            count += 1
        
        return count
LeetCode Problems/1342. Number of Steps to Reduce a Number to Zero.py
JosephLahiru/Hacktoberfest2023-Python-Projects
"""Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).

Return the running sum of nums.

https://leetcode.com/problems/running-sum-of-1d-array/
"""

class Solution:
    def runningSum(self, nums: List[int]) -> List[int]:
        for i in range(1,len(nums)):
            nums[i]+=nums[i-1]
        return nums
LeetCode Problems/1480. Running Sum of 1d Array.py
JosephLahiru/Hacktoberfest2023-Python-Projects
# 2. Add Two Numbers
# https://leetcode.com/problems/add-two-numbers/
#  You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself.

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        dummy_head = ListNode(0)  # Create a dummy node to simplify code
        current = dummy_head
        carry = 0

        while l1 or l2:
            x = l1.val if l1 else 0
            y = l2.val if l2 else 0

            total = x + y + carry
            carry = total // 10  # Calculate the carry for the next step
            current.next = ListNode(total % 10)  # Create a new node for the sum
            current = current.next

            if l1:
                l1 = l1.next
            if l2:
                l2 = l2.next

        if carry > 0:
            current.next = ListNode(carry)  # If there's a carry left, create a new node

        return dummy_head.next  # Return the result linked list (skip the dummy node)

LeetCode Problems/2. Add Two Numbers.py
JosephLahiru/Hacktoberfest2023-Python-Projects
"""Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.

Each letter in magazine can only be used once in ransomNote.

https://leetcode.com/problems/ransom-note/
"""

from collections import Counter

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        # count number of each alphabet in string
        s1, s2 = Counter(ransomNote), Counter(magazine)
        # bitwise and operation to check if ransomeNote sring can be constructed using magazine string
        return s1 & s2 == s1
LeetCode Problems/383. Ransom Note.py
JosephLahiru/Hacktoberfest2023-Python-Projects
class Solution:
    def isPalindrome(self, x: int) -> bool:
        # Handle negative numbers and numbers ending with 0 (except 0 itself)
        if x < 0 or (x != 0 and x % 10 == 0):
            return False
        
        reversed_x = 0
        original_x = x
        
        # Reverse the integer
        while x > 0:
            digit = x % 10
            reversed_x = reversed_x * 10 + digit
            x = x // 10
        
        # Check if the reversed integer is the same as the original
        return original_x == reversed_x

LeetCode Problems/9. Palindrome Number.py
JosephLahiru/Hacktoberfest2023-Python-Projects
class Solution:
    def zigzagLevelOrder(self, root):
        res = []
        if root is None:
            return res
        LtoR = []
        RtoL = []
        LtoR.append(root)
        lefttorigh = False
        while LtoR or RtoL:
            temp = []
            if lefttorigh:
                while RtoL:
                    node = RtoL.pop()
                    temp.append(node.val)
                    if node.left:
                        LtoR.append(node.left)
                    if node.right:
                        LtoR.append(node.right)
                temp.reverse()
                res.append(temp)
                lefttorigh = False
            else:
                while LtoR:
                    node = LtoR.pop()
                    temp.append(node.val)
                    if node.right:
                        RtoL.append(node.right)
                    if node.left:
                        RtoL.append(node.left)
                res.append(temp)
                lefttorigh = True
        return res
LeetCode Problems/Binary Tree Zigzag Level Order Traversal.py
JosephLahiru/Hacktoberfest2023-Python-Projects
# Time:  O(m + n)
# Space: O(1)
#
# Implement wildcard pattern matching with support for '?' and '*'.
#
# '?' Matches any single character.
# '*' Matches any sequence of characters (including the empty sequence).
#
# The matching should cover the entire input string (not partial).
#
# The function prototype should be:
# bool isMatch(const char *s, const char *p)
#
# Some examples:
# isMatch("aa","a") -> false
# isMatch("aa","aa") -> true
# isMatch("aaa","aa") -> false
# isMatch("aa", "*") -> true
# isMatch("aa", "a*") -> true
# isMatch("ab", "?*") -> true
# isMatch("aab", "c*a*b") -> false

class Solution:
    # @param s, an input string
    # @param p, a pattern string
    # @return a boolean
    def isMatch(self, s, p):
        p_ptr, s_ptr, last_s_ptr, last_p_ptr = 0, 0, -1, -1
        while s_ptr < len(s):
            if p_ptr < len(p) and (s[s_ptr] == p[p_ptr] or p[p_ptr] == '?'):
                s_ptr += 1
                p_ptr += 1
            elif p_ptr < len(p) and p[p_ptr] == '*':
                p_ptr += 1
                last_s_ptr = s_ptr
                last_p_ptr = p_ptr
            elif last_p_ptr != -1:
                last_s_ptr += 1
                s_ptr = last_s_ptr
                p_ptr = last_p_ptr
            else:
                return False

        while p_ptr < len(p) and p[p_ptr] == '*':
            p_ptr += 1

        return p_ptr == len(p)

# dp with rolling window
# Time:  O(m * n)
# Space: O(m + n)
class Solution2:
    # @return a boolean
    def isMatch(self, s, p):
        k = 2
        result = [[False for j in xrange(len(p) + 1)] for i in xrange(k)]

        result[0][0] = True
        for i in xrange(1, len(p) + 1):
            if p[i-1] == '*':
                result[0][i] = result[0][i-1]
        for i in xrange(1,len(s) + 1):
            result[i % k][0] = False
            for j in xrange(1, len(p) + 1):
                if p[j-1] != '*':
                    result[i % k][j] = result[(i-1) % k][j-1] and (s[i-1] == p[j-1] or p[j-1] == '?')
                else:
                    result[i % k][j] = result[i % k][j-1] or result[(i-1) % k][j]

        return result[len(s) % k][len(p)]

# dp
# Time:  O(m * n)
# Space: O(m * n)
class Solution3:
    # @return a boolean
    def isMatch(self, s, p):
        result = [[False for j in xrange(len(p) + 1)] for i in xrange(len(s) + 1)]

        result[0][0] = True
        for i in xrange(1, len(p) + 1):
            if p[i-1] == '*':
                result[0][i] = result[0][i-1]
        for i in xrange(1,len(s) + 1):
            result[i][0] = False
            for j in xrange(1, len(p) + 1):
                if p[j-1] != '*':
                    result[i][j] = result[i-1][j-1] and (s[i-1] == p[j-1] or p[j-1] == '?')
                else:
                    result[i][j] = result[i][j-1] or result[i-1][j]

        return result[len(s)][len(p)]


# recursive, slowest, TLE
class Solution4:
    # @return a boolean
    def isMatch(self, s, p):
        if not p or not s:
            return not s and not p

        if p[0] != '*':
            if p[0] == s[0] or p[0] == '?':
                return self.isMatch(s[1:], p[1:])
            else:
                return False
        else:
            while len(s) > 0:
                if self.isMatch(s, p[1:]):
                    return True
                s = s[1:]
            return self.isMatch(s, p[1:])

if __name__ == "__main__":
    print Solution().isMatch("aaaabaaaab","a*b*b")
    print Solution().isMatch("aaaaaaaaaaaaab", "a*a*a*a*a*a*a*a*a*a*c")
    print Solution().isMatch("aa","a")
    print Solution().isMatch("aa","aa")
    print Solution().isMatch("aaa","aa")
    print Solution().isMatch("aa", "a*")
    print Solution().isMatch("aa", "?*")
    print Solution().isMatch("ab", "?*")
    print Solution().isMatch("aab", "c*a*b")

LeetCode Problems/Wildcard_Matching.py
JosephLahiru/Hacktoberfest2023-Python-Projects
def find_minimum(nums):
  low = 0
  high = len(nums) - 1
  while low < high:
    mid = (low + high) // 2
    if nums[mid] > nums[high]:
      low = mid + 1
    else:
      high = mid
  return nums[low]

LeetCode Problems/problem on LeetCode.py
JosephLahiru/Hacktoberfest2023-Python-Projects
class Graph:
    def __init__(self, vertices):
        self.Destination = vertices
        self.edges = []
        self.component = {}
    def add_edge(self, Source, Destination, weight):
        self.edges.append([Source, Destination, weight])
    def find_component(self, Source):
        if self.component[Source] == Source:
            return Source
        return self.find_component(self.component[Source])

    def set_component(self, Source):
        if self.component[Source] == Source:
            return
        else:
            for k in self.component.keys():
                self.component[k] = self.find_component(k)

    def union(self, component_size, Source, Destination):
        if component_size[Source] <= component_size[Destination]:
            self.component[Source] = Destination
            component_size[Destination] += component_size[Source]
            self.set_component(Source)

        elif component_size[Source] >= component_size[Destination]:
            self.component[Destination] = self.find_component(Source)
            component_size[Source] += component_size[Destination]
            self.set_component(Destination)

        print(self.component)

    def boruvka(self):
        component_size = []
        mst_weight = 0

        minimum_weight_edge = [-1] * self.Destination

        for node in range(self.Destination):
            self.component.update({node: node})
            component_size.append(1)

        num_of_components = self.Destination

        print("---------Forming MST------------")
        while num_of_components > 1:
            for i in range(len(self.edges)):

                Source = self.edges[i][0]
                Destination = self.edges[i][1]
                w = self.edges[i][2]

                Source_component = self.component[Source]
                Destination_component = self.component[Destination]

                if Source_component != Destination_component:
                    if minimum_weight_edge[Source_component] == -1 or \
                            minimum_weight_edge[Source_component][2] > w:
                        minimum_weight_edge[Source_component] = [Source, Destination, w]
                    if minimum_weight_edge[Destination_component] == -1 or \
                            minimum_weight_edge[Destination_component][2] > w:
                        minimum_weight_edge[Destination_component] = [Source, Destination, w]

            for node in range(self.Destination):
                if minimum_weight_edge[node] != -1:
                    Source = minimum_weight_edge[node][0]
                    Destination = minimum_weight_edge[node][1]
                    w = minimum_weight_edge[node][2]

                    Source_component = self.component[Source]
                    Destination_component = self.component[Destination]

                    if Source_component != Destination_component:
                        mst_weight += w
                        self.union(component_size, Source_component, Destination_component)
                        print("edge_Added [" + str(Source) + " - "
                              + str(Destination) + "]\n"
                              + "weight_Added: " + str(w) + "\n")
                        num_of_components -= 1

            minimum_weight_edge = [-1] * self.Destination
        print("-------------MAXMULLER---------------------")
        print("The minimum spanning tree is overall weighed is: " + str(mst_weight))

g = Graph(9)
g.add_edge(0, 1, 4)
g.add_edge(0, 6, 7)
g.add_edge(1, 6, 11)
g.add_edge(1, 7, 20)
g.add_edge(1, 2, 9)
g.add_edge(2, 3, 6)
g.add_edge(2, 4, 2)
g.add_edge(3, 4, 10)
g.add_edge(3, 5, 5)
g.add_edge(4, 5, 15)
g.add_edge(4, 7, 1)
g.add_edge(4, 8, 5)
g.add_edge(5, 8, 12)
g.add_edge(6, 7, 1)
g.add_edge(7, 8, 3)
g.boruvka()

#by: Max Muller
MMVonnSeek/Boruvka-s-Algorithm.py
JosephLahiru/Hacktoberfest2023-Python-Projects
class BPlusTree:
    def __init__(self, order):
        self.root = Node()
        self.order = order

    def search(self, key):
        return self.root.search(key)

    def insert(self, key, value):
        if self.root.is_full():
            new_root = Node()
            new_root.children.append(self.root)
            new_root.split_child(0)
            self.root = new_root
        self.root.insert(key, value)

class Node:
    def __init__(self, is_leaf=True):
        self.keys = []
        self.values = []
        self.children = []
        self.is_leaf = is_leaf

    def is_full(self):
        return len(self.keys) == 2 * tree.order - 1

    def split_child(self, i):
        new_node = Node(is_leaf=self.children[i].is_leaf)
        split_key = self.children[i].keys[tree.order - 1]

        self.keys.insert(i, split_key)
        self.values.insert(i, self.children[i].values[tree.order - 1])
        self.children.insert(i + 1, new_node)

        new_node.keys = self.children[i].keys[tree.order:]
        new_node.values = self.children[i].values[tree.order:]
        self.children[i].keys = self.children[i].keys[:tree.order - 1]
        self.children[i].values = self.children[i].values[:tree.order - 1]

    def insert(self, key, value):
        i = len(self.keys) - 1
        if self.is_leaf:
            self.keys.append(None)
            self.values.append(None)
            while i >= 0 and key < self.keys[i]:
                self.keys[i + 1] = self.keys[i]
                self.values[i + 1] = self.values[i]
                i -= 1
            self.keys[i + 1] = key
            self.values[i + 1] = value
        else:
            while i >= 0 and key < self.keys[i]:
                i -= 1
            i += 1
            if self.children[i].is_full():
                self.split_child(i)
                if key > self.keys[i]:
                    i += 1
            self.children[i].insert(key, value)

    def search(self, key):
        i = 0
        while i < len(self.keys) and key > self.keys[i]:
            i += 1
        if i < len(self.keys) and key == self.keys[i]:
            return self.values[i]
        elif self.is_leaf:
            return None
        else:
            return self.children[i].search(key)

if __name__ == "__main__":
    tree = BPlusTree(order=3)

    # Inserting values into the B+ tree
    tree.insert(10, "Value 10")
    tree.insert(20, "Value 20")
    tree.insert(5, "Value 5")

    # Searching for a value in the B+ tree
    result = tree.search(10)
    if result:
        print("Key 10 found with value:", result)
    else:
        print("Key 10 not found")

Niraj-Dilshan/bplus.py
JosephLahiru/Hacktoberfest2023-Python-Projects
a = input("Enter the first number")
b = input("Enter the second number");
ch=-1

while ch !=0:
  print("--Menu--");
  print("\n1.Sum \n2.Diff \n3>Prod \n4.Division")
  ch = input("Enter your choice :")

  if ch == 1:
    print("Sum = ", (a+b))
  elif ch==2:
    print("Diff = ", (a-b))
  elif ch==3:
    print("Product =", (a*b))
  elif ch==4:
    print("Quotient=",(a/b))
  elif ch==0:
    print("Exiting")
    break
  else:
    print("Wrong choice.Please try again!")
    continue

ParalallHimself/basic_calculator.py
JosephLahiru/Hacktoberfest2023-Python-Projects
def bubble_sort(arr):
    n = len(arr)

    for i in range(n):
        
        for j in range(0, n-i-1):
        
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]


my_list = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(my_list)

print("Sorted array:", my_list)

ParalallHimself/bubble_sort.py
JosephLahiru/Hacktoberfest2023-Python-Projects
def selection_sort(arr):
    n = len(arr)

  
    for i in range(n):
        min_index = i
        for j in range(i+1, n):
            if arr[j] < arr[min_index]:
                min_index = j

        arr[i], arr[min_index] = arr[min_index], arr[i]

my_list = [64, 25, 12, 22, 11]
selection_sort(my_list)

print("Sorted array:", my_list)

ParalallHimself/selection_sort.py
JosephLahiru/Hacktoberfest2023-Python-Projects
import dns.resolver

# Set the target domain and record type
target_domain = "thepythoncode.com"      #Example Wesite
record_types = ["A", "AAAA", "CNAME", "MX", "NS", "SOA", "TXT"]
# Create a DNS resolver
resolver = dns.resolver.Resolver()
for record_type in record_types:
    # Perform DNS lookup for the specified domain and record type
    try:
        answers = resolver.resolve(target_domain, record_type)
    except dns.resolver.NoAnswer:
        continue
    # Print the answers
    print(f"{record_type} records for {target_domain}:")
    for rdata in answers:
        print(f" {rdata}")
Python-Script/dns-resolve.py
JosephLahiru/Hacktoberfest2023-Python-Projects
def merge_sort(arr):
    if len(arr) <= 1:
        return arr

    # Split the array into two halves
    mid = len(arr) // 2
    left_half = arr[:mid]
    right_half = arr[mid:]

    # Recursive call to merge_sort for both halves
    left_half = merge_sort(left_half)
    right_half = merge_sort(right_half)

    # Merge the sorted halves
    return merge(left_half, right_half)

def merge(left, right):
    merged = []
    left_index, right_index = 0, 0

    # Compare elements from left and right subarrays and merge them in sorted order
    while left_index < len(left) and right_index < len(right):
        if left[left_index] < right[right_index]:
            merged.append(left[left_index])
            left_index += 1
        else:
            merged.append(right[right_index])
            right_index += 1

    # Add remaining elements from left and right subarrays
    merged.extend(left[left_index:])
    merged.extend(right[right_index:])
    return merged

# Example usage
if __name__ == "__main__":
    arr = [12, 11, 13, 5, 6, 7]
    sorted_arr = merge_sort(arr)
    print("Sorted array:", sorted_arr)

Sayak-Bhunia/Merge_sort.py
JosephLahiru/Hacktoberfest2023-Python-Projects
import cv2
import mediapipe as mp

mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_hands = mp.solutions.hands

cap = cv2.VideoCapture(0)
with mp_hands.Hands(
    model_complexity=0, min_detection_confidence=0.5,
    min_tracking_confidence=0.5
) as hands:
    while cap.isOpened():
        success, image = cap.read()
        if not success:
            print("Ignoring empty camera frame.")

            continue

        image.flags.writeable = False
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        results = hands.process(image)

        # Draw the hand annotations on the image.
        image.flags.writeable = True
        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
        if results.multi_hand_landmarks:
            for hand_landmarks in results.multi_hand_landmarks:
                mp_drawing.draw_landmarks(
                    image,
                    hand_landmarks,
                    mp_hands.HAND_CONNECTIONS,
                    mp_drawing_styles.get_default_hand_landmarks_style(),
                    mp_drawing_styles.get_default_hand_connections_style(),
                )
        # Flip the image horizontally
        cv2.imshow("MediaPipe Hands", cv2.flip(image, 1))
        if cv2.waitKey(5) & 0xFF == ord("q"):
            break
cap.release()

aaditya1612/HandDetector/main.py
JosephLahiru/Hacktoberfest2023-Python-Projects
#You can implement a basic stack in Python using a list. Here's a simple example of a stack:

class Stack:
    def __init__(self):
        self.items = []

    def is_empty(self):
        return len(self.items) == 0

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if not self.is_empty():
            return self.items.pop()
        else:
            raise IndexError("pop from an empty stack")

    def peek(self):
        if not self.is_empty():
            return self.items[-1]
        else:
            raise IndexError("peek from an empty stack")

    def size(self):
        return len(self.items)

# Example usage:
if __name__ == "__main__":
    stack = Stack()

    # Push elements onto the stack
    stack.push(1)
    stack.push(2)
    stack.push(3)

    # Print the stack
    print("Stack:", stack.items)

    # Pop elements from the stack
    popped_item = stack.pop()
    print("Popped item:", popped_item)

    # Peek at the top element
    top_item = stack.peek()
    print("Top item:", top_item)

    # Check the size of the stack
    stack_size = stack.size()
    print("Stack size:", stack_size)

#In this code, we define a Stack class that uses a list (self.items) to implement the stack operations:

#push(item): Adds an item to the top of the stack.
#pop(): Removes and returns the top item from the stack.
#peek(): Returns the top item from the stack without removing it.
#is_empty(): Checks if the stack is empty.
#size(): Returns the number of items in the stack.
#You can use this Stack class to create and manipulate stacks in your Python programs.

arpitajana1220/stack.py
JosephLahiru/Hacktoberfest2023-Python-Projects
def jump_sort(arr):
    n = len(arr)
    jump = int(n**0.5)  # Jump distance

    # Perform jump sort
    for i in range(0, n, jump):
        # Find the insertion point for the current element
        key = arr[i]
        j = i - jump
        while j >= 0 and arr[j] > key:
            arr[j + jump] = arr[j]
            j -= jump
        arr[j + jump] = key

    # Perform final insertion sort on the sorted blocks
    for i in range(jump, n):
        key = arr[i]
        j = i - jump
        while j >= 0 and arr[j] > key:
            arr[j + jump] = arr[j]
            j -= jump
        arr[j + jump] = key

    return arr


# Example usage
arr = [29, 10, 14, 37, 13]
print("Original array:", arr)
sorted_arr = jump_sort(arr)
print("Sorted array:", sorted_arr)






bstrachn/jumpsort.py
JosephLahiru/Hacktoberfest2023-Python-Projects
# Small script that sorts files into folders if there are more then 1 file with similar name.
import os
import PySimpleGUI as sg
import shutil
log_entries = ""
window = sg.Window(title="Sorter", layout=[[sg.Text('Choose folder to sort')], [sg.In(size=(40,1), enable_events=True, key='-FOLDER-'), sg.FolderBrowse()], [sg.Button('OK')], [sg.Text(log_entries, key='-logtext-')]], margins=(100, 50))
while True:
    event, values = window.read()
    if event == "Exit" or event == sg.WIN_CLOSED:
        break
    elif event == 'OK':
        folder = values["-FOLDER-"]
        print(folder)
        try:
            file_list = os.listdir(folder)
        except:
            file_list = []
        for dirn in file_list:
            if os.path.isdir(folder+"/"+dirn):
                for i in file_list:
                    print
                    if dirn in i and os.path.isfile(folder+"/"+i):
                        if os.path.exists(folder+"/"+dirn+"/"+i):
                            log_entries = log_entries +"\n"+ folder+"/"+dirn+"/"+i+" already exists"
                        else:
                            shutil.move(folder+"/"+i, folder+"/"+dirn+"/")
                            log_entries = log_entries +"\n"+"moved "+i+" to "+ folder+"/"+dirn+"/"
        print(log_entries)
        if log_entries != "":
            with open(folder+"/log_script.txt", 'a') as f:
                f.write(log_entries)
            window.Element('-logtext-').Update("Done. Log written to file "+folder+"/log_script.txt")
        else:
            with open(folder+"/log_script.txt", 'a') as f:
                f.write("\n"+"No similarities found ")
            window.Element('-logtext-').Update("No similar filenames found, folder untouched ")
    log_entries = ""             

dimonalik/sorter.py
JosephLahiru/Hacktoberfest2023-Python-Projects
#fromkeys(key,val): used to take keys and assign values from iterable

#creaing dict from list using fromkeys() method
list1 = [1,2,3,4,5]
my_dict  = dict.fromkeys(list1)
print("dict", my_dict)
#creating list using range()
print({}.fromkeys(range(1,7),10))

#--------------------------------------------------------------------
#setdefault(key, values):  using this method we can check if the value is present in the dictionary, if not it will add the value
my_dict.setdefault(6)
print(my_dict)

#--------------------------------------------------------------------
#update()
#concatenating 2 dict
d1 = {1:'one',2:'two',3:'three'}
d2 = {4:'four', 5:'five', 6:'six'}
print(d1.update(d2))
print(d1)


#adding list values in dict------------------------------------------
list1 = [7,'seven']
d1.update([list1])
print(d1)

#adding expressions using update command
print(d1)

#-----------------------------------------------------------------
#pop()-return value of the element to be deleted
dict_abc = {'a':'cat', 'b':'bat', 'c':'dog'}
print("dictionary before deleting ele: ",dict_abc)
#del---------------------------------------------------------------
del dict_abc['a']
#pop()-------------------------------------------------------------
dict_abc.pop('b')
print("after deleting element: ",dict_abc)

#clear()-used to delete all elements from a dictionary--------------
dict_abc.clear()
print("after deleting all elements from a dictionary", dict_abc)

# to delete the actual dictionary del keyword+dict_name is used------m
del dict_abc

itsRushikesh/dictmethods.py
JosephLahiru/Hacktoberfest2023-Python-Projects
def linear_search(arr, target):
    for i in range(len(arr)):
        if arr[i] == target:
            return i
    return -1


arr = [10, 20, 30, 40, 50]
target = 30

result = linear_search(arr, target)

if result != -1:
    print(f"Element {target} found at index {result}")
else:
    print(f"Element {target} not found in the array")

shehzan/LinearSearch.py
JosephLahiru/Hacktoberfest2023-Python-Projects
import requests
from bs4 import BeautifulSoup

def fetch_books_data():
    #replace https://www.examplebookswebsite.com with some website of your choice
    url = "https://www.examplebookswebsite.com"
    response = requests.get(url)

    if response.status_code == 200:
        soup = BeautifulSoup(response.content, 'html.parser')
        book_list = soup.find_all('div', class_='book-item')

        for book in book_list:
            title = book.find('h2', class_='book-title').text
            author = book.find('p', class_='book-author').text
            price = book.find('span', class_='book-price').text

            print(f"Title: {title}")
            print(f"Author: {author}")
            print(f"Price: {price}")
            print()

    else:
        print("Failed to fetch data. Status code:", response.status_code)

if __name__ == "__main__":
    fetch_books_data()
zeeshan/web-scraping.py
JosephLahiru/Hacktoberfest2023-Python-Projects