repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/scheduling/first_come_first_served.py
scheduling/first_come_first_served.py
# Implementation of First Come First Served scheduling algorithm # In this Algorithm we just care about the order that the processes arrived # without carring about their duration time # https://en.wikipedia.org/wiki/Scheduling_(computing)#First_come,_first_served from __future__ import annotations def calculate_waiting_times(duration_times: list[int]) -> list[int]: """ This function calculates the waiting time of some processes that have a specified duration time. Return: The waiting time for each process. >>> calculate_waiting_times([5, 10, 15]) [0, 5, 15] >>> calculate_waiting_times([1, 2, 3, 4, 5]) [0, 1, 3, 6, 10] >>> calculate_waiting_times([10, 3]) [0, 10] """ waiting_times = [0] * len(duration_times) for i in range(1, len(duration_times)): waiting_times[i] = duration_times[i - 1] + waiting_times[i - 1] return waiting_times def calculate_turnaround_times( duration_times: list[int], waiting_times: list[int] ) -> list[int]: """ This function calculates the turnaround time of some processes. Return: The time difference between the completion time and the arrival time. Practically waiting_time + duration_time >>> calculate_turnaround_times([5, 10, 15], [0, 5, 15]) [5, 15, 30] >>> calculate_turnaround_times([1, 2, 3, 4, 5], [0, 1, 3, 6, 10]) [1, 3, 6, 10, 15] >>> calculate_turnaround_times([10, 3], [0, 10]) [10, 13] """ return [ duration_time + waiting_times[i] for i, duration_time in enumerate(duration_times) ] def calculate_average_turnaround_time(turnaround_times: list[int]) -> float: """ This function calculates the average of the turnaround times Return: The average of the turnaround times. >>> calculate_average_turnaround_time([0, 5, 16]) 7.0 >>> calculate_average_turnaround_time([1, 5, 8, 12]) 6.5 >>> calculate_average_turnaround_time([10, 24]) 17.0 """ return sum(turnaround_times) / len(turnaround_times) def calculate_average_waiting_time(waiting_times: list[int]) -> float: """ This function calculates the average of the waiting times Return: The average of the waiting times. >>> calculate_average_waiting_time([0, 5, 16]) 7.0 >>> calculate_average_waiting_time([1, 5, 8, 12]) 6.5 >>> calculate_average_waiting_time([10, 24]) 17.0 """ return sum(waiting_times) / len(waiting_times) if __name__ == "__main__": # process id's processes = [1, 2, 3] # ensure that we actually have processes if len(processes) == 0: print("Zero amount of processes") raise SystemExit(0) # duration time of all processes duration_times = [19, 8, 9] # ensure we can match each id to a duration time if len(duration_times) != len(processes): print("Unable to match all id's with their duration time") raise SystemExit(0) # get the waiting times and the turnaround times waiting_times = calculate_waiting_times(duration_times) turnaround_times = calculate_turnaround_times(duration_times, waiting_times) # get the average times average_waiting_time = calculate_average_waiting_time(waiting_times) average_turnaround_time = calculate_average_turnaround_time(turnaround_times) # print all the results print("Process ID\tDuration Time\tWaiting Time\tTurnaround Time") for i, process in enumerate(processes): print( f"{process}\t\t{duration_times[i]}\t\t{waiting_times[i]}\t\t" f"{turnaround_times[i]}" ) print(f"Average waiting time = {average_waiting_time}") print(f"Average turn around time = {average_turnaround_time}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/scheduling/job_sequence_with_deadline.py
scheduling/job_sequence_with_deadline.py
""" Given a list of tasks, each with a deadline and reward, calculate which tasks can be completed to yield the maximum reward. Each task takes one unit of time to complete, and we can only work on one task at a time. Once a task has passed its deadline, it can no longer be scheduled. Example : tasks_info = [(4, 20), (1, 10), (1, 40), (1, 30)] max_tasks will return (2, [2, 0]) - Scheduling these tasks would result in a reward of 40 + 20 This problem can be solved using the concept of "GREEDY ALGORITHM". Time Complexity - O(n log n) https://medium.com/@nihardudhat2000/job-sequencing-with-deadline-17ddbb5890b5 """ from dataclasses import dataclass from operator import attrgetter @dataclass class Task: task_id: int deadline: int reward: int def max_tasks(tasks_info: list[tuple[int, int]]) -> list[int]: """ Create a list of Task objects that are sorted so the highest rewards come first. Return a list of those task ids that can be completed before i becomes too high. >>> max_tasks([(4, 20), (1, 10), (1, 40), (1, 30)]) [2, 0] >>> max_tasks([(1, 10), (2, 20), (3, 30), (2, 40)]) [3, 2] >>> max_tasks([(9, 10)]) [0] >>> max_tasks([(-9, 10)]) [] >>> max_tasks([]) [] >>> max_tasks([(0, 10), (0, 20), (0, 30), (0, 40)]) [] >>> max_tasks([(-1, 10), (-2, 20), (-3, 30), (-4, 40)]) [] """ tasks = sorted( ( Task(task_id, deadline, reward) for task_id, (deadline, reward) in enumerate(tasks_info) ), key=attrgetter("reward"), reverse=True, ) return [task.task_id for i, task in enumerate(tasks, start=1) if task.deadline >= i] if __name__ == "__main__": import doctest doctest.testmod() print(f"{max_tasks([(4, 20), (1, 10), (1, 40), (1, 30)]) = }") print(f"{max_tasks([(1, 10), (2, 20), (3, 30), (2, 40)]) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/scheduling/shortest_job_first.py
scheduling/shortest_job_first.py
""" Shortest job remaining first Please note arrival time and burst Please use spaces to separate times entered. """ from __future__ import annotations import pandas as pd def calculate_waitingtime( arrival_time: list[int], burst_time: list[int], no_of_processes: int ) -> list[int]: """ Calculate the waiting time of each processes Return: List of waiting times. >>> calculate_waitingtime([1,2,3,4],[3,3,5,1],4) [0, 3, 5, 0] >>> calculate_waitingtime([1,2,3],[2,5,1],3) [0, 2, 0] >>> calculate_waitingtime([2,3],[5,1],2) [1, 0] """ remaining_time = [0] * no_of_processes waiting_time = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(no_of_processes): remaining_time[i] = burst_time[i] complete = 0 increment_time = 0 minm = 999999999 short = 0 check = False # Process until all processes are completed while complete != no_of_processes: for j in range(no_of_processes): if ( arrival_time[j] <= increment_time and remaining_time[j] > 0 and remaining_time[j] < minm ): minm = remaining_time[j] short = j check = True if not check: increment_time += 1 continue remaining_time[short] -= 1 minm = remaining_time[short] if minm == 0: minm = 999999999 if remaining_time[short] == 0: complete += 1 check = False # Find finish time of current process finish_time = increment_time + 1 # Calculate waiting time finar = finish_time - arrival_time[short] waiting_time[short] = finar - burst_time[short] waiting_time[short] = max(waiting_time[short], 0) # Increment time increment_time += 1 return waiting_time def calculate_turnaroundtime( burst_time: list[int], no_of_processes: int, waiting_time: list[int] ) -> list[int]: """ Calculate the turn around time of each Processes Return: list of turn around times. >>> calculate_turnaroundtime([3,3,5,1], 4, [0,3,5,0]) [3, 6, 10, 1] >>> calculate_turnaroundtime([3,3], 2, [0,3]) [3, 6] >>> calculate_turnaroundtime([8,10,1], 3, [1,0,3]) [9, 10, 4] """ turn_around_time = [0] * no_of_processes for i in range(no_of_processes): turn_around_time[i] = burst_time[i] + waiting_time[i] return turn_around_time def calculate_average_times( waiting_time: list[int], turn_around_time: list[int], no_of_processes: int ) -> None: """ This function calculates the average of the waiting & turnaround times Prints: Average Waiting time & Average Turn Around Time >>> calculate_average_times([0,3,5,0],[3,6,10,1],4) Average waiting time = 2.00000 Average turn around time = 5.0 >>> calculate_average_times([2,3],[3,6],2) Average waiting time = 2.50000 Average turn around time = 4.5 >>> calculate_average_times([10,4,3],[2,7,6],3) Average waiting time = 5.66667 Average turn around time = 5.0 """ total_waiting_time = 0 total_turn_around_time = 0 for i in range(no_of_processes): total_waiting_time = total_waiting_time + waiting_time[i] total_turn_around_time = total_turn_around_time + turn_around_time[i] print(f"Average waiting time = {total_waiting_time / no_of_processes:.5f}") print("Average turn around time =", total_turn_around_time / no_of_processes) if __name__ == "__main__": print("Enter how many process you want to analyze") no_of_processes = int(input()) burst_time = [0] * no_of_processes arrival_time = [0] * no_of_processes processes = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print("Enter the arrival time and burst time for process:--" + str(i + 1)) arrival_time[i], burst_time[i] = map(int, input().split()) waiting_time = calculate_waitingtime(arrival_time, burst_time, no_of_processes) bt = burst_time n = no_of_processes wt = waiting_time turn_around_time = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) fcfs = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ "Process", "BurstTime", "ArrivalTime", "WaitingTime", "TurnAroundTime", ], ) # Printing the dataFrame pd.set_option("display.max_rows", fcfs.shape[0] + 1) print(fcfs)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/scheduling/multi_level_feedback_queue.py
scheduling/multi_level_feedback_queue.py
from collections import deque class Process: def __init__(self, process_name: str, arrival_time: int, burst_time: int) -> None: self.process_name = process_name # process name self.arrival_time = arrival_time # arrival time of the process # completion time of finished process or last interrupted time self.stop_time = arrival_time self.burst_time = burst_time # remaining burst time self.waiting_time = 0 # total time of the process wait in ready queue self.turnaround_time = 0 # time from arrival time to completion time class MLFQ: """ MLFQ(Multi Level Feedback Queue) https://en.wikipedia.org/wiki/Multilevel_feedback_queue MLFQ has a lot of queues that have different priority In this MLFQ, The first Queue(0) to last second Queue(N-2) of MLFQ have Round Robin Algorithm The last Queue(N-1) has First Come, First Served Algorithm """ def __init__( self, number_of_queues: int, time_slices: list[int], queue: deque[Process], current_time: int, ) -> None: # total number of mlfq's queues self.number_of_queues = number_of_queues # time slice of queues that round robin algorithm applied self.time_slices = time_slices # unfinished process is in this ready_queue self.ready_queue = queue # current time self.current_time = current_time # finished process is in this sequence queue self.finish_queue: deque[Process] = deque() def calculate_sequence_of_finish_queue(self) -> list[str]: """ This method returns the sequence of finished processes >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> _ = mlfq.multi_level_feedback_queue() >>> mlfq.calculate_sequence_of_finish_queue() ['P2', 'P4', 'P1', 'P3'] """ sequence = [] for i in range(len(self.finish_queue)): sequence.append(self.finish_queue[i].process_name) return sequence def calculate_waiting_time(self, queue: list[Process]) -> list[int]: """ This method calculates waiting time of processes >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> _ = mlfq.multi_level_feedback_queue() >>> mlfq.calculate_waiting_time([P1, P2, P3, P4]) [83, 17, 94, 101] """ waiting_times = [] for i in range(len(queue)): waiting_times.append(queue[i].waiting_time) return waiting_times def calculate_turnaround_time(self, queue: list[Process]) -> list[int]: """ This method calculates turnaround time of processes >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> _ = mlfq.multi_level_feedback_queue() >>> mlfq.calculate_turnaround_time([P1, P2, P3, P4]) [136, 34, 162, 125] """ turnaround_times = [] for i in range(len(queue)): turnaround_times.append(queue[i].turnaround_time) return turnaround_times def calculate_completion_time(self, queue: list[Process]) -> list[int]: """ This method calculates completion time of processes >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> _ = mlfq.multi_level_feedback_queue() >>> mlfq.calculate_turnaround_time([P1, P2, P3, P4]) [136, 34, 162, 125] """ completion_times = [] for i in range(len(queue)): completion_times.append(queue[i].stop_time) return completion_times def calculate_remaining_burst_time_of_processes( self, queue: deque[Process] ) -> list[int]: """ This method calculate remaining burst time of processes >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> finish_queue, ready_queue = mlfq.round_robin(deque([P1, P2, P3, P4]), 17) >>> mlfq.calculate_remaining_burst_time_of_processes(mlfq.finish_queue) [0] >>> mlfq.calculate_remaining_burst_time_of_processes(ready_queue) [36, 51, 7] >>> finish_queue, ready_queue = mlfq.round_robin(ready_queue, 25) >>> mlfq.calculate_remaining_burst_time_of_processes(mlfq.finish_queue) [0, 0] >>> mlfq.calculate_remaining_burst_time_of_processes(ready_queue) [11, 26] """ return [q.burst_time for q in queue] def update_waiting_time(self, process: Process) -> int: """ This method updates waiting times of unfinished processes >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> mlfq.current_time = 10 >>> P1.stop_time = 5 >>> mlfq.update_waiting_time(P1) 5 """ process.waiting_time += self.current_time - process.stop_time return process.waiting_time def first_come_first_served(self, ready_queue: deque[Process]) -> deque[Process]: """ FCFS(First Come, First Served) FCFS will be applied to MLFQ's last queue A first came process will be finished at first >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> _ = mlfq.first_come_first_served(mlfq.ready_queue) >>> mlfq.calculate_sequence_of_finish_queue() ['P1', 'P2', 'P3', 'P4'] """ finished: deque[Process] = deque() # sequence deque of finished process while len(ready_queue) != 0: cp = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(cp) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 cp.burst_time = 0 # set the process's turnaround time because it is finished cp.turnaround_time = self.current_time - cp.arrival_time # set the completion time cp.stop_time = self.current_time # add the process to queue that has finished queue finished.append(cp) self.finish_queue.extend(finished) # add finished process to finish queue # FCFS will finish all remaining processes return finished def round_robin( self, ready_queue: deque[Process], time_slice: int ) -> tuple[deque[Process], deque[Process]]: """ RR(Round Robin) RR will be applied to MLFQ's all queues except last queue All processes can't use CPU for time more than time_slice If the process consume CPU up to time_slice, it will go back to ready queue >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> finish_queue, ready_queue = mlfq.round_robin(mlfq.ready_queue, 17) >>> mlfq.calculate_sequence_of_finish_queue() ['P2'] """ finished: deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(ready_queue)): cp = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(cp) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time cp.stop_time = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(cp) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished cp.burst_time = 0 # set the finish time cp.stop_time = self.current_time # update the process' turnaround time because it is finished cp.turnaround_time = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(cp) self.finish_queue.extend(finished) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def multi_level_feedback_queue(self) -> deque[Process]: """ MLFQ(Multi Level Feedback Queue) >>> P1 = Process("P1", 0, 53) >>> P2 = Process("P2", 0, 17) >>> P3 = Process("P3", 0, 68) >>> P4 = Process("P4", 0, 24) >>> mlfq = MLFQ(3, [17, 25], deque([P1, P2, P3, P4]), 0) >>> finish_queue = mlfq.multi_level_feedback_queue() >>> mlfq.calculate_sequence_of_finish_queue() ['P2', 'P4', 'P1', 'P3'] """ # all queues except last one have round_robin algorithm for i in range(self.number_of_queues - 1): _finished, self.ready_queue = self.round_robin( self.ready_queue, self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue) return self.finish_queue if __name__ == "__main__": import doctest P1 = Process("P1", 0, 53) P2 = Process("P2", 0, 17) P3 = Process("P3", 0, 68) P4 = Process("P4", 0, 24) number_of_queues = 3 time_slices = [17, 25] queue = deque([P1, P2, P3, P4]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={"queue": deque([P1, P2, P3, P4])}) P1 = Process("P1", 0, 53) P2 = Process("P2", 0, 17) P3 = Process("P3", 0, 68) P4 = Process("P4", 0, 24) number_of_queues = 3 time_slices = [17, 25] queue = deque([P1, P2, P3, P4]) mlfq = MLFQ(number_of_queues, time_slices, queue, 0) finish_queue = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( f"waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [P1, P2, P3, P4])}" ) # print completion times of processes(P1, P2, P3, P4) print( f"completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [P1, P2, P3, P4])}" ) # print total turnaround times of processes(P1, P2, P3, P4) print( f"turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [P1, P2, P3, P4])}" ) # print sequence of finished processes print( f"sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}" )
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/scheduling/non_preemptive_shortest_job_first.py
scheduling/non_preemptive_shortest_job_first.py
""" Non-preemptive Shortest Job First Shortest execution time process is chosen for the next execution. https://www.guru99.com/shortest-job-first-sjf-scheduling.html https://en.wikipedia.org/wiki/Shortest_job_next """ from __future__ import annotations from statistics import mean def calculate_waitingtime( arrival_time: list[int], burst_time: list[int], no_of_processes: int ) -> list[int]: """ Calculate the waiting time of each processes Return: The waiting time for each process. >>> calculate_waitingtime([0,1,2], [10, 5, 8], 3) [0, 9, 13] >>> calculate_waitingtime([1,2,2,4], [4, 6, 3, 1], 4) [0, 7, 4, 1] >>> calculate_waitingtime([0,0,0], [12, 2, 10],3) [12, 0, 2] """ waiting_time = [0] * no_of_processes remaining_time = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(no_of_processes): remaining_time[i] = burst_time[i] ready_process: list[int] = [] completed = 0 total_time = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: ready_process = [] target_process = -1 for i in range(no_of_processes): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(i) if len(ready_process) > 0: target_process = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: target_process = i total_time += burst_time[target_process] completed += 1 remaining_time[target_process] = 0 waiting_time[target_process] = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def calculate_turnaroundtime( burst_time: list[int], no_of_processes: int, waiting_time: list[int] ) -> list[int]: """ Calculate the turnaround time of each process. Return: The turnaround time for each process. >>> calculate_turnaroundtime([0,1,2], 3, [0, 10, 15]) [0, 11, 17] >>> calculate_turnaroundtime([1,2,2,4], 4, [1, 8, 5, 4]) [2, 10, 7, 8] >>> calculate_turnaroundtime([0,0,0], 3, [12, 0, 2]) [12, 0, 2] """ turn_around_time = [0] * no_of_processes for i in range(no_of_processes): turn_around_time[i] = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") no_of_processes = 4 burst_time = [2, 5, 3, 7] arrival_time = [0, 0, 0, 0] waiting_time = calculate_waitingtime(arrival_time, burst_time, no_of_processes) turn_around_time = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_id in enumerate(list(range(1, 5))): print( f"{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t" f"{waiting_time[i]}\t\t\t\t{turn_around_time[i]}" ) print(f"\nAverage waiting time = {mean(waiting_time):.5f}") print(f"Average turnaround time = {mean(turn_around_time):.5f}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/scheduling/highest_response_ratio_next.py
scheduling/highest_response_ratio_next.py
""" Highest response ratio next (HRRN) scheduling is a non-preemptive discipline. It was developed as modification of shortest job next or shortest job first (SJN or SJF) to mitigate the problem of process starvation. https://en.wikipedia.org/wiki/Highest_response_ratio_next """ from statistics import mean import numpy as np def calculate_turn_around_time( process_name: list, arrival_time: list, burst_time: list, no_of_process: int ) -> list: """ Calculate the turn around time of each processes Return: The turn around time time for each process. >>> calculate_turn_around_time(["A", "B", "C"], [3, 5, 8], [2, 4, 6], 3) [2, 4, 7] >>> calculate_turn_around_time(["A", "B", "C"], [0, 2, 4], [3, 5, 7], 3) [3, 6, 11] """ current_time = 0 # Number of processes finished finished_process_count = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. finished_process = [0] * no_of_process # List to include calculation results turn_around_time = [0] * no_of_process # Sort by arrival time. burst_time = [burst_time[i] for i in np.argsort(arrival_time)] process_name = [process_name[i] for i in np.argsort(arrival_time)] arrival_time.sort() while no_of_process > finished_process_count: """ If the current time is less than the arrival time of the process that arrives first among the processes that have not been performed, change the current time. """ i = 0 while finished_process[i] == 1: i += 1 current_time = max(current_time, arrival_time[i]) response_ratio = 0 # Index showing the location of the process being performed loc = 0 # Saves the current response ratio. temp = 0 for i in range(no_of_process): if finished_process[i] == 0 and arrival_time[i] <= current_time: temp = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: response_ratio = temp loc = i # Calculate the turn around time turn_around_time[loc] = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. finished_process[loc] = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def calculate_waiting_time( process_name: list, # noqa: ARG001 turn_around_time: list, burst_time: list, no_of_process: int, ) -> list: """ Calculate the waiting time of each processes. Return: The waiting time for each process. >>> calculate_waiting_time(["A", "B", "C"], [2, 4, 7], [2, 4, 6], 3) [0, 0, 1] >>> calculate_waiting_time(["A", "B", "C"], [3, 6, 11], [3, 5, 7], 3) [0, 1, 4] """ waiting_time = [0] * no_of_process for i in range(no_of_process): waiting_time[i] = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": no_of_process = 5 process_name = ["A", "B", "C", "D", "E"] arrival_time = [1, 2, 3, 4, 5] burst_time = [1, 2, 3, 4, 5] turn_around_time = calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) waiting_time = calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print("Process name \tArrival time \tBurst time \tTurn around time \tWaiting time") for i in range(no_of_process): print( f"{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t" f"{turn_around_time[i]}\t\t\t{waiting_time[i]}" ) print(f"average waiting time : {mean(waiting_time):.5f}") print(f"average turn around time : {mean(turn_around_time):.5f}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/scheduling/__init__.py
scheduling/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/scheduling/round_robin.py
scheduling/round_robin.py
""" Round Robin is a scheduling algorithm. In Round Robin each process is assigned a fixed time slot in a cyclic way. https://en.wikipedia.org/wiki/Round-robin_scheduling """ from __future__ import annotations from statistics import mean def calculate_waiting_times(burst_times: list[int]) -> list[int]: """ Calculate the waiting times of a list of processes that have a specified duration. Return: The waiting time for each process. >>> calculate_waiting_times([10, 5, 8]) [13, 10, 13] >>> calculate_waiting_times([4, 6, 3, 1]) [5, 8, 9, 6] >>> calculate_waiting_times([12, 2, 10]) [12, 2, 12] """ quantum = 2 rem_burst_times = list(burst_times) waiting_times = [0] * len(burst_times) t = 0 while True: done = True for i, burst_time in enumerate(burst_times): if rem_burst_times[i] > 0: done = False if rem_burst_times[i] > quantum: t += quantum rem_burst_times[i] -= quantum else: t += rem_burst_times[i] waiting_times[i] = t - burst_time rem_burst_times[i] = 0 if done is True: return waiting_times def calculate_turn_around_times( burst_times: list[int], waiting_times: list[int] ) -> list[int]: """ >>> calculate_turn_around_times([1, 2, 3, 4], [0, 1, 3]) [1, 3, 6] >>> calculate_turn_around_times([10, 3, 7], [10, 6, 11]) [20, 9, 18] """ return [burst + waiting for burst, waiting in zip(burst_times, waiting_times)] if __name__ == "__main__": burst_times = [3, 5, 7] waiting_times = calculate_waiting_times(burst_times) turn_around_times = calculate_turn_around_times(burst_times, waiting_times) print("Process ID \tBurst Time \tWaiting Time \tTurnaround Time") for i, burst_time in enumerate(burst_times): print( f" {i + 1}\t\t {burst_time}\t\t {waiting_times[i]}\t\t " f"{turn_around_times[i]}" ) print(f"\nAverage waiting time = {mean(waiting_times):.5f}") print(f"Average turn around time = {mean(turn_around_times):.5f}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_compression/burrows_wheeler.py
data_compression/burrows_wheeler.py
""" https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform The Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. More importantly, the transformation is reversible, without needing to store any additional data except the position of the first original character. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation. """ from __future__ import annotations from typing import TypedDict class BWTTransformDict(TypedDict): bwt_string: str idx_original_string: int def all_rotations(s: str) -> list[str]: """ :param s: The string that will be rotated len(s) times. :return: A list with the rotations. :raises TypeError: If s is not an instance of str. Examples: >>> all_rotations("^BANANA|") # doctest: +NORMALIZE_WHITESPACE ['^BANANA|', 'BANANA|^', 'ANANA|^B', 'NANA|^BA', 'ANA|^BAN', 'NA|^BANA', 'A|^BANAN', '|^BANANA'] >>> all_rotations("a_asa_da_casa") # doctest: +NORMALIZE_WHITESPACE ['a_asa_da_casa', '_asa_da_casaa', 'asa_da_casaa_', 'sa_da_casaa_a', 'a_da_casaa_as', '_da_casaa_asa', 'da_casaa_asa_', 'a_casaa_asa_d', '_casaa_asa_da', 'casaa_asa_da_', 'asaa_asa_da_c', 'saa_asa_da_ca', 'aa_asa_da_cas'] >>> all_rotations("panamabanana") # doctest: +NORMALIZE_WHITESPACE ['panamabanana', 'anamabananap', 'namabananapa', 'amabananapan', 'mabananapana', 'abananapanam', 'bananapanama', 'ananapanamab', 'nanapanamaba', 'anapanamaban', 'napanamabana', 'apanamabanan'] >>> all_rotations(5) Traceback (most recent call last): ... TypeError: The parameter s type must be str. """ if not isinstance(s, str): raise TypeError("The parameter s type must be str.") return [s[i:] + s[:i] for i in range(len(s))] def bwt_transform(s: str) -> BWTTransformDict: """ :param s: The string that will be used at bwt algorithm :return: the string composed of the last char of each row of the ordered rotations and the index of the original string at ordered rotations list :raises TypeError: If the s parameter type is not str :raises ValueError: If the s parameter is empty Examples: >>> bwt_transform("^BANANA") {'bwt_string': 'BNN^AAA', 'idx_original_string': 6} >>> bwt_transform("a_asa_da_casa") {'bwt_string': 'aaaadss_c__aa', 'idx_original_string': 3} >>> bwt_transform("panamabanana") {'bwt_string': 'mnpbnnaaaaaa', 'idx_original_string': 11} >>> bwt_transform(4) Traceback (most recent call last): ... TypeError: The parameter s type must be str. >>> bwt_transform('') Traceback (most recent call last): ... ValueError: The parameter s must not be empty. """ if not isinstance(s, str): raise TypeError("The parameter s type must be str.") if not s: raise ValueError("The parameter s must not be empty.") rotations = all_rotations(s) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation response: BWTTransformDict = { "bwt_string": "".join([word[-1] for word in rotations]), "idx_original_string": rotations.index(s), } return response def reverse_bwt(bwt_string: str, idx_original_string: int) -> str: """ :param bwt_string: The string returned from bwt algorithm execution :param idx_original_string: A 0-based index of the string that was used to generate bwt_string at ordered rotations list :return: The string used to generate bwt_string when bwt was executed :raises TypeError: If the bwt_string parameter type is not str :raises ValueError: If the bwt_string parameter is empty :raises TypeError: If the idx_original_string type is not int or if not possible to cast it to int :raises ValueError: If the idx_original_string value is lower than 0 or greater than len(bwt_string) - 1 >>> reverse_bwt("BNN^AAA", 6) '^BANANA' >>> reverse_bwt("aaaadss_c__aa", 3) 'a_asa_da_casa' >>> reverse_bwt("mnpbnnaaaaaa", 11) 'panamabanana' >>> reverse_bwt(4, 11) Traceback (most recent call last): ... TypeError: The parameter bwt_string type must be str. >>> reverse_bwt("", 11) Traceback (most recent call last): ... ValueError: The parameter bwt_string must not be empty. >>> reverse_bwt("mnpbnnaaaaaa", "asd") # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... TypeError: The parameter idx_original_string type must be int or passive of cast to int. >>> reverse_bwt("mnpbnnaaaaaa", -1) Traceback (most recent call last): ... ValueError: The parameter idx_original_string must not be lower than 0. >>> reverse_bwt("mnpbnnaaaaaa", 12) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: The parameter idx_original_string must be lower than len(bwt_string). >>> reverse_bwt("mnpbnnaaaaaa", 11.0) 'panamabanana' >>> reverse_bwt("mnpbnnaaaaaa", 11.4) 'panamabanana' """ if not isinstance(bwt_string, str): raise TypeError("The parameter bwt_string type must be str.") if not bwt_string: raise ValueError("The parameter bwt_string must not be empty.") try: idx_original_string = int(idx_original_string) except ValueError: raise TypeError( "The parameter idx_original_string type must be int or passive" " of cast to int." ) if idx_original_string < 0: raise ValueError("The parameter idx_original_string must not be lower than 0.") if idx_original_string >= len(bwt_string): raise ValueError( "The parameter idx_original_string must be lower than len(bwt_string)." ) ordered_rotations = [""] * len(bwt_string) for _ in range(len(bwt_string)): for i in range(len(bwt_string)): ordered_rotations[i] = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": entry_msg = "Provide a string that I will generate its BWT transform: " s = input(entry_msg).strip() result = bwt_transform(s) print( f"Burrows Wheeler transform for string '{s}' results " f"in '{result['bwt_string']}'" ) original_string = reverse_bwt(result["bwt_string"], result["idx_original_string"]) print( f"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " f"we get original string '{original_string}'" )
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_compression/huffman.py
data_compression/huffman.py
from __future__ import annotations import sys class Letter: def __init__(self, letter: str, freq: int): self.letter: str = letter self.freq: int = freq self.bitstring: dict[str, str] = {} def __repr__(self) -> str: return f"{self.letter}:{self.freq}" class TreeNode: def __init__(self, freq: int, left: Letter | TreeNode, right: Letter | TreeNode): self.freq: int = freq self.left: Letter | TreeNode = left self.right: Letter | TreeNode = right def parse_file(file_path: str) -> list[Letter]: """ Read the file and build a dict of all letters and their frequencies, then convert the dict into a list of Letters. """ chars: dict[str, int] = {} with open(file_path) as f: while True: c = f.read(1) if not c: break chars[c] = chars[c] + 1 if c in chars else 1 return sorted((Letter(c, f) for c, f in chars.items()), key=lambda x: x.freq) def build_tree(letters: list[Letter]) -> Letter | TreeNode: """ Run through the list of Letters and build the min heap for the Huffman Tree. """ response: list[Letter | TreeNode] = list(letters) while len(response) > 1: left = response.pop(0) right = response.pop(0) total_freq = left.freq + right.freq node = TreeNode(total_freq, left, right) response.append(node) response.sort(key=lambda x: x.freq) return response[0] def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]: """ Recursively traverse the Huffman Tree to set each Letter's bitstring dictionary, and return the list of Letters """ if isinstance(root, Letter): root.bitstring[root.letter] = bitstring return [root] treenode: TreeNode = root letters = [] letters += traverse_tree(treenode.left, bitstring + "0") letters += traverse_tree(treenode.right, bitstring + "1") return letters def huffman(file_path: str) -> None: """ Parse the file, build the tree, then run through the file again, using the letters dictionary to find and print out the bitstring for each letter. """ letters_list = parse_file(file_path) root = build_tree(letters_list) letters = { k: v for letter in traverse_tree(root, "") for k, v in letter.bitstring.items() } print(f"Huffman Coding of {file_path}: ") with open(file_path) as f: while True: c = f.read(1) if not c: break print(letters[c], end=" ") print() if __name__ == "__main__": # pass the file path to the huffman function huffman(sys.argv[1])
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_compression/peak_signal_to_noise_ratio.py
data_compression/peak_signal_to_noise_ratio.py
""" Peak signal-to-noise ratio - PSNR https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio Source: https://tutorials.techonical.com/how-to-calculate-psnr-value-of-two-images-using-python """ import math import os import cv2 import numpy as np PIXEL_MAX = 255.0 def peak_signal_to_noise_ratio(original: float, contrast: float) -> float: mse = np.mean((original - contrast) ** 2) if mse == 0: return 100 return 20 * math.log10(PIXEL_MAX / math.sqrt(mse)) def main() -> None: dir_path = os.path.dirname(os.path.realpath(__file__)) # Loading images (original image and compressed image) original = cv2.imread(os.path.join(dir_path, "image_data/original_image.png")) contrast = cv2.imread(os.path.join(dir_path, "image_data/compressed_image.png"), 1) original2 = cv2.imread(os.path.join(dir_path, "image_data/PSNR-example-base.png")) contrast2 = cv2.imread( os.path.join(dir_path, "image_data/PSNR-example-comp-10.jpg"), 1 ) # Value expected: 29.73dB print("-- First Test --") print(f"PSNR value is {peak_signal_to_noise_ratio(original, contrast)} dB") # # Value expected: 31.53dB (Wikipedia Example) print("\n-- Second Test --") print(f"PSNR value is {peak_signal_to_noise_ratio(original2, contrast2)} dB") if __name__ == "__main__": main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_compression/coordinate_compression.py
data_compression/coordinate_compression.py
""" Assumption: - The values to compress are assumed to be comparable, values can be sorted and compared with '<' and '>' operators. """ class CoordinateCompressor: """ A class for coordinate compression. This class allows you to compress and decompress a list of values. Mapping: In addition to compression and decompression, this class maintains a mapping between original values and their compressed counterparts using two data structures: a dictionary `coordinate_map` and a list `reverse_map`: - `coordinate_map`: A dictionary that maps original values to their compressed coordinates. Keys are original values, and values are compressed coordinates. - `reverse_map`: A list used for reverse mapping, where each index corresponds to a compressed coordinate, and the value at that index is the original value. Example of mapping: Original: 10, Compressed: 0 Original: 52, Compressed: 1 Original: 83, Compressed: 2 Original: 100, Compressed: 3 This mapping allows for efficient compression and decompression of values within the list. """ def __init__(self, arr: list[int | float | str]) -> None: """ Initialize the CoordinateCompressor with a list. Args: arr: The list of values to be compressed. >>> arr = [100, 10, 52, 83] >>> cc = CoordinateCompressor(arr) >>> cc.compress(100) 3 >>> cc.compress(52) 1 >>> cc.decompress(1) 52 """ # A dictionary to store compressed coordinates self.coordinate_map: dict[int | float | str, int] = {} # A list to store reverse mapping self.reverse_map: list[int | float | str] = [-1] * len(arr) self.arr = sorted(arr) # The input list self.n = len(arr) # The length of the input list self.compress_coordinates() def compress_coordinates(self) -> None: """ Compress the coordinates in the input list. >>> arr = [100, 10, 52, 83] >>> cc = CoordinateCompressor(arr) >>> cc.coordinate_map[83] 2 >>> cc.coordinate_map[80] # Value not in the original list Traceback (most recent call last): ... KeyError: 80 >>> cc.reverse_map[2] 83 """ key = 0 for val in self.arr: if val not in self.coordinate_map: self.coordinate_map[val] = key self.reverse_map[key] = val key += 1 def compress(self, original: float | str) -> int: """ Compress a single value. Args: original: The value to compress. Returns: The compressed integer, or -1 if not found in the original list. >>> arr = [100, 10, 52, 83] >>> cc = CoordinateCompressor(arr) >>> cc.compress(100) 3 >>> cc.compress(7) # Value not in the original list -1 """ return self.coordinate_map.get(original, -1) def decompress(self, num: int) -> int | float | str: """ Decompress a single integer. Args: num: The compressed integer to decompress. Returns: The original value. >>> arr = [100, 10, 52, 83] >>> cc = CoordinateCompressor(arr) >>> cc.decompress(0) 10 >>> cc.decompress(5) # Compressed coordinate out of range -1 """ return self.reverse_map[num] if 0 <= num < len(self.reverse_map) else -1 if __name__ == "__main__": from doctest import testmod testmod() arr: list[int | float | str] = [100, 10, 52, 83] cc = CoordinateCompressor(arr) for original in arr: compressed = cc.compress(original) decompressed = cc.decompress(compressed) print(f"Original: {decompressed}, Compressed: {compressed}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_compression/lempel_ziv.py
data_compression/lempel_ziv.py
""" One of the several implementations of Lempel-Ziv-Welch compression algorithm https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch """ import math import os import sys def read_file_binary(file_path: str) -> str: """ Reads given file as bytes and returns them as a long string """ result = "" try: with open(file_path, "rb") as binary_file: data = binary_file.read() for dat in data: curr_byte = f"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible") sys.exit() def add_key_to_lexicon( lexicon: dict[str, str], curr_string: str, index: int, last_match_id: str ) -> None: """ Adds new strings (curr_string + "0", curr_string + "1") to the lexicon """ lexicon.pop(curr_string) lexicon[curr_string + "0"] = last_match_id if math.log2(index).is_integer(): for curr_key, value in lexicon.items(): lexicon[curr_key] = f"0{value}" lexicon[curr_string + "1"] = bin(index)[2:] def compress_data(data_bits: str) -> str: """ Compresses given data_bits using Lempel-Ziv-Welch compression algorithm and returns the result as a string """ lexicon = {"0": "0", "1": "1"} result, curr_string = "", "" index = len(lexicon) for i in range(len(data_bits)): curr_string += data_bits[i] if curr_string not in lexicon: continue last_match_id = lexicon[curr_string] result += last_match_id add_key_to_lexicon(lexicon, curr_string, index, last_match_id) index += 1 curr_string = "" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": last_match_id = lexicon[curr_string] result += last_match_id return result def add_file_length(source_path: str, compressed: str) -> str: """ Adds given file's length in front (using Elias gamma coding) of the compressed string """ file_length = os.path.getsize(source_path) file_length_binary = bin(file_length)[2:] length_length = len(file_length_binary) return "0" * (length_length - 1) + file_length_binary + compressed def write_file_binary(file_path: str, to_write: str) -> None: """ Writes given to_write string (should only consist of 0's and 1's) as bytes in the file """ byte_length = 8 try: with open(file_path, "wb") as opened_file: result_byte_array = [ to_write[i : i + byte_length] for i in range(0, len(to_write), byte_length) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append("10000000") else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array: opened_file.write(int(elem, 2).to_bytes(1, byteorder="big")) except OSError: print("File not accessible") sys.exit() def compress(source_path: str, destination_path: str) -> None: """ Reads source file, compresses it and writes the compressed result in destination file """ data_bits = read_file_binary(source_path) compressed = compress_data(data_bits) compressed = add_file_length(source_path, compressed) write_file_binary(destination_path, compressed) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_compression/__init__.py
data_compression/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_compression/run_length_encoding.py
data_compression/run_length_encoding.py
# https://en.wikipedia.org/wiki/Run-length_encoding def run_length_encode(text: str) -> list: """ Performs Run Length Encoding >>> run_length_encode("AAAABBBCCDAA") [('A', 4), ('B', 3), ('C', 2), ('D', 1), ('A', 2)] >>> run_length_encode("A") [('A', 1)] >>> run_length_encode("AA") [('A', 2)] >>> run_length_encode("AAADDDDDDFFFCCCAAVVVV") [('A', 3), ('D', 6), ('F', 3), ('C', 3), ('A', 2), ('V', 4)] """ encoded = [] count = 1 for i in range(len(text)): if i + 1 < len(text) and text[i] == text[i + 1]: count += 1 else: encoded.append((text[i], count)) count = 1 return encoded def run_length_decode(encoded: list) -> str: """ Performs Run Length Decoding >>> run_length_decode([('A', 4), ('B', 3), ('C', 2), ('D', 1), ('A', 2)]) 'AAAABBBCCDAA' >>> run_length_decode([('A', 1)]) 'A' >>> run_length_decode([('A', 2)]) 'AA' >>> run_length_decode([('A', 3), ('D', 6), ('F', 3), ('C', 3), ('A', 2), ('V', 4)]) 'AAADDDDDDFFFCCCAAVVVV' """ return "".join(char * length for char, length in encoded) if __name__ == "__main__": from doctest import testmod testmod(name="run_length_encode", verbose=True) testmod(name="run_length_decode", verbose=True)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_compression/lz77.py
data_compression/lz77.py
""" LZ77 compression algorithm - lossless data compression published in papers by Abraham Lempel and Jacob Ziv in 1977 - also known as LZ1 or sliding-window compression - form the basis for many variations including LZW, LZSS, LZMA and others It uses a “sliding window” method. Within the sliding window we have: - search buffer - look ahead buffer len(sliding_window) = len(search_buffer) + len(look_ahead_buffer) LZ77 manages a dictionary that uses triples composed of: - Offset into search buffer, it's the distance between the start of a phrase and the beginning of a file. - Length of the match, it's the number of characters that make up a phrase. - The indicator is represented by a character that is going to be encoded next. As a file is parsed, the dictionary is dynamically updated to reflect the compressed data contents and size. Examples: "cabracadabrarrarrad" <-> [(0, 0, 'c'), (0, 0, 'a'), (0, 0, 'b'), (0, 0, 'r'), (3, 1, 'c'), (2, 1, 'd'), (7, 4, 'r'), (3, 5, 'd')] "ababcbababaa" <-> [(0, 0, 'a'), (0, 0, 'b'), (2, 2, 'c'), (4, 3, 'a'), (2, 2, 'a')] "aacaacabcabaaac" <-> [(0, 0, 'a'), (1, 1, 'c'), (3, 4, 'b'), (3, 3, 'a'), (1, 2, 'c')] Sources: en.wikipedia.org/wiki/LZ77_and_LZ78 """ from dataclasses import dataclass __version__ = "0.1" __author__ = "Lucia Harcekova" @dataclass class Token: """ Dataclass representing triplet called token consisting of length, offset and indicator. This triplet is used during LZ77 compression. """ offset: int length: int indicator: str def __repr__(self) -> str: """ >>> token = Token(1, 2, "c") >>> repr(token) '(1, 2, c)' >>> str(token) '(1, 2, c)' """ return f"({self.offset}, {self.length}, {self.indicator})" class LZ77Compressor: """ Class containing compress and decompress methods using LZ77 compression algorithm. """ def __init__(self, window_size: int = 13, lookahead_buffer_size: int = 6) -> None: self.window_size = window_size self.lookahead_buffer_size = lookahead_buffer_size self.search_buffer_size = self.window_size - self.lookahead_buffer_size def compress(self, text: str) -> list[Token]: """ Compress the given string text using LZ77 compression algorithm. Args: text: string to be compressed Returns: output: the compressed text as a list of Tokens >>> lz77_compressor = LZ77Compressor() >>> str(lz77_compressor.compress("ababcbababaa")) '[(0, 0, a), (0, 0, b), (2, 2, c), (4, 3, a), (2, 2, a)]' >>> str(lz77_compressor.compress("aacaacabcabaaac")) '[(0, 0, a), (1, 1, c), (3, 4, b), (3, 3, a), (1, 2, c)]' """ output = [] search_buffer = "" # while there are still characters in text to compress while text: # find the next encoding phrase # - triplet with offset, length, indicator (the next encoding character) token = self._find_encoding_token(text, search_buffer) # update the search buffer: # - add new characters from text into it # - check if size exceed the max search buffer size, if so, drop the # oldest elements search_buffer += text[: token.length + 1] if len(search_buffer) > self.search_buffer_size: search_buffer = search_buffer[-self.search_buffer_size :] # update the text text = text[token.length + 1 :] # append the token to output output.append(token) return output def decompress(self, tokens: list[Token]) -> str: """ Convert the list of tokens into an output string. Args: tokens: list containing triplets (offset, length, char) Returns: output: decompressed text Tests: >>> lz77_compressor = LZ77Compressor() >>> lz77_compressor.decompress([Token(0, 0, 'c'), Token(0, 0, 'a'), ... Token(0, 0, 'b'), Token(0, 0, 'r'), Token(3, 1, 'c'), ... Token(2, 1, 'd'), Token(7, 4, 'r'), Token(3, 5, 'd')]) 'cabracadabrarrarrad' >>> lz77_compressor.decompress([Token(0, 0, 'a'), Token(0, 0, 'b'), ... Token(2, 2, 'c'), Token(4, 3, 'a'), Token(2, 2, 'a')]) 'ababcbababaa' >>> lz77_compressor.decompress([Token(0, 0, 'a'), Token(1, 1, 'c'), ... Token(3, 4, 'b'), Token(3, 3, 'a'), Token(1, 2, 'c')]) 'aacaacabcabaaac' """ output = "" for token in tokens: for _ in range(token.length): output += output[-token.offset] output += token.indicator return output def _find_encoding_token(self, text: str, search_buffer: str) -> Token: """Finds the encoding token for the first character in the text. Tests: >>> lz77_compressor = LZ77Compressor() >>> lz77_compressor._find_encoding_token("abrarrarrad", "abracad").offset 7 >>> lz77_compressor._find_encoding_token("adabrarrarrad", "cabrac").length 1 >>> lz77_compressor._find_encoding_token("abc", "xyz").offset 0 >>> lz77_compressor._find_encoding_token("", "xyz").offset Traceback (most recent call last): ... ValueError: We need some text to work with. >>> lz77_compressor._find_encoding_token("abc", "").offset 0 """ if not text: raise ValueError("We need some text to work with.") # Initialise result parameters to default values length, offset = 0, 0 if not search_buffer: return Token(offset, length, text[length]) for i, character in enumerate(search_buffer): found_offset = len(search_buffer) - i if character == text[0]: found_length = self._match_length_from_index(text, search_buffer, 0, i) # if the found length is bigger than the current or if it's equal, # which means it's offset is smaller: update offset and length if found_length >= length: offset, length = found_offset, found_length return Token(offset, length, text[length]) def _match_length_from_index( self, text: str, window: str, text_index: int, window_index: int ) -> int: """Calculate the longest possible match of text and window characters from text_index in text and window_index in window. Args: text: _description_ window: sliding window text_index: index of character in text window_index: index of character in sliding window Returns: The maximum match between text and window, from given indexes. Tests: >>> lz77_compressor = LZ77Compressor(13, 6) >>> lz77_compressor._match_length_from_index("rarrad", "adabrar", 0, 4) 5 >>> lz77_compressor._match_length_from_index("adabrarrarrad", ... "cabrac", 0, 1) 1 """ if not text or text[text_index] != window[window_index]: return 0 return 1 + self._match_length_from_index( text, window + text[text_index], text_index + 1, window_index + 1 ) if __name__ == "__main__": from doctest import testmod testmod() # Initialize compressor class lz77_compressor = LZ77Compressor(window_size=13, lookahead_buffer_size=6) # Example TEXT = "cabracadabrarrarrad" compressed_text = lz77_compressor.compress(TEXT) print(lz77_compressor.compress("ababcbababaa")) decompressed_text = lz77_compressor.decompress(compressed_text) assert decompressed_text == TEXT, "The LZ77 algorithm returned the invalid result."
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_compression/lempel_ziv_decompress.py
data_compression/lempel_ziv_decompress.py
""" One of the several implementations of Lempel-Ziv-Welch decompression algorithm https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch """ import math import sys def read_file_binary(file_path: str) -> str: """ Reads given file as bytes and returns them as a long string """ result = "" try: with open(file_path, "rb") as binary_file: data = binary_file.read() for dat in data: curr_byte = f"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible") sys.exit() def decompress_data(data_bits: str) -> str: """ Decompresses given data_bits using Lempel-Ziv-Welch compression algorithm and returns the result as a string """ lexicon = {"0": "0", "1": "1"} result, curr_string = "", "" index = len(lexicon) for i in range(len(data_bits)): curr_string += data_bits[i] if curr_string not in lexicon: continue last_match_id = lexicon[curr_string] result += last_match_id lexicon[curr_string] = last_match_id + "0" if math.log2(index).is_integer(): new_lex = {} for curr_key in list(lexicon): new_lex["0" + curr_key] = lexicon.pop(curr_key) lexicon = new_lex lexicon[bin(index)[2:]] = last_match_id + "1" index += 1 curr_string = "" return result def write_file_binary(file_path: str, to_write: str) -> None: """ Writes given to_write string (should only consist of 0's and 1's) as bytes in the file """ byte_length = 8 try: with open(file_path, "wb") as opened_file: result_byte_array = [ to_write[i : i + byte_length] for i in range(0, len(to_write), byte_length) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append("10000000") else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(elem, 2).to_bytes(1, byteorder="big")) except OSError: print("File not accessible") sys.exit() def remove_prefix(data_bits: str) -> str: """ Removes size prefix, that compressed file should have Returns the result """ counter = 0 for letter in data_bits: if letter == "1": break counter += 1 data_bits = data_bits[counter:] data_bits = data_bits[counter + 1 :] return data_bits def compress(source_path: str, destination_path: str) -> None: """ Reads source file, decompresses it and writes the result in destination file """ data_bits = read_file_binary(source_path) data_bits = remove_prefix(data_bits) decompressed = decompress_data(data_bits) write_file_binary(destination_path, decompressed) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/file_transfer/send_file.py
file_transfer/send_file.py
def send_file(filename: str = "mytext.txt", testing: bool = False) -> None: import socket port = 12312 # Reserve a port for your service. sock = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name sock.bind((host, port)) # Bind to the port sock.listen(5) # Now wait for client connection. print("Server listening....") while True: conn, addr = sock.accept() # Establish connection with client. print(f"Got connection from {addr}") data = conn.recv(1024) print(f"Server received: {data = }") with open(filename, "rb") as in_file: data = in_file.read(1024) while data: conn.send(data) print(f"Sent {data!r}") data = in_file.read(1024) print("Done sending") conn.close() if testing: # Allow the test to complete break sock.shutdown(1) sock.close() if __name__ == "__main__": send_file()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/file_transfer/__init__.py
file_transfer/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/file_transfer/receive_file.py
file_transfer/receive_file.py
import socket def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() port = 12312 sock.connect((host, port)) sock.send(b"Hello server!") with open("Received_file", "wb") as out_file: print("File opened") print("Receiving data...") while True: data = sock.recv(1024) if not data: break out_file.write(data) print("Successfully received the file") sock.close() print("Connection closed") if __name__ == "__main__": main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/file_transfer/tests/test_send_file.py
file_transfer/tests/test_send_file.py
from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch("socket.socket") @patch("builtins.open") def test_send_file_running_as_expected(file, sock): # ===== initialization ===== conn = Mock() sock.return_value.accept.return_value = conn, Mock() f = iter([1, None]) file.return_value.__enter__.return_value.read.side_effect = lambda _: next(f) # ===== invoke ===== send_file(filename="mytext.txt", testing=True) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/file_transfer/tests/__init__.py
file_transfer/tests/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/greedy_methods/fractional_cover_problem.py
greedy_methods/fractional_cover_problem.py
# https://en.wikipedia.org/wiki/Set_cover_problem from dataclasses import dataclass from operator import attrgetter @dataclass class Item: weight: int value: int @property def ratio(self) -> float: """ Return the value-to-weight ratio for the item. Returns: float: The value-to-weight ratio for the item. Examples: >>> Item(10, 65).ratio 6.5 >>> Item(20, 100).ratio 5.0 >>> Item(30, 120).ratio 4.0 """ return self.value / self.weight def fractional_cover(items: list[Item], capacity: int) -> float: """ Solve the Fractional Cover Problem. Args: items: A list of items, where each item has weight and value attributes. capacity: The maximum weight capacity of the knapsack. Returns: The maximum value that can be obtained by selecting fractions of items to cover the knapsack's capacity. Raises: ValueError: If capacity is negative. Examples: >>> fractional_cover((Item(10, 60), Item(20, 100), Item(30, 120)), capacity=50) 240.0 >>> fractional_cover([Item(20, 100), Item(30, 120), Item(10, 60)], capacity=25) 135.0 >>> fractional_cover([Item(10, 60), Item(20, 100), Item(30, 120)], capacity=60) 280.0 >>> fractional_cover(items=[Item(5, 30), Item(10, 60), Item(15, 90)], capacity=30) 180.0 >>> fractional_cover(items=[], capacity=50) 0.0 >>> fractional_cover(items=[Item(10, 60)], capacity=5) 30.0 >>> fractional_cover(items=[Item(10, 60)], capacity=1) 6.0 >>> fractional_cover(items=[Item(10, 60)], capacity=0) 0.0 >>> fractional_cover(items=[Item(10, 60)], capacity=-1) Traceback (most recent call last): ... ValueError: Capacity cannot be negative """ if capacity < 0: raise ValueError("Capacity cannot be negative") total_value = 0.0 remaining_capacity = capacity # Sort the items by their value-to-weight ratio in descending order for item in sorted(items, key=attrgetter("ratio"), reverse=True): if remaining_capacity == 0: break weight_taken = min(item.weight, remaining_capacity) total_value += weight_taken * item.ratio remaining_capacity -= weight_taken return total_value if __name__ == "__main__": import doctest if result := doctest.testmod().failed: print(f"{result} test(s) failed") else: print("All tests passed")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/greedy_methods/smallest_range.py
greedy_methods/smallest_range.py
""" smallest_range function takes a list of sorted integer lists and finds the smallest range that includes at least one number from each list, using a min heap for efficiency. """ from heapq import heappop, heappush from sys import maxsize def smallest_range(nums: list[list[int]]) -> list[int]: """ Find the smallest range from each list in nums. Uses min heap for efficiency. The range includes at least one number from each list. Args: `nums`: List of k sorted integer lists. Returns: list: Smallest range as a two-element list. Examples: >>> smallest_range([[4, 10, 15, 24, 26], [0, 9, 12, 20], [5, 18, 22, 30]]) [20, 24] >>> smallest_range([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) [1, 1] >>> smallest_range(((1, 2, 3), (1, 2, 3), (1, 2, 3))) [1, 1] >>> smallest_range(((-3, -2, -1), (0, 0, 0), (1, 2, 3))) [-1, 1] >>> smallest_range([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) [3, 7] >>> smallest_range([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) [0, 0] >>> smallest_range([[], [], []]) Traceback (most recent call last): ... IndexError: list index out of range """ min_heap: list[tuple[int, int, int]] = [] current_max = -maxsize - 1 for i, items in enumerate(nums): heappush(min_heap, (items[0], i, 0)) current_max = max(current_max, items[0]) # Initialize smallest_range with large integer values smallest_range = [-maxsize - 1, maxsize] while min_heap: current_min, list_index, element_index = heappop(min_heap) if current_max - current_min < smallest_range[1] - smallest_range[0]: smallest_range = [current_min, current_max] if element_index == len(nums[list_index]) - 1: break next_element = nums[list_index][element_index + 1] heappush(min_heap, (next_element, list_index, element_index + 1)) current_max = max(current_max, next_element) return smallest_range if __name__ == "__main__": from doctest import testmod testmod() print(f"{smallest_range([[1, 2, 3], [1, 2, 3], [1, 2, 3]])}") # Output: [1, 1]
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/greedy_methods/optimal_merge_pattern.py
greedy_methods/optimal_merge_pattern.py
""" This is a pure Python implementation of the greedy-merge-sort algorithm reference: https://www.geeksforgeeks.org/optimal-file-merge-patterns/ For doctests run following command: python3 -m doctest -v greedy_merge_sort.py Objective Merge a set of sorted files of different length into a single sorted file. We need to find an optimal solution, where the resultant file will be generated in minimum time. Approach If the number of sorted files are given, there are many ways to merge them into a single sorted file. This merge can be performed pair wise. To merge a m-record file and a n-record file requires possibly m+n record moves the optimal choice being, merge the two smallest files together at each step (greedy approach). """ def optimal_merge_pattern(files: list) -> float: """Function to merge all the files with optimum cost Args: files [list]: A list of sizes of different files to be merged Returns: optimal_merge_cost [int]: Optimal cost to merge all those files Examples: >>> optimal_merge_pattern([2, 3, 4]) 14 >>> optimal_merge_pattern([5, 10, 20, 30, 30]) 205 >>> optimal_merge_pattern([8, 8, 8, 8, 8]) 96 """ optimal_merge_cost = 0 while len(files) > 1: temp = 0 # Consider two files with minimum cost to be merged for _ in range(2): min_index = files.index(min(files)) temp += files[min_index] files.pop(min_index) files.append(temp) optimal_merge_cost += temp return optimal_merge_cost if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/greedy_methods/best_time_to_buy_and_sell_stock.py
greedy_methods/best_time_to_buy_and_sell_stock.py
""" Given a list of stock prices calculate the maximum profit that can be made from a single buy and sell of one share of stock. We only allowed to complete one buy transaction and one sell transaction but must buy before we sell. Example : prices = [7, 1, 5, 3, 6, 4] max_profit will return 5 - which is by buying at price 1 and selling at price 6. This problem can be solved using the concept of "GREEDY ALGORITHM". We iterate over the price array once, keeping track of the lowest price point (buy) and the maximum profit we can get at each point. The greedy choice at each point is to either buy at the current price if it's less than our current buying price, or sell at the current price if the profit is more than our current maximum profit. """ def max_profit(prices: list[int]) -> int: """ >>> max_profit([7, 1, 5, 3, 6, 4]) 5 >>> max_profit([7, 6, 4, 3, 1]) 0 """ if not prices: return 0 min_price = prices[0] max_profit: int = 0 for price in prices: min_price = min(price, min_price) max_profit = max(price - min_price, max_profit) return max_profit if __name__ == "__main__": import doctest doctest.testmod() print(max_profit([7, 1, 5, 3, 6, 4]))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/greedy_methods/minimum_coin_change.py
greedy_methods/minimum_coin_change.py
""" Test cases: Do you want to enter your denominations ? (Y/N) :N Enter the change you want to make in Indian Currency: 987 Following is minimal change for 987 : 500 100 100 100 100 50 20 10 5 2 Do you want to enter your denominations ? (Y/N) :Y Enter number of denomination:10 1 5 10 20 50 100 200 500 1000 2000 Enter the change you want to make: 18745 Following is minimal change for 18745 : 2000 2000 2000 2000 2000 2000 2000 2000 2000 500 200 20 20 5 Do you want to enter your denominations ? (Y/N) :N Enter the change you want to make: 0 The total value cannot be zero or negative. Do you want to enter your denominations ? (Y/N) :N Enter the change you want to make: -98 The total value cannot be zero or negative. Do you want to enter your denominations ? (Y/N) :Y Enter number of denomination:5 1 5 100 500 1000 Enter the change you want to make: 456 Following is minimal change for 456 : 100 100 100 100 5 5 5 5 5 5 5 5 5 5 5 1 """ def find_minimum_change(denominations: list[int], value: str) -> list[int]: """ Find the minimum change from the given denominations and value >>> find_minimum_change([1, 5, 10, 20, 50, 100, 200, 500, 1000,2000], 18745) [2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 500, 200, 20, 20, 5] >>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], 987) [500, 100, 100, 100, 100, 50, 20, 10, 5, 2] >>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], 0) [] >>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], -98) [] >>> find_minimum_change([1, 5, 100, 500, 1000], 456) [100, 100, 100, 100, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1] """ total_value = int(value) # Initialize Result answer = [] # Traverse through all denomination for denomination in reversed(denominations): # Find denominations while int(total_value) >= int(denomination): total_value -= int(denomination) answer.append(denomination) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": denominations = [] value = "0" if ( input("Do you want to enter your denominations ? (yY/n): ").strip().lower() == "y" ): n = int(input("Enter the number of denominations you want to add: ").strip()) for i in range(n): denominations.append(int(input(f"Denomination {i}: ").strip())) value = input("Enter the change you want to make in Indian Currency: ").strip() else: # All denominations of Indian Currency if user does not enter denominations = [1, 2, 5, 10, 20, 50, 100, 500, 2000] value = input("Enter the change you want to make: ").strip() if int(value) == 0 or int(value) < 0: print("The total value cannot be zero or negative.") else: print(f"Following is minimal change for {value}: ") answer = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=" ")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/greedy_methods/fractional_knapsack.py
greedy_methods/fractional_knapsack.py
from bisect import bisect from itertools import accumulate def frac_knapsack(vl, wt, w, n): """ >>> frac_knapsack([60, 100, 120], [10, 20, 30], 50, 3) 240.0 >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 10, 4) 105.0 >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 8, 4) 95.0 >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6], 8, 4) 60.0 >>> frac_knapsack([10, 40, 30], [5, 4, 6, 3], 8, 4) 60.0 >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 0, 4) 0 >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 8, 0) 95.0 >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], -8, 4) 0 >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 8, -4) 95.0 >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 800, 4) 130 >>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 8, 400) 95.0 >>> frac_knapsack("ABCD", [5, 4, 6, 3], 8, 400) Traceback (most recent call last): ... TypeError: unsupported operand type(s) for /: 'str' and 'int' """ r = sorted(zip(vl, wt), key=lambda x: x[0] / x[1], reverse=True) vl, wt = [i[0] for i in r], [i[1] for i in r] acc = list(accumulate(wt)) k = bisect(acc, w) return ( 0 if k == 0 else sum(vl[:k]) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k]) ) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/greedy_methods/__init__.py
greedy_methods/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/greedy_methods/gas_station.py
greedy_methods/gas_station.py
""" Task: There are n gas stations along a circular route, where the amount of gas at the ith station is gas_quantities[i]. You have a car with an unlimited gas tank and it costs costs[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays gas_quantities and costs, return the starting gas station's index if you can travel around the circuit once in the clockwise direction otherwise, return -1. If there exists a solution, it is guaranteed to be unique Reference: https://leetcode.com/problems/gas-station/description Implementation notes: First, check whether the total gas is enough to complete the journey. If not, return -1. However, if there is enough gas, it is guaranteed that there is a valid starting index to reach the end of the journey. Greedily calculate the net gain (gas_quantity - cost) at each station. If the net gain ever goes below 0 while iterating through the stations, start checking from the next station. """ from dataclasses import dataclass @dataclass class GasStation: gas_quantity: int cost: int def get_gas_stations( gas_quantities: list[int], costs: list[int] ) -> tuple[GasStation, ...]: """ This function returns a tuple of gas stations. Args: gas_quantities: Amount of gas available at each station costs: The cost of gas required to move from one station to the next Returns: A tuple of gas stations >>> gas_stations = get_gas_stations([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]) >>> len(gas_stations) 5 >>> gas_stations[0] GasStation(gas_quantity=1, cost=3) >>> gas_stations[-1] GasStation(gas_quantity=5, cost=2) """ return tuple( GasStation(quantity, cost) for quantity, cost in zip(gas_quantities, costs) ) def can_complete_journey(gas_stations: tuple[GasStation, ...]) -> int: """ This function returns the index from which to start the journey in order to reach the end. Args: gas_quantities [list]: Amount of gas available at each station cost [list]: The cost of gas required to move from one station to the next Returns: start [int]: start index needed to complete the journey Examples: >>> can_complete_journey(get_gas_stations([1, 2, 3, 4, 5], [3, 4, 5, 1, 2])) 3 >>> can_complete_journey(get_gas_stations([2, 3, 4], [3, 4, 3])) -1 """ total_gas = sum(gas_station.gas_quantity for gas_station in gas_stations) total_cost = sum(gas_station.cost for gas_station in gas_stations) if total_gas < total_cost: return -1 start = 0 net = 0 for i, gas_station in enumerate(gas_stations): net += gas_station.gas_quantity - gas_station.cost if net < 0: start = i + 1 net = 0 return start if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/greedy_methods/fractional_knapsack_2.py
greedy_methods/fractional_knapsack_2.py
# https://en.wikipedia.org/wiki/Continuous_knapsack_problem # https://www.guru99.com/fractional-knapsack-problem-greedy.html # https://medium.com/walkinthecode/greedy-algorithm-fractional-knapsack-problem-9aba1daecc93 from __future__ import annotations def fractional_knapsack( value: list[int], weight: list[int], capacity: int ) -> tuple[float, list[float]]: """ >>> value = [1, 3, 5, 7, 9] >>> weight = [0.9, 0.7, 0.5, 0.3, 0.1] >>> fractional_knapsack(value, weight, 5) (25, [1, 1, 1, 1, 1]) >>> fractional_knapsack(value, weight, 15) (25, [1, 1, 1, 1, 1]) >>> fractional_knapsack(value, weight, 25) (25, [1, 1, 1, 1, 1]) >>> fractional_knapsack(value, weight, 26) (25, [1, 1, 1, 1, 1]) >>> fractional_knapsack(value, weight, -1) (-90.0, [0, 0, 0, 0, -10.0]) >>> fractional_knapsack([1, 3, 5, 7], weight, 30) (16, [1, 1, 1, 1]) >>> fractional_knapsack(value, [0.9, 0.7, 0.5, 0.3, 0.1], 30) (25, [1, 1, 1, 1, 1]) >>> fractional_knapsack([], [], 30) (0, []) """ index = list(range(len(value))) ratio = [v / w for v, w in zip(value, weight)] index.sort(key=lambda i: ratio[i], reverse=True) max_value: float = 0 fractions: list[float] = [0] * len(value) for i in index: if weight[i] <= capacity: fractions[i] = 1 max_value += value[i] capacity -= weight[i] else: fractions[i] = capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/greedy_methods/minimum_waiting_time.py
greedy_methods/minimum_waiting_time.py
""" Calculate the minimum waiting time using a greedy algorithm. reference: https://www.youtube.com/watch?v=Sf3eiO12eJs For doctests run following command: python -m doctest -v minimum_waiting_time.py The minimum_waiting_time function uses a greedy algorithm to calculate the minimum time for queries to complete. It sorts the list in non-decreasing order, calculates the waiting time for each query by multiplying its position in the list with the sum of all remaining query times, and returns the total waiting time. A doctest ensures that the function produces the correct output. """ def minimum_waiting_time(queries: list[int]) -> int: """ This function takes a list of query times and returns the minimum waiting time for all queries to be completed. Args: queries: A list of queries measured in picoseconds Returns: total_waiting_time: Minimum waiting time measured in picoseconds Examples: >>> minimum_waiting_time([3, 2, 1, 2, 6]) 17 >>> minimum_waiting_time([3, 2, 1]) 4 >>> minimum_waiting_time([1, 2, 3, 4]) 10 >>> minimum_waiting_time([5, 5, 5, 5]) 30 >>> minimum_waiting_time([]) 0 """ n = len(queries) if n in (0, 1): return 0 return sum(query * (n - i - 1) for i, query in enumerate(sorted(queries))) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/linear_algebra/gaussian_elimination.py
linear_algebra/gaussian_elimination.py
""" | Gaussian elimination method for solving a system of linear equations. | Gaussian elimination - https://en.wikipedia.org/wiki/Gaussian_elimination """ import numpy as np from numpy import float64 from numpy.typing import NDArray def retroactive_resolution( coefficients: NDArray[float64], vector: NDArray[float64] ) -> NDArray[float64]: """ This function performs a retroactive linear system resolution for triangular matrix Examples: 1. * 2x1 + 2x2 - 1x3 = 5 * 0x1 - 2x2 - 1x3 = -7 * 0x1 + 0x2 + 5x3 = 15 2. * 2x1 + 2x2 = -1 * 0x1 - 2x2 = -1 >>> gaussian_elimination([[2, 2, -1], [0, -2, -1], [0, 0, 5]], [[5], [-7], [15]]) array([[2.], [2.], [3.]]) >>> gaussian_elimination([[2, 2], [0, -2]], [[-1], [-1]]) array([[-1. ], [ 0.5]]) """ rows, _columns = np.shape(coefficients) x: NDArray[float64] = np.zeros((rows, 1), dtype=float) for row in reversed(range(rows)): total = np.dot(coefficients[row, row + 1 :], x[row + 1 :]) x[row, 0] = (vector[row][0] - total[0]) / coefficients[row, row] return x def gaussian_elimination( coefficients: NDArray[float64], vector: NDArray[float64] ) -> NDArray[float64]: """ This function performs Gaussian elimination method Examples: 1. * 1x1 - 4x2 - 2x3 = -2 * 5x1 + 2x2 - 2x3 = -3 * 1x1 - 1x2 + 0x3 = 4 2. * 1x1 + 2x2 = 5 * 5x1 + 2x2 = 5 >>> gaussian_elimination([[1, -4, -2], [5, 2, -2], [1, -1, 0]], [[-2], [-3], [4]]) array([[ 2.3 ], [-1.7 ], [ 5.55]]) >>> gaussian_elimination([[1, 2], [5, 2]], [[5], [5]]) array([[0. ], [2.5]]) """ # coefficients must to be a square matrix so we need to check first rows, columns = np.shape(coefficients) if rows != columns: return np.array((), dtype=float) # augmented matrix augmented_mat: NDArray[float64] = np.concatenate((coefficients, vector), axis=1) augmented_mat = augmented_mat.astype("float64") # scale the matrix leaving it triangular for row in range(rows - 1): pivot = augmented_mat[row, row] for col in range(row + 1, columns): factor = augmented_mat[col, row] / pivot augmented_mat[col, :] -= factor * augmented_mat[row, :] x = retroactive_resolution( augmented_mat[:, 0:columns], augmented_mat[:, columns : columns + 1] ) return x if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/linear_algebra/jacobi_iteration_method.py
linear_algebra/jacobi_iteration_method.py
""" Jacobi Iteration Method - https://en.wikipedia.org/wiki/Jacobi_method """ from __future__ import annotations import numpy as np from numpy import float64 from numpy.typing import NDArray # Method to find solution of system of linear equations def jacobi_iteration_method( coefficient_matrix: NDArray[float64], constant_matrix: NDArray[float64], init_val: list[float], iterations: int, ) -> list[float]: """ Jacobi Iteration Method: An iterative algorithm to determine the solutions of strictly diagonally dominant system of linear equations 4x1 + x2 + x3 = 2 x1 + 5x2 + 2x3 = -6 x1 + 2x2 + 4x3 = -4 x_init = [0.5, -0.5 , -0.5] Examples: >>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]]) >>> constant = np.array([[2], [-6], [-4]]) >>> init_val = [0.5, -0.5, -0.5] >>> iterations = 3 >>> jacobi_iteration_method(coefficient, constant, init_val, iterations) [0.909375, -1.14375, -0.7484375] >>> coefficient = np.array([[4, 1, 1], [1, 5, 2]]) >>> constant = np.array([[2], [-6], [-4]]) >>> init_val = [0.5, -0.5, -0.5] >>> iterations = 3 >>> jacobi_iteration_method(coefficient, constant, init_val, iterations) Traceback (most recent call last): ... ValueError: Coefficient matrix dimensions must be nxn but received 2x3 >>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]]) >>> constant = np.array([[2], [-6]]) >>> init_val = [0.5, -0.5, -0.5] >>> iterations = 3 >>> jacobi_iteration_method( ... coefficient, constant, init_val, iterations ... ) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: Coefficient and constant matrices dimensions must be nxn and nx1 but received 3x3 and 2x1 >>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]]) >>> constant = np.array([[2], [-6], [-4]]) >>> init_val = [0.5, -0.5] >>> iterations = 3 >>> jacobi_iteration_method( ... coefficient, constant, init_val, iterations ... ) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: Number of initial values must be equal to number of rows in coefficient matrix but received 2 and 3 >>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]]) >>> constant = np.array([[2], [-6], [-4]]) >>> init_val = [0.5, -0.5, -0.5] >>> iterations = 0 >>> jacobi_iteration_method(coefficient, constant, init_val, iterations) Traceback (most recent call last): ... ValueError: Iterations must be at least 1 """ rows1, cols1 = coefficient_matrix.shape rows2, cols2 = constant_matrix.shape if rows1 != cols1: msg = f"Coefficient matrix dimensions must be nxn but received {rows1}x{cols1}" raise ValueError(msg) if cols2 != 1: msg = f"Constant matrix must be nx1 but received {rows2}x{cols2}" raise ValueError(msg) if rows1 != rows2: msg = ( "Coefficient and constant matrices dimensions must be nxn and nx1 but " f"received {rows1}x{cols1} and {rows2}x{cols2}" ) raise ValueError(msg) if len(init_val) != rows1: msg = ( "Number of initial values must be equal to number of rows in coefficient " f"matrix but received {len(init_val)} and {rows1}" ) raise ValueError(msg) if iterations <= 0: raise ValueError("Iterations must be at least 1") table: NDArray[float64] = np.concatenate( (coefficient_matrix, constant_matrix), axis=1 ) rows, _cols = table.shape strictly_diagonally_dominant(table) """ # Iterates the whole matrix for given number of times for _ in range(iterations): new_val = [] for row in range(rows): temp = 0 for col in range(cols): if col == row: denom = table[row][col] elif col == cols - 1: val = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] temp = (temp + val) / denom new_val.append(temp) init_val = new_val """ # denominator - a list of values along the diagonal denominator = np.diag(coefficient_matrix) # val_last - values of the last column of the table array val_last = table[:, -1] # masks - boolean mask of all strings without diagonal # elements array coefficient_matrix masks = ~np.eye(coefficient_matrix.shape[0], dtype=bool) # no_diagonals - coefficient_matrix array values without diagonal elements no_diagonals = coefficient_matrix[masks].reshape(-1, rows - 1) # Here we get 'i_col' - these are the column numbers, for each row # without diagonal elements, except for the last column. _i_row, i_col = np.where(masks) ind = i_col.reshape(-1, rows - 1) #'i_col' is converted to a two-dimensional list 'ind', which will be # used to make selections from 'init_val' ('arr' array see below). # Iterates the whole matrix for given number of times for _ in range(iterations): arr = np.take(init_val, ind) sum_product_rows = np.sum((-1) * no_diagonals * arr, axis=1) new_val = (sum_product_rows + val_last) / denominator init_val = new_val return new_val.tolist() # Checks if the given matrix is strictly diagonally dominant def strictly_diagonally_dominant(table: NDArray[float64]) -> bool: """ >>> table = np.array([[4, 1, 1, 2], [1, 5, 2, -6], [1, 2, 4, -4]]) >>> strictly_diagonally_dominant(table) True >>> table = np.array([[4, 1, 1, 2], [1, 5, 2, -6], [1, 2, 3, -4]]) >>> strictly_diagonally_dominant(table) Traceback (most recent call last): ... ValueError: Coefficient matrix is not strictly diagonally dominant """ rows, cols = table.shape is_diagonally_dominant = True for i in range(rows): total = 0 for j in range(cols - 1): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("Coefficient matrix is not strictly diagonally dominant") return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/linear_algebra/matrix_inversion.py
linear_algebra/matrix_inversion.py
import numpy as np def invert_matrix(matrix: list[list[float]]) -> list[list[float]]: """ Returns the inverse of a square matrix using NumPy. Parameters: matrix (list[list[float]]): A square matrix. Returns: list[list[float]]: Inverted matrix if invertible, else raises error. >>> invert_matrix([[4.0, 7.0], [2.0, 6.0]]) [[0.6000000000000001, -0.7000000000000001], [-0.2, 0.4]] >>> invert_matrix([[1.0, 2.0], [0.0, 0.0]]) Traceback (most recent call last): ... ValueError: Matrix is not invertible """ np_matrix = np.array(matrix) try: inv_matrix = np.linalg.inv(np_matrix) except np.linalg.LinAlgError: raise ValueError("Matrix is not invertible") return inv_matrix.tolist() if __name__ == "__main__": mat = [[4.0, 7.0], [2.0, 6.0]] print("Original Matrix:") print(mat) print("Inverted Matrix:") print(invert_matrix(mat))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/linear_algebra/__init__.py
linear_algebra/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/linear_algebra/lu_decomposition.py
linear_algebra/lu_decomposition.py
""" Lower-upper (LU) decomposition factors a matrix as a product of a lower triangular matrix and an upper triangular matrix. A square matrix has an LU decomposition under the following conditions: - If the matrix is invertible, then it has an LU decomposition if and only if all of its leading principal minors are non-zero (see https://en.wikipedia.org/wiki/Minor_(linear_algebra) for an explanation of leading principal minors of a matrix). - If the matrix is singular (i.e., not invertible) and it has a rank of k (i.e., it has k linearly independent columns), then it has an LU decomposition if its first k leading principal minors are non-zero. This algorithm will simply attempt to perform LU decomposition on any square matrix and raise an error if no such decomposition exists. Reference: https://en.wikipedia.org/wiki/LU_decomposition """ from __future__ import annotations import numpy as np def lower_upper_decomposition(table: np.ndarray) -> tuple[np.ndarray, np.ndarray]: """ Perform LU decomposition on a given matrix and raises an error if the matrix isn't square or if no such decomposition exists >>> matrix = np.array([[2, -2, 1], [0, 1, 2], [5, 3, 1]]) >>> lower_mat, upper_mat = lower_upper_decomposition(matrix) >>> lower_mat array([[1. , 0. , 0. ], [0. , 1. , 0. ], [2.5, 8. , 1. ]]) >>> upper_mat array([[ 2. , -2. , 1. ], [ 0. , 1. , 2. ], [ 0. , 0. , -17.5]]) >>> matrix = np.array([[4, 3], [6, 3]]) >>> lower_mat, upper_mat = lower_upper_decomposition(matrix) >>> lower_mat array([[1. , 0. ], [1.5, 1. ]]) >>> upper_mat array([[ 4. , 3. ], [ 0. , -1.5]]) >>> # Matrix is not square >>> matrix = np.array([[2, -2, 1], [0, 1, 2]]) >>> lower_mat, upper_mat = lower_upper_decomposition(matrix) Traceback (most recent call last): ... ValueError: 'table' has to be of square shaped array but got a 2x3 array: [[ 2 -2 1] [ 0 1 2]] >>> # Matrix is invertible, but its first leading principal minor is 0 >>> matrix = np.array([[0, 1], [1, 0]]) >>> lower_mat, upper_mat = lower_upper_decomposition(matrix) Traceback (most recent call last): ... ArithmeticError: No LU decomposition exists >>> # Matrix is singular, but its first leading principal minor is 1 >>> matrix = np.array([[1, 0], [1, 0]]) >>> lower_mat, upper_mat = lower_upper_decomposition(matrix) >>> lower_mat array([[1., 0.], [1., 1.]]) >>> upper_mat array([[1., 0.], [0., 0.]]) >>> # Matrix is singular, but its first leading principal minor is 0 >>> matrix = np.array([[0, 1], [0, 1]]) >>> lower_mat, upper_mat = lower_upper_decomposition(matrix) Traceback (most recent call last): ... ArithmeticError: No LU decomposition exists """ # Ensure that table is a square array rows, columns = np.shape(table) if rows != columns: msg = ( "'table' has to be of square shaped array but got a " f"{rows}x{columns} array:\n{table}" ) raise ValueError(msg) lower = np.zeros((rows, columns)) upper = np.zeros((rows, columns)) # in 'total', the necessary data is extracted through slices # and the sum of the products is obtained. for i in range(columns): for j in range(i): total = np.sum(lower[i, :i] * upper[:i, j]) if upper[j][j] == 0: raise ArithmeticError("No LU decomposition exists") lower[i][j] = (table[i][j] - total) / upper[j][j] lower[i][i] = 1 for j in range(i, columns): total = np.sum(lower[i, :i] * upper[:i, j]) upper[i][j] = table[i][j] - total return lower, upper if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/linear_algebra/src/lib.py
linear_algebra/src/lib.py
""" Created on Mon Feb 26 14:29:11 2018 @author: Christian Bender @license: MIT-license This module contains some useful classes and functions for dealing with linear algebra in python. Overview: - class Vector - function zero_vector(dimension) - function unit_basis_vector(dimension, pos) - function axpy(scalar, vector1, vector2) - function random_vector(N, a, b) - class Matrix - function square_zero_matrix(N) - function random_matrix(W, H, a, b) """ from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class Vector: """ This class represents a vector of arbitrary size. You need to give the vector components. Overview of the methods: __init__(components: Collection[float] | None): init the vector __len__(): gets the size of the vector (number of components) __str__(): returns a string representation __add__(other: Vector): vector addition __sub__(other: Vector): vector subtraction __mul__(other: float): scalar multiplication __mul__(other: Vector): dot product copy(): copies this vector and returns it component(i): gets the i-th component (0-indexed) change_component(pos: int, value: float): changes specified component euclidean_length(): returns the euclidean length of the vector angle(other: Vector, deg: bool): returns the angle between two vectors """ def __init__(self, components: Collection[float] | None = None) -> None: """ input: components or nothing simple constructor for init the vector """ if components is None: components = [] self.__components = list(components) def __len__(self) -> int: """ returns the size of the vector """ return len(self.__components) def __str__(self) -> str: """ returns a string representation of the vector """ return "(" + ",".join(map(str, self.__components)) + ")" def __add__(self, other: Vector) -> Vector: """ input: other vector assumes: other vector has the same size returns a new vector that represents the sum. """ size = len(self) if size == len(other): result = [self.__components[i] + other.component(i) for i in range(size)] return Vector(result) else: raise Exception("must have the same size") def __sub__(self, other: Vector) -> Vector: """ input: other vector assumes: other vector has the same size returns a new vector that represents the difference. """ size = len(self) if size == len(other): result = [self.__components[i] - other.component(i) for i in range(size)] return Vector(result) else: # error case raise Exception("must have the same size") def __eq__(self, other: object) -> bool: """ performs the comparison between two vectors """ if not isinstance(other, Vector): return NotImplemented if len(self) != len(other): return False return all(self.component(i) == other.component(i) for i in range(len(self))) @overload def __mul__(self, other: float) -> Vector: ... @overload def __mul__(self, other: Vector) -> float: ... def __mul__(self, other: float | Vector) -> float | Vector: """ mul implements the scalar multiplication and the dot-product """ if isinstance(other, (float, int)): ans = [c * other for c in self.__components] return Vector(ans) elif isinstance(other, Vector) and len(self) == len(other): size = len(self) prods = [self.__components[i] * other.component(i) for i in range(size)] return sum(prods) else: # error case raise Exception("invalid operand!") def copy(self) -> Vector: """ copies this vector and returns it. """ return Vector(self.__components) def component(self, i: int) -> float: """ input: index (0-indexed) output: the i-th component of the vector. """ if isinstance(i, int) and -len(self.__components) <= i < len(self.__components): return self.__components[i] else: raise Exception("index out of range") def change_component(self, pos: int, value: float) -> None: """ input: an index (pos) and a value changes the specified component (pos) with the 'value' """ # precondition assert -len(self.__components) <= pos < len(self.__components) self.__components[pos] = value def euclidean_length(self) -> float: """ returns the euclidean length of the vector >>> Vector([2, 3, 4]).euclidean_length() 5.385164807134504 >>> Vector([1]).euclidean_length() 1.0 >>> Vector([0, -1, -2, -3, 4, 5, 6]).euclidean_length() 9.539392014169456 >>> Vector([]).euclidean_length() Traceback (most recent call last): ... Exception: Vector is empty """ if len(self.__components) == 0: raise Exception("Vector is empty") squares = [c**2 for c in self.__components] return math.sqrt(sum(squares)) def angle(self, other: Vector, deg: bool = False) -> float: """ find angle between two Vector (self, Vector) >>> Vector([3, 4, -1]).angle(Vector([2, -1, 1])) 1.4906464636572374 >>> Vector([3, 4, -1]).angle(Vector([2, -1, 1]), deg = True) 85.40775111366095 >>> Vector([3, 4, -1]).angle(Vector([2, -1])) Traceback (most recent call last): ... Exception: invalid operand! """ num = self * other den = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den)) else: return math.acos(num / den) def zero_vector(dimension: int) -> Vector: """ returns a zero-vector of size 'dimension' """ # precondition assert isinstance(dimension, int) return Vector([0] * dimension) def unit_basis_vector(dimension: int, pos: int) -> Vector: """ returns a unit basis vector with a One at index 'pos' (indexing at 0) """ # precondition assert isinstance(dimension, int) assert isinstance(pos, int) ans = [0] * dimension ans[pos] = 1 return Vector(ans) def axpy(scalar: float, x: Vector, y: Vector) -> Vector: """ input: a 'scalar' and two vectors 'x' and 'y' output: a vector computes the axpy operation """ # precondition assert isinstance(x, Vector) assert isinstance(y, Vector) assert isinstance(scalar, (int, float)) return x * scalar + y def random_vector(n: int, a: int, b: int) -> Vector: """ input: size (N) of the vector. random range (a,b) output: returns a random vector of size N, with random integer components between 'a' and 'b'. """ random.seed(None) ans = [random.randint(a, b) for _ in range(n)] return Vector(ans) class Matrix: """ class: Matrix This class represents an arbitrary matrix. Overview of the methods: __init__(): __str__(): returns a string representation __add__(other: Matrix): matrix addition __sub__(other: Matrix): matrix subtraction __mul__(other: float): scalar multiplication __mul__(other: Vector): vector multiplication height() : returns height width() : returns width component(x: int, y: int): returns specified component change_component(x: int, y: int, value: float): changes specified component minor(x: int, y: int): returns minor along (x, y) cofactor(x: int, y: int): returns cofactor along (x, y) determinant() : returns determinant """ def __init__(self, matrix: list[list[float]], w: int, h: int) -> None: """ simple constructor for initializing the matrix with components. """ self.__matrix = matrix self.__width = w self.__height = h def __str__(self) -> str: """ returns a string representation of this matrix. """ ans = "" for i in range(self.__height): ans += "|" for j in range(self.__width): if j < self.__width - 1: ans += str(self.__matrix[i][j]) + "," else: ans += str(self.__matrix[i][j]) + "|\n" return ans def __add__(self, other: Matrix) -> Matrix: """ implements matrix addition. """ if self.__width == other.width() and self.__height == other.height(): matrix = [] for i in range(self.__height): row = [ self.__matrix[i][j] + other.component(i, j) for j in range(self.__width) ] matrix.append(row) return Matrix(matrix, self.__width, self.__height) else: raise Exception("matrix must have the same dimension!") def __sub__(self, other: Matrix) -> Matrix: """ implements matrix subtraction. """ if self.__width == other.width() and self.__height == other.height(): matrix = [] for i in range(self.__height): row = [ self.__matrix[i][j] - other.component(i, j) for j in range(self.__width) ] matrix.append(row) return Matrix(matrix, self.__width, self.__height) else: raise Exception("matrices must have the same dimension!") @overload def __mul__(self, other: float) -> Matrix: ... @overload def __mul__(self, other: Vector) -> Vector: ... def __mul__(self, other: float | Vector) -> Vector | Matrix: """ implements the matrix-vector multiplication. implements the matrix-scalar multiplication """ if isinstance(other, Vector): # matrix-vector if len(other) == self.__width: ans = zero_vector(self.__height) for i in range(self.__height): prods = [ self.__matrix[i][j] * other.component(j) for j in range(self.__width) ] ans.change_component(i, sum(prods)) return ans else: raise Exception( "vector must have the same size as the " "number of columns of the matrix!" ) elif isinstance(other, (int, float)): # matrix-scalar matrix = [ [self.__matrix[i][j] * other for j in range(self.__width)] for i in range(self.__height) ] return Matrix(matrix, self.__width, self.__height) return None def height(self) -> int: """ getter for the height """ return self.__height def width(self) -> int: """ getter for the width """ return self.__width def component(self, x: int, y: int) -> float: """ returns the specified (x,y) component """ if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception("change_component: indices out of bounds") def change_component(self, x: int, y: int, value: float) -> None: """ changes the x-y component of this matrix """ if 0 <= x < self.__height and 0 <= y < self.__width: self.__matrix[x][y] = value else: raise Exception("change_component: indices out of bounds") def minor(self, x: int, y: int) -> float: """ returns the minor along (x, y) """ if self.__height != self.__width: raise Exception("Matrix is not square") minor = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(minor)): minor[i] = minor[i][:y] + minor[i][y + 1 :] return Matrix(minor, self.__width - 1, self.__height - 1).determinant() def cofactor(self, x: int, y: int) -> float: """ returns the cofactor (signed minor) along (x, y) """ if self.__height != self.__width: raise Exception("Matrix is not square") if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(x, y) else: raise Exception("Indices out of bounds") def determinant(self) -> float: """ returns the determinant of an nxn matrix using Laplace expansion """ if self.__height != self.__width: raise Exception("Matrix is not square") if self.__height < 1: raise Exception("Matrix has no element") elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: cofactor_prods = [ self.__matrix[0][y] * self.cofactor(0, y) for y in range(self.__width) ] return sum(cofactor_prods) def square_zero_matrix(n: int) -> Matrix: """ returns a square zero-matrix of dimension NxN """ ans: list[list[float]] = [[0] * n for _ in range(n)] return Matrix(ans, n, n) def random_matrix(width: int, height: int, a: int, b: int) -> Matrix: """ returns a random matrix WxH with integer components between 'a' and 'b' """ random.seed(None) matrix: list[list[float]] = [ [random.randint(a, b) for _ in range(width)] for _ in range(height) ] return Matrix(matrix, width, height)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/linear_algebra/src/rayleigh_quotient.py
linear_algebra/src/rayleigh_quotient.py
""" https://en.wikipedia.org/wiki/Rayleigh_quotient """ from typing import Any import numpy as np def is_hermitian(matrix: np.ndarray) -> bool: """ Checks if a matrix is Hermitian. >>> import numpy as np >>> A = np.array([ ... [2, 2+1j, 4], ... [2-1j, 3, 1j], ... [4, -1j, 1]]) >>> is_hermitian(A) True >>> A = np.array([ ... [2, 2+1j, 4+1j], ... [2-1j, 3, 1j], ... [4, -1j, 1]]) >>> is_hermitian(A) False """ return np.array_equal(matrix, matrix.conjugate().T) def rayleigh_quotient(a: np.ndarray, v: np.ndarray) -> Any: """ Returns the Rayleigh quotient of a Hermitian matrix A and vector v. >>> import numpy as np >>> A = np.array([ ... [1, 2, 4], ... [2, 3, -1], ... [4, -1, 1] ... ]) >>> v = np.array([ ... [1], ... [2], ... [3] ... ]) >>> rayleigh_quotient(A, v) array([[3.]]) """ v_star = v.conjugate().T v_star_dot = v_star.dot(a) assert isinstance(v_star_dot, np.ndarray) return (v_star_dot.dot(v)) / (v_star.dot(v)) def tests() -> None: a = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]]) v = np.array([[1], [2], [3]]) assert is_hermitian(a), f"{a} is not hermitian." print(rayleigh_quotient(a, v)) a = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]]) assert is_hermitian(a), f"{a} is not hermitian." assert rayleigh_quotient(a, v) == float(3) if __name__ == "__main__": import doctest doctest.testmod() tests()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/linear_algebra/src/power_iteration.py
linear_algebra/src/power_iteration.py
import numpy as np def power_iteration( input_matrix: np.ndarray, vector: np.ndarray, error_tol: float = 1e-12, max_iterations: int = 100, ) -> tuple[float, np.ndarray]: """ Power Iteration. Find the largest eigenvalue and corresponding eigenvector of matrix input_matrix given a random vector in the same space. Will work so long as vector has component of largest eigenvector. input_matrix must be either real or Hermitian. Input input_matrix: input matrix whose largest eigenvalue we will find. Numpy array. np.shape(input_matrix) == (N,N). vector: random initial vector in same space as matrix. Numpy array. np.shape(vector) == (N,) or (N,1) Output largest_eigenvalue: largest eigenvalue of the matrix input_matrix. Float. Scalar. largest_eigenvector: eigenvector corresponding to largest_eigenvalue. Numpy array. np.shape(largest_eigenvector) == (N,) or (N,1). >>> import numpy as np >>> input_matrix = np.array([ ... [41, 4, 20], ... [ 4, 26, 30], ... [20, 30, 50] ... ]) >>> vector = np.array([41,4,20]) >>> power_iteration(input_matrix,vector) (79.66086378788381, array([0.44472726, 0.46209842, 0.76725662])) """ # Ensure matrix is square. assert np.shape(input_matrix)[0] == np.shape(input_matrix)[1] # Ensure proper dimensionality. assert np.shape(input_matrix)[0] == np.shape(vector)[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(input_matrix) == np.iscomplexobj(vector) is_complex = np.iscomplexobj(input_matrix) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(input_matrix, input_matrix.conj().T) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. convergence = False lambda_previous = 0 iterations = 0 error = 1e12 while not convergence: # Multiple matrix by the vector. w = np.dot(input_matrix, vector) # Normalize the resulting output vector. vector = w / np.linalg.norm(w) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) vector_h = vector.conj().T if is_complex else vector.T lambda_ = np.dot(vector_h, np.dot(input_matrix, vector)) # Check convergence. error = np.abs(lambda_ - lambda_previous) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: convergence = True lambda_previous = lambda_ if is_complex: lambda_ = np.real(lambda_) return float(lambda_), vector def test_power_iteration() -> None: """ >>> test_power_iteration() # self running tests """ real_input_matrix = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]) real_vector = np.array([41, 4, 20]) complex_input_matrix = real_input_matrix.astype(np.complex128) imag_matrix = np.triu(1j * complex_input_matrix, 1) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T complex_vector = np.array([41, 4, 20]).astype(np.complex128) for problem_type in ["real", "complex"]: if problem_type == "real": input_matrix = real_input_matrix vector = real_vector elif problem_type == "complex": input_matrix = complex_input_matrix vector = complex_vector # Our implementation. eigen_value, eigen_vector = power_iteration(input_matrix, vector) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). eigen_values, eigen_vectors = np.linalg.eigh(input_matrix) # Last eigenvalue is the maximum one. eigen_value_max = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. eigen_vector_max = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max) <= 1e-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(eigen_vector) - np.abs(eigen_vector_max)) <= 1e-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/linear_algebra/src/conjugate_gradient.py
linear_algebra/src/conjugate_gradient.py
""" Resources: - https://en.wikipedia.org/wiki/Conjugate_gradient_method - https://en.wikipedia.org/wiki/Definite_symmetric_matrix """ from typing import Any import numpy as np def _is_matrix_spd(matrix: np.ndarray) -> bool: """ Returns True if input matrix is symmetric positive definite. Returns False otherwise. For a matrix to be SPD, all eigenvalues must be positive. >>> import numpy as np >>> matrix = np.array([ ... [4.12401784, -5.01453636, -0.63865857], ... [-5.01453636, 12.33347422, -3.40493586], ... [-0.63865857, -3.40493586, 5.78591885]]) >>> _is_matrix_spd(matrix) True >>> matrix = np.array([ ... [0.34634879, 1.96165514, 2.18277744], ... [0.74074469, -1.19648894, -1.34223498], ... [-0.7687067 , 0.06018373, -1.16315631]]) >>> _is_matrix_spd(matrix) False """ # Ensure matrix is square. assert np.shape(matrix)[0] == np.shape(matrix)[1] # If matrix not symmetric, exit right away. if np.allclose(matrix, matrix.T) is False: return False # Get eigenvalues and eignevectors for a symmetric matrix. eigen_values, _ = np.linalg.eigh(matrix) # Check sign of all eigenvalues. # np.all returns a value of type np.bool_ return bool(np.all(eigen_values > 0)) def _create_spd_matrix(dimension: int) -> Any: """ Returns a symmetric positive definite matrix given a dimension. Input: dimension gives the square matrix dimension. Output: spd_matrix is an diminesion x dimensions symmetric positive definite (SPD) matrix. >>> import numpy as np >>> dimension = 3 >>> spd_matrix = _create_spd_matrix(dimension) >>> _is_matrix_spd(spd_matrix) True """ rng = np.random.default_rng() random_matrix = rng.normal(size=(dimension, dimension)) spd_matrix = np.dot(random_matrix, random_matrix.T) assert _is_matrix_spd(spd_matrix) return spd_matrix def conjugate_gradient( spd_matrix: np.ndarray, load_vector: np.ndarray, max_iterations: int = 1000, tol: float = 1e-8, ) -> Any: """ Returns solution to the linear system np.dot(spd_matrix, x) = b. Input: spd_matrix is an NxN Symmetric Positive Definite (SPD) matrix. load_vector is an Nx1 vector. Output: x is an Nx1 vector that is the solution vector. >>> import numpy as np >>> spd_matrix = np.array([ ... [8.73256573, -5.02034289, -2.68709226], ... [-5.02034289, 3.78188322, 0.91980451], ... [-2.68709226, 0.91980451, 1.94746467]]) >>> b = np.array([ ... [-5.80872761], ... [ 3.23807431], ... [ 1.95381422]]) >>> conjugate_gradient(spd_matrix, b) array([[-0.63114139], [-0.01561498], [ 0.13979294]]) """ # Ensure proper dimensionality. assert np.shape(spd_matrix)[0] == np.shape(spd_matrix)[1] assert np.shape(load_vector)[0] == np.shape(spd_matrix)[0] assert _is_matrix_spd(spd_matrix) # Initialize solution guess, residual, search direction. x0 = np.zeros((np.shape(load_vector)[0], 1)) r0 = np.copy(load_vector) p0 = np.copy(r0) # Set initial errors in solution guess and residual. error_residual = 1e9 error_x_solution = 1e9 error = 1e9 # Set iteration counter to threshold number of iterations. iterations = 0 while error > tol: # Save this value so we only calculate the matrix-vector product once. w = np.dot(spd_matrix, p0) # The main algorithm. # Update search direction magnitude. alpha = np.dot(r0.T, r0) / np.dot(p0.T, w) # Update solution guess. x = x0 + alpha * p0 # Calculate new residual. r = r0 - alpha * w # Calculate new Krylov subspace scale. beta = np.dot(r.T, r) / np.dot(r0.T, r0) # Calculate new A conjuage search direction. p = r + beta * p0 # Calculate errors. error_residual = np.linalg.norm(r - r0) error_x_solution = np.linalg.norm(x - x0) error = np.maximum(error_residual, error_x_solution) # Update variables. x0 = np.copy(x) r0 = np.copy(r) p0 = np.copy(p) # Update number of iterations. iterations += 1 if iterations > max_iterations: break return x def test_conjugate_gradient() -> None: """ >>> test_conjugate_gradient() # self running tests """ # Create linear system with SPD matrix and known solution x_true. dimension = 3 spd_matrix = _create_spd_matrix(dimension) rng = np.random.default_rng() x_true = rng.normal(size=(dimension, 1)) b = np.dot(spd_matrix, x_true) # Numpy solution. x_numpy = np.linalg.solve(spd_matrix, b) # Our implementation. x_conjugate_gradient = conjugate_gradient(spd_matrix, b) # Ensure both solutions are close to x_true (and therefore one another). assert np.linalg.norm(x_numpy - x_true) <= 1e-6 assert np.linalg.norm(x_conjugate_gradient - x_true) <= 1e-6 if __name__ == "__main__": import doctest doctest.testmod() test_conjugate_gradient()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/linear_algebra/src/schur_complement.py
linear_algebra/src/schur_complement.py
import unittest import numpy as np import pytest def schur_complement( mat_a: np.ndarray, mat_b: np.ndarray, mat_c: np.ndarray, pseudo_inv: np.ndarray | None = None, ) -> np.ndarray: """ Schur complement of a symmetric matrix X given as a 2x2 block matrix consisting of matrices `A`, `B` and `C`. Matrix `A` must be quadratic and non-singular. In case `A` is singular, a pseudo-inverse may be provided using the `pseudo_inv` argument. | Link to Wiki: https://en.wikipedia.org/wiki/Schur_complement | See also Convex Optimization - Boyd and Vandenberghe, A.5.5 >>> import numpy as np >>> a = np.array([[1, 2], [2, 1]]) >>> b = np.array([[0, 3], [3, 0]]) >>> c = np.array([[2, 1], [6, 3]]) >>> schur_complement(a, b, c) array([[ 5., -5.], [ 0., 6.]]) """ shape_a = np.shape(mat_a) shape_b = np.shape(mat_b) shape_c = np.shape(mat_c) if shape_a[0] != shape_b[0]: msg = ( "Expected the same number of rows for A and B. " f"Instead found A of size {shape_a} and B of size {shape_b}" ) raise ValueError(msg) if shape_b[1] != shape_c[1]: msg = ( "Expected the same number of columns for B and C. " f"Instead found B of size {shape_b} and C of size {shape_c}" ) raise ValueError(msg) a_inv = pseudo_inv if a_inv is None: try: a_inv = np.linalg.inv(mat_a) except np.linalg.LinAlgError: raise ValueError( "Input matrix A is not invertible. Cannot compute Schur complement." ) return mat_c - mat_b.T @ a_inv @ mat_b class TestSchurComplement(unittest.TestCase): def test_schur_complement(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1], [6, 3]]) s = schur_complement(a, b, c) input_matrix = np.block([[a, b], [b.T, c]]) det_x = np.linalg.det(input_matrix) det_a = np.linalg.det(a) det_s = np.linalg.det(s) assert np.is_close(det_x, det_a * det_s) def test_improper_a_b_dimensions(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1], [6, 3]]) with pytest.raises(ValueError): schur_complement(a, b, c) def test_improper_b_c_dimensions(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1, 3], [6, 3, 5]]) with pytest.raises(ValueError): schur_complement(a, b, c) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/linear_algebra/src/rank_of_matrix.py
linear_algebra/src/rank_of_matrix.py
""" Calculate the rank of a matrix. See: https://en.wikipedia.org/wiki/Rank_(linear_algebra) """ def rank_of_matrix(matrix: list[list[int | float]]) -> int: """ Finds the rank of a matrix. Args: `matrix`: The matrix as a list of lists. Returns: The rank of the matrix. Example: >>> matrix1 = [[1, 2, 3], ... [4, 5, 6], ... [7, 8, 9]] >>> rank_of_matrix(matrix1) 2 >>> matrix2 = [[1, 0, 0], ... [0, 1, 0], ... [0, 0, 0]] >>> rank_of_matrix(matrix2) 2 >>> matrix3 = [[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12]] >>> rank_of_matrix(matrix3) 2 >>> rank_of_matrix([[2,3,-1,-1], ... [1,-1,-2,4], ... [3,1,3,-2], ... [6,3,0,-7]]) 4 >>> rank_of_matrix([[2,1,-3,-6], ... [3,-3,1,2], ... [1,1,1,2]]) 3 >>> rank_of_matrix([[2,-1,0], ... [1,3,4], ... [4,1,-3]]) 3 >>> rank_of_matrix([[3,2,1], ... [-6,-4,-2]]) 1 >>> rank_of_matrix([[],[]]) 0 >>> rank_of_matrix([[1]]) 1 >>> rank_of_matrix([[]]) 0 """ rows = len(matrix) columns = len(matrix[0]) rank = min(rows, columns) for row in range(rank): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1, rows): multiplier = matrix[col][row] / matrix[row][row] for i in range(row, columns): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows reduce = True for i in range(row + 1, rows): if matrix[i][row] != 0: matrix[row], matrix[i] = matrix[i], matrix[row] reduce = False break if reduce: rank -= 1 for i in range(rows): matrix[i][row] = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/linear_algebra/src/test_linear_algebra.py
linear_algebra/src/test_linear_algebra.py
""" Created on Mon Feb 26 15:40:07 2018 @author: Christian Bender @license: MIT-license This file contains the test-suite for the linear algebra library. """ import unittest import pytest from .lib import ( Matrix, Vector, axpy, square_zero_matrix, unit_basis_vector, zero_vector, ) class Test(unittest.TestCase): def test_component(self) -> None: """ test for method component() """ x = Vector([1, 2, 3]) assert x.component(0) == 1 assert x.component(2) == 3 _ = Vector() def test_str(self) -> None: """ test for method toString() """ x = Vector([0, 0, 0, 0, 0, 1]) assert str(x) == "(0,0,0,0,0,1)" def test_size(self) -> None: """ test for method size() """ x = Vector([1, 2, 3, 4]) assert len(x) == 4 def test_euclidean_length(self) -> None: """ test for method euclidean_length() """ x = Vector([1, 2]) y = Vector([1, 2, 3, 4, 5]) z = Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) w = Vector([1, -1, 1, -1, 2, -3, 4, -5]) assert x.euclidean_length() == pytest.approx(2.236, abs=1e-3) assert y.euclidean_length() == pytest.approx(7.416, abs=1e-3) assert z.euclidean_length() == 0 assert w.euclidean_length() == pytest.approx(7.616, abs=1e-3) def test_add(self) -> None: """ test for + operator """ x = Vector([1, 2, 3]) y = Vector([1, 1, 1]) assert (x + y).component(0) == 2 assert (x + y).component(1) == 3 assert (x + y).component(2) == 4 def test_sub(self) -> None: """ test for - operator """ x = Vector([1, 2, 3]) y = Vector([1, 1, 1]) assert (x - y).component(0) == 0 assert (x - y).component(1) == 1 assert (x - y).component(2) == 2 def test_mul(self) -> None: """ test for * operator """ x = Vector([1, 2, 3]) a = Vector([2, -1, 4]) # for test of dot product b = Vector([1, -2, -1]) assert str(x * 3.0) == "(3.0,6.0,9.0)" assert a * b == 0 def test_zero_vector(self) -> None: """ test for global function zero_vector() """ assert str(zero_vector(10)).count("0") == 10 def test_unit_basis_vector(self) -> None: """ test for global function unit_basis_vector() """ assert str(unit_basis_vector(3, 1)) == "(0,1,0)" def test_axpy(self) -> None: """ test for global function axpy() (operation) """ x = Vector([1, 2, 3]) y = Vector([1, 0, 1]) assert str(axpy(2, x, y)) == "(3,4,7)" def test_copy(self) -> None: """ test for method copy() """ x = Vector([1, 0, 0, 0, 0, 0]) y = x.copy() assert str(x) == str(y) def test_change_component(self) -> None: """ test for method change_component() """ x = Vector([1, 0, 0]) x.change_component(0, 0) x.change_component(1, 1) assert str(x) == "(0,1,0)" def test_str_matrix(self) -> None: """ test for Matrix method str() """ a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) assert str(a) == "|1,2,3|\n|2,4,5|\n|6,7,8|\n" def test_minor(self) -> None: """ test for Matrix method minor() """ a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) minors = [[-3, -14, -10], [-5, -10, -5], [-2, -1, 0]] for x in range(a.height()): for y in range(a.width()): assert minors[x][y] == a.minor(x, y) def test_cofactor(self) -> None: """ test for Matrix method cofactor() """ a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) cofactors = [[-3, 14, -10], [5, -10, 5], [-2, 1, 0]] for x in range(a.height()): for y in range(a.width()): assert cofactors[x][y] == a.cofactor(x, y) def test_determinant(self) -> None: """ test for Matrix method determinant() """ a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) assert a.determinant() == -5 def test__mul__matrix(self) -> None: """ test for Matrix * operator """ a = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3, 3) x = Vector([1, 2, 3]) assert str(a * x) == "(14,32,50)" assert str(a * 2) == "|2,4,6|\n|8,10,12|\n|14,16,18|\n" def test_change_component_matrix(self) -> None: """ test for Matrix method change_component() """ a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) a.change_component(0, 2, 5) assert str(a) == "|1,2,5|\n|2,4,5|\n|6,7,8|\n" def test_component_matrix(self) -> None: """ test for Matrix method component() """ a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) assert a.component(2, 1) == 7, "0.01" def test__add__matrix(self) -> None: """ test for Matrix + operator """ a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) b = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]], 3, 3) assert str(a + b) == "|2,4,10|\n|4,8,10|\n|12,14,18|\n" def test__sub__matrix(self) -> None: """ test for Matrix - operator """ a = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3) b = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]], 3, 3) assert str(a - b) == "|0,0,-4|\n|0,0,0|\n|0,0,-2|\n" def test_square_zero_matrix(self) -> None: """ test for global function square_zero_matrix() """ assert str(square_zero_matrix(5)) == ( "|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n" ) if __name__ == "__main__": unittest.main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/linear_algebra/src/transformations_2d.py
linear_algebra/src/transformations_2d.py
""" 2D Transformations are regularly used in Linear Algebra. I have added the codes for reflection, projection, scaling and rotation 2D matrices. .. code-block:: python scaling(5) = [[5.0, 0.0], [0.0, 5.0]] rotation(45) = [[0.5253219888177297, -0.8509035245341184], [0.8509035245341184, 0.5253219888177297]] projection(45) = [[0.27596319193541496, 0.446998331800279], [0.446998331800279, 0.7240368080645851]] reflection(45) = [[0.05064397763545947, 0.893996663600558], [0.893996663600558, 0.7018070490682369]] """ from math import cos, sin def scaling(scaling_factor: float) -> list[list[float]]: """ >>> scaling(5) [[5.0, 0.0], [0.0, 5.0]] """ scaling_factor = float(scaling_factor) return [[scaling_factor * int(x == y) for x in range(2)] for y in range(2)] def rotation(angle: float) -> list[list[float]]: """ >>> rotation(45) # doctest: +NORMALIZE_WHITESPACE [[0.5253219888177297, -0.8509035245341184], [0.8509035245341184, 0.5253219888177297]] """ c, s = cos(angle), sin(angle) return [[c, -s], [s, c]] def projection(angle: float) -> list[list[float]]: """ >>> projection(45) # doctest: +NORMALIZE_WHITESPACE [[0.27596319193541496, 0.446998331800279], [0.446998331800279, 0.7240368080645851]] """ c, s = cos(angle), sin(angle) cs = c * s return [[c * c, cs], [cs, s * s]] def reflection(angle: float) -> list[list[float]]: """ >>> reflection(45) # doctest: +NORMALIZE_WHITESPACE [[0.05064397763545947, 0.893996663600558], [0.893996663600558, 0.7018070490682369]] """ c, s = cos(angle), sin(angle) cs = c * s return [[2 * c - 1, 2 * cs], [2 * cs, 2 * s - 1]] print(f" {scaling(5) = }") print(f" {rotation(45) = }") print(f"{projection(45) = }") print(f"{reflection(45) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/linear_algebra/src/polynom_for_points.py
linear_algebra/src/polynom_for_points.py
def points_to_polynomial(coordinates: list[list[int]]) -> str: """ coordinates is a two dimensional matrix: [[x, y], [x, y], ...] number of points you want to use >>> points_to_polynomial([]) Traceback (most recent call last): ... ValueError: The program cannot work out a fitting polynomial. >>> points_to_polynomial([[]]) Traceback (most recent call last): ... ValueError: The program cannot work out a fitting polynomial. >>> points_to_polynomial([[1, 0], [2, 0], [3, 0]]) 'f(x)=x^2*0.0+x^1*-0.0+x^0*0.0' >>> points_to_polynomial([[1, 1], [2, 1], [3, 1]]) 'f(x)=x^2*0.0+x^1*-0.0+x^0*1.0' >>> points_to_polynomial([[1, 3], [2, 3], [3, 3]]) 'f(x)=x^2*0.0+x^1*-0.0+x^0*3.0' >>> points_to_polynomial([[1, 1], [2, 2], [3, 3]]) 'f(x)=x^2*0.0+x^1*1.0+x^0*0.0' >>> points_to_polynomial([[1, 1], [2, 4], [3, 9]]) 'f(x)=x^2*1.0+x^1*-0.0+x^0*0.0' >>> points_to_polynomial([[1, 3], [2, 6], [3, 11]]) 'f(x)=x^2*1.0+x^1*-0.0+x^0*2.0' >>> points_to_polynomial([[1, -3], [2, -6], [3, -11]]) 'f(x)=x^2*-1.0+x^1*-0.0+x^0*-2.0' >>> points_to_polynomial([[1, 5], [2, 2], [3, 9]]) 'f(x)=x^2*5.0+x^1*-18.0+x^0*18.0' >>> points_to_polynomial([[1, 1], [1, 2], [1, 3]]) 'x=1' >>> points_to_polynomial([[1, 1], [2, 2], [2, 2]]) Traceback (most recent call last): ... ValueError: The program cannot work out a fitting polynomial. """ if len(coordinates) == 0 or not all(len(pair) == 2 for pair in coordinates): raise ValueError("The program cannot work out a fitting polynomial.") if len({tuple(pair) for pair in coordinates}) != len(coordinates): raise ValueError("The program cannot work out a fitting polynomial.") set_x = {x for x, _ in coordinates} if len(set_x) == 1: return f"x={coordinates[0][0]}" if len(set_x) != len(coordinates): raise ValueError("The program cannot work out a fitting polynomial.") x = len(coordinates) # put the x and x to the power values in a matrix matrix: list[list[float]] = [ [ coordinates[count_of_line][0] ** (x - (count_in_line + 1)) for count_in_line in range(x) ] for count_of_line in range(x) ] # put the y values into a vector vector: list[float] = [coordinates[count_of_line][1] for count_of_line in range(x)] for count in range(x): for number in range(x): if count == number: continue fraction = matrix[number][count] / matrix[count][count] for counting_columns, item in enumerate(matrix[count]): # manipulating all the values in the matrix matrix[number][counting_columns] -= item * fraction # manipulating the values in the vector vector[number] -= vector[count] * fraction # make solutions solution: list[str] = [ str(vector[count] / matrix[count][count]) for count in range(x) ] solved = "f(x)=" for count in range(x): remove_e: list[str] = solution[count].split("E") if len(remove_e) > 1: solution[count] = f"{remove_e[0]}*10^{remove_e[1]}" solved += f"x^{x - (count + 1)}*{solution[count]}" if count + 1 != x: solved += "+" return solved if __name__ == "__main__": print(points_to_polynomial([])) print(points_to_polynomial([[]])) print(points_to_polynomial([[1, 0], [2, 0], [3, 0]])) print(points_to_polynomial([[1, 1], [2, 1], [3, 1]])) print(points_to_polynomial([[1, 3], [2, 3], [3, 3]])) print(points_to_polynomial([[1, 1], [2, 2], [3, 3]])) print(points_to_polynomial([[1, 1], [2, 4], [3, 9]])) print(points_to_polynomial([[1, 3], [2, 6], [3, 11]])) print(points_to_polynomial([[1, -3], [2, -6], [3, -11]])) print(points_to_polynomial([[1, 5], [2, 2], [3, 9]]))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/linear_algebra/src/__init__.py
linear_algebra/src/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/linear_algebra/src/gaussian_elimination_pivoting.py
linear_algebra/src/gaussian_elimination_pivoting.py
import numpy as np def solve_linear_system(matrix: np.ndarray) -> np.ndarray: """ Solve a linear system of equations using Gaussian elimination with partial pivoting Args: - `matrix`: Coefficient matrix with the last column representing the constants. Returns: - Solution vector. Raises: - ``ValueError``: If the matrix is not correct (i.e., singular). https://courses.engr.illinois.edu/cs357/su2013/lect.htm Lecture 7 Example: >>> A = np.array([[2, 1, -1], [-3, -1, 2], [-2, 1, 2]], dtype=float) >>> B = np.array([8, -11, -3], dtype=float) >>> solution = solve_linear_system(np.column_stack((A, B))) >>> np.allclose(solution, np.array([2., 3., -1.])) True >>> solve_linear_system(np.array([[0, 0, 0]], dtype=float)) Traceback (most recent call last): ... ValueError: Matrix is not square >>> solve_linear_system(np.array([[0, 0, 0], [0, 0, 0]], dtype=float)) Traceback (most recent call last): ... ValueError: Matrix is singular """ ab = np.copy(matrix) num_of_rows = ab.shape[0] num_of_columns = ab.shape[1] - 1 x_lst: list[float] = [] if num_of_rows != num_of_columns: raise ValueError("Matrix is not square") for column_num in range(num_of_rows): # Lead element search for i in range(column_num, num_of_columns): if abs(ab[i][column_num]) > abs(ab[column_num][column_num]): ab[[column_num, i]] = ab[[i, column_num]] # Upper triangular matrix if abs(ab[column_num, column_num]) < 1e-8: raise ValueError("Matrix is singular") if column_num != 0: for i in range(column_num, num_of_rows): ab[i, :] -= ( ab[i, column_num - 1] / ab[column_num - 1, column_num - 1] * ab[column_num - 1, :] ) # Find x vector (Back Substitution) for column_num in range(num_of_rows - 1, -1, -1): x = ab[column_num, -1] / ab[column_num, column_num] x_lst.insert(0, x) for i in range(column_num - 1, -1, -1): ab[i, -1] -= ab[i, column_num] * x # Return the solution vector return np.asarray(x_lst) if __name__ == "__main__": from doctest import testmod testmod() example_matrix = np.array( [ [5.0, -5.0, -3.0, 4.0, -11.0], [1.0, -4.0, 6.0, -4.0, -10.0], [-2.0, -5.0, 4.0, -5.0, -12.0], [-3.0, -3.0, 5.0, -5.0, 8.0], ], dtype=float, ) print(f"Matrix:\n{example_matrix}") print(f"{solve_linear_system(example_matrix) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/sherman_morrison.py
matrix/sherman_morrison.py
from __future__ import annotations from typing import Any class Matrix: """ <class Matrix> Matrix structure. """ def __init__(self, row: int, column: int, default_value: float = 0) -> None: """ <method Matrix.__init__> Initialize matrix with given size and default value. Example: >>> a = Matrix(2, 3, 1) >>> a Matrix consist of 2 rows and 3 columns [1, 1, 1] [1, 1, 1] """ self.row, self.column = row, column self.array = [[default_value for _ in range(column)] for _ in range(row)] def __str__(self) -> str: """ <method Matrix.__str__> Return string representation of this matrix. """ # Prefix s = f"Matrix consist of {self.row} rows and {self.column} columns\n" # Make string identifier max_element_length = 0 for row_vector in self.array: for obj in row_vector: max_element_length = max(max_element_length, len(str(obj))) string_format_identifier = f"%{max_element_length}s" # Make string and return def single_line(row_vector: list[float]) -> str: nonlocal string_format_identifier line = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector) line += "]" return line s += "\n".join(single_line(row_vector) for row_vector in self.array) return s def __repr__(self) -> str: return str(self) def validate_indices(self, loc: tuple[int, int]) -> bool: """ <method Matrix.validate_indicies> Check if given indices are valid to pick element from matrix. Example: >>> a = Matrix(2, 6, 0) >>> a.validate_indices((2, 7)) False >>> a.validate_indices((0, 0)) True """ if not (isinstance(loc, (list, tuple)) and len(loc) == 2): # noqa: SIM114 return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__(self, loc: tuple[int, int]) -> Any: """ <method Matrix.__getitem__> Return array[row][column] where loc = (row, column). Example: >>> a = Matrix(3, 2, 7) >>> a[1, 0] 7 """ assert self.validate_indices(loc) return self.array[loc[0]][loc[1]] def __setitem__(self, loc: tuple[int, int], value: float) -> None: """ <method Matrix.__setitem__> Set array[row][column] = value where loc = (row, column). Example: >>> a = Matrix(2, 3, 1) >>> a[1, 2] = 51 >>> a Matrix consist of 2 rows and 3 columns [ 1, 1, 1] [ 1, 1, 51] """ assert self.validate_indices(loc) self.array[loc[0]][loc[1]] = value def __add__(self, another: Matrix) -> Matrix: """ <method Matrix.__add__> Return self + another. Example: >>> a = Matrix(2, 1, -4) >>> b = Matrix(2, 1, 3) >>> a+b Matrix consist of 2 rows and 1 columns [-1] [-1] """ # Validation assert isinstance(another, Matrix) assert self.row == another.row assert self.column == another.column # Add result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = self[r, c] + another[r, c] return result def __neg__(self) -> Matrix: """ <method Matrix.__neg__> Return -self. Example: >>> a = Matrix(2, 2, 3) >>> a[0, 1] = a[1, 0] = -2 >>> -a Matrix consist of 2 rows and 2 columns [-3, 2] [ 2, -3] """ result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = -self[r, c] return result def __sub__(self, another: Matrix) -> Matrix: return self + (-another) def __mul__(self, another: float | Matrix) -> Matrix: """ <method Matrix.__mul__> Return self * another. Example: >>> a = Matrix(2, 3, 1) >>> a[0,2] = a[1,2] = 3 >>> a * -2 Matrix consist of 2 rows and 3 columns [-2, -2, -6] [-2, -2, -6] """ if isinstance(another, (int, float)): # Scalar multiplication result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = self[r, c] * another return result elif isinstance(another, Matrix): # Matrix multiplication assert self.column == another.row result = Matrix(self.row, another.column) for r in range(self.row): for c in range(another.column): for i in range(self.column): result[r, c] += self[r, i] * another[i, c] return result else: msg = f"Unsupported type given for another ({type(another)})" raise TypeError(msg) def transpose(self) -> Matrix: """ <method Matrix.transpose> Return self^T. Example: >>> a = Matrix(2, 3) >>> for r in range(2): ... for c in range(3): ... a[r,c] = r*c ... >>> a.transpose() Matrix consist of 3 rows and 2 columns [0, 0] [0, 1] [0, 2] """ result = Matrix(self.column, self.row) for r in range(self.row): for c in range(self.column): result[c, r] = self[r, c] return result def sherman_morrison(self, u: Matrix, v: Matrix) -> Any: """ <method Matrix.sherman_morrison> Apply Sherman-Morrison formula in O(n^2). To learn this formula, please look this: https://en.wikipedia.org/wiki/Sherman%E2%80%93Morrison_formula This method returns (A + uv^T)^(-1) where A^(-1) is self. Returns None if it's impossible to calculate. Warning: This method doesn't check if self is invertible. Make sure self is invertible before execute this method. Example: >>> ainv = Matrix(3, 3, 0) >>> for i in range(3): ainv[i,i] = 1 ... >>> u = Matrix(3, 1, 0) >>> u[0,0], u[1,0], u[2,0] = 1, 2, -3 >>> v = Matrix(3, 1, 0) >>> v[0,0], v[1,0], v[2,0] = 4, -2, 5 >>> ainv.sherman_morrison(u, v) Matrix consist of 3 rows and 3 columns [ 1.2857142857142856, -0.14285714285714285, 0.3571428571428571] [ 0.5714285714285714, 0.7142857142857143, 0.7142857142857142] [ -0.8571428571428571, 0.42857142857142855, -0.0714285714285714] """ # Size validation assert isinstance(u, Matrix) assert isinstance(v, Matrix) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate v_t = v.transpose() numerator_factor = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertible return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def test1() -> None: # a^(-1) ainv = Matrix(3, 3, 0) for i in range(3): ainv[i, i] = 1 print(f"a^(-1) is {ainv}") # u, v u = Matrix(3, 1, 0) u[0, 0], u[1, 0], u[2, 0] = 1, 2, -3 v = Matrix(3, 1, 0) v[0, 0], v[1, 0], v[2, 0] = 4, -2, 5 print(f"u is {u}") print(f"v is {v}") print(f"uv^T is {u * v.transpose()}") # Sherman Morrison print(f"(a + uv^T)^(-1) is {ainv.sherman_morrison(u, v)}") def test2() -> None: import doctest doctest.testmod() test2()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/largest_square_area_in_matrix.py
matrix/largest_square_area_in_matrix.py
""" Question: Given a binary matrix mat of size n * m, find out the maximum size square sub-matrix with all 1s. --- Example 1: Input: n = 2, m = 2 mat = [[1, 1], [1, 1]] Output: 2 Explanation: The maximum size of the square sub-matrix is 2. The matrix itself is the maximum sized sub-matrix in this case. --- Example 2 Input: n = 2, m = 2 mat = [[0, 0], [0, 0]] Output: 0 Explanation: There is no 1 in the matrix. Approach: We initialize another matrix (dp) with the same dimensions as the original one initialized with all 0's. dp_array(i,j) represents the side length of the maximum square whose bottom right corner is the cell with index (i,j) in the original matrix. Starting from index (0,0), for every 1 found in the original matrix, we update the value of the current element as dp_array(i,j)=dp_array(dp(i-1,j),dp_array(i-1,j-1),dp_array(i,j-1)) + 1. """ def largest_square_area_in_matrix_top_down_approch( rows: int, cols: int, mat: list[list[int]] ) -> int: """ Function updates the largest_square_area[0], if recursive call found square with maximum area. We aren't using dp_array here, so the time complexity would be exponential. >>> largest_square_area_in_matrix_top_down_approch(2, 2, [[1,1], [1,1]]) 2 >>> largest_square_area_in_matrix_top_down_approch(2, 2, [[0,0], [0,0]]) 0 """ def update_area_of_max_square(row: int, col: int) -> int: # BASE CASE if row >= rows or col >= cols: return 0 right = update_area_of_max_square(row, col + 1) diagonal = update_area_of_max_square(row + 1, col + 1) down = update_area_of_max_square(row + 1, col) if mat[row][col]: sub_problem_sol = 1 + min([right, diagonal, down]) largest_square_area[0] = max(largest_square_area[0], sub_problem_sol) return sub_problem_sol else: return 0 largest_square_area = [0] update_area_of_max_square(0, 0) return largest_square_area[0] def largest_square_area_in_matrix_top_down_approch_with_dp( rows: int, cols: int, mat: list[list[int]] ) -> int: """ Function updates the largest_square_area[0], if recursive call found square with maximum area. We are using dp_array here, so the time complexity would be O(N^2). >>> largest_square_area_in_matrix_top_down_approch_with_dp(2, 2, [[1,1], [1,1]]) 2 >>> largest_square_area_in_matrix_top_down_approch_with_dp(2, 2, [[0,0], [0,0]]) 0 """ def update_area_of_max_square_using_dp_array( row: int, col: int, dp_array: list[list[int]] ) -> int: if row >= rows or col >= cols: return 0 if dp_array[row][col] != -1: return dp_array[row][col] right = update_area_of_max_square_using_dp_array(row, col + 1, dp_array) diagonal = update_area_of_max_square_using_dp_array(row + 1, col + 1, dp_array) down = update_area_of_max_square_using_dp_array(row + 1, col, dp_array) if mat[row][col]: sub_problem_sol = 1 + min([right, diagonal, down]) largest_square_area[0] = max(largest_square_area[0], sub_problem_sol) dp_array[row][col] = sub_problem_sol return sub_problem_sol else: return 0 largest_square_area = [0] dp_array = [[-1] * cols for _ in range(rows)] update_area_of_max_square_using_dp_array(0, 0, dp_array) return largest_square_area[0] def largest_square_area_in_matrix_bottom_up( rows: int, cols: int, mat: list[list[int]] ) -> int: """ Function updates the largest_square_area, using bottom up approach. >>> largest_square_area_in_matrix_bottom_up(2, 2, [[1,1], [1,1]]) 2 >>> largest_square_area_in_matrix_bottom_up(2, 2, [[0,0], [0,0]]) 0 """ dp_array = [[0] * (cols + 1) for _ in range(rows + 1)] largest_square_area = 0 for row in range(rows - 1, -1, -1): for col in range(cols - 1, -1, -1): right = dp_array[row][col + 1] diagonal = dp_array[row + 1][col + 1] bottom = dp_array[row + 1][col] if mat[row][col] == 1: dp_array[row][col] = 1 + min(right, diagonal, bottom) largest_square_area = max(dp_array[row][col], largest_square_area) else: dp_array[row][col] = 0 return largest_square_area def largest_square_area_in_matrix_bottom_up_space_optimization( rows: int, cols: int, mat: list[list[int]] ) -> int: """ Function updates the largest_square_area, using bottom up approach. with space optimization. >>> largest_square_area_in_matrix_bottom_up_space_optimization(2, 2, [[1,1], [1,1]]) 2 >>> largest_square_area_in_matrix_bottom_up_space_optimization(2, 2, [[0,0], [0,0]]) 0 """ current_row = [0] * (cols + 1) next_row = [0] * (cols + 1) largest_square_area = 0 for row in range(rows - 1, -1, -1): for col in range(cols - 1, -1, -1): right = current_row[col + 1] diagonal = next_row[col + 1] bottom = next_row[col] if mat[row][col] == 1: current_row[col] = 1 + min(right, diagonal, bottom) largest_square_area = max(current_row[col], largest_square_area) else: current_row[col] = 0 next_row = current_row return largest_square_area if __name__ == "__main__": import doctest doctest.testmod() print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/max_area_of_island.py
matrix/max_area_of_island.py
""" Given an two dimensional binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. The area of an island is the number of cells with a value 1 in the island. Return the maximum area of an island in a grid. If there is no island, return 0. """ matrix = [ [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0], ] def is_safe(row: int, col: int, rows: int, cols: int) -> bool: """ Checking whether coordinate (row, col) is valid or not. >>> is_safe(0, 0, 5, 5) True >>> is_safe(-1,-1, 5, 5) False """ return 0 <= row < rows and 0 <= col < cols def depth_first_search(row: int, col: int, seen: set, mat: list[list[int]]) -> int: """ Returns the current area of the island >>> depth_first_search(0, 0, set(), matrix) 0 """ rows = len(mat) cols = len(mat[0]) if is_safe(row, col, rows, cols) and (row, col) not in seen and mat[row][col] == 1: seen.add((row, col)) return ( 1 + depth_first_search(row + 1, col, seen, mat) + depth_first_search(row - 1, col, seen, mat) + depth_first_search(row, col + 1, seen, mat) + depth_first_search(row, col - 1, seen, mat) ) else: return 0 def find_max_area(mat: list[list[int]]) -> int: """ Finds the area of all islands and returns the maximum area. >>> find_max_area(matrix) 6 """ seen: set = set() max_area = 0 for row, line in enumerate(mat): for col, item in enumerate(line): if item == 1 and (row, col) not in seen: # Maximizing the area max_area = max(max_area, depth_first_search(row, col, seen, mat)) return max_area if __name__ == "__main__": import doctest print(find_max_area(matrix)) # Output -> 6 """ Explanation: We are allowed to move in four directions (horizontal or vertical) so the possible in a matrix if we are at x and y position the possible moving are Directions are [(x, y+1), (x, y-1), (x+1, y), (x-1, y)] but we need to take care of boundary cases as well which are x and y can not be smaller than 0 and greater than the number of rows and columns respectively. Visualization mat = [ [0,0,A,0,0,0,0,B,0,0,0,0,0], [0,0,0,0,0,0,0,B,B,B,0,0,0], [0,C,C,0,D,0,0,0,0,0,0,0,0], [0,C,0,0,D,D,0,0,E,0,E,0,0], [0,C,0,0,D,D,0,0,E,E,E,0,0], [0,0,0,0,0,0,0,0,0,0,E,0,0], [0,0,0,0,0,0,0,F,F,F,0,0,0], [0,0,0,0,0,0,0,F,F,0,0,0,0] ] For visualization, I have defined the connected island with letters by observation, we can see that A island is of area 1 B island is of area 4 C island is of area 4 D island is of area 5 E island is of area 6 and F island is of area 5 it has 6 unique islands of mentioned areas and the maximum of all of them is 6 so we return 6. """ doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/pascal_triangle.py
matrix/pascal_triangle.py
""" This implementation demonstrates how to generate the elements of a Pascal's triangle. The element havingva row index of r and column index of c can be derivedvas follows: triangle[r][c] = triangle[r-1][c-1]+triangle[r-1][c] A Pascal's triangle is a triangular array containing binomial coefficients. https://en.wikipedia.org/wiki/Pascal%27s_triangle """ def print_pascal_triangle(num_rows: int) -> None: """ Print Pascal's triangle for different number of rows >>> print_pascal_triangle(5) 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 """ triangle = generate_pascal_triangle(num_rows) for row_idx in range(num_rows): # Print left spaces for _ in range(num_rows - row_idx - 1): print(end=" ") # Print row values for col_idx in range(row_idx + 1): if col_idx != row_idx: print(triangle[row_idx][col_idx], end=" ") else: print(triangle[row_idx][col_idx], end="") print() def generate_pascal_triangle(num_rows: int) -> list[list[int]]: """ Create Pascal's triangle for different number of rows >>> generate_pascal_triangle(0) [] >>> generate_pascal_triangle(1) [[1]] >>> generate_pascal_triangle(2) [[1], [1, 1]] >>> generate_pascal_triangle(3) [[1], [1, 1], [1, 2, 1]] >>> generate_pascal_triangle(4) [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]] >>> generate_pascal_triangle(5) [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]] >>> generate_pascal_triangle(-5) Traceback (most recent call last): ... ValueError: The input value of 'num_rows' should be greater than or equal to 0 >>> generate_pascal_triangle(7.89) Traceback (most recent call last): ... TypeError: The input value of 'num_rows' should be 'int' """ if not isinstance(num_rows, int): raise TypeError("The input value of 'num_rows' should be 'int'") if num_rows == 0: return [] elif num_rows < 0: raise ValueError( "The input value of 'num_rows' should be greater than or equal to 0" ) triangle: list[list[int]] = [] for current_row_idx in range(num_rows): current_row = populate_current_row(triangle, current_row_idx) triangle.append(current_row) return triangle def populate_current_row(triangle: list[list[int]], current_row_idx: int) -> list[int]: """ >>> triangle = [[1]] >>> populate_current_row(triangle, 1) [1, 1] """ current_row = [-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 current_row[0], current_row[-1] = 1, 1 for current_col_idx in range(1, current_row_idx): calculate_current_element( triangle, current_row, current_row_idx, current_col_idx ) return current_row def calculate_current_element( triangle: list[list[int]], current_row: list[int], current_row_idx: int, current_col_idx: int, ) -> None: """ >>> triangle = [[1], [1, 1]] >>> current_row = [1, -1, 1] >>> calculate_current_element(triangle, current_row, 2, 1) >>> current_row [1, 2, 1] """ above_to_left_elt = triangle[current_row_idx - 1][current_col_idx - 1] above_to_right_elt = triangle[current_row_idx - 1][current_col_idx] current_row[current_col_idx] = above_to_left_elt + above_to_right_elt def generate_pascal_triangle_optimized(num_rows: int) -> list[list[int]]: """ This function returns a matrix representing the corresponding pascal's triangle according to the given input of number of rows of Pascal's triangle to be generated. It reduces the operations done to generate a row by half by eliminating redundant calculations. :param num_rows: Integer specifying the number of rows in the Pascal's triangle :return: 2-D List (matrix) representing the Pascal's triangle Return the Pascal's triangle of given rows >>> generate_pascal_triangle_optimized(3) [[1], [1, 1], [1, 2, 1]] >>> generate_pascal_triangle_optimized(1) [[1]] >>> generate_pascal_triangle_optimized(0) [] >>> generate_pascal_triangle_optimized(-5) Traceback (most recent call last): ... ValueError: The input value of 'num_rows' should be greater than or equal to 0 >>> generate_pascal_triangle_optimized(7.89) Traceback (most recent call last): ... TypeError: The input value of 'num_rows' should be 'int' """ if not isinstance(num_rows, int): raise TypeError("The input value of 'num_rows' should be 'int'") if num_rows == 0: return [] elif num_rows < 0: raise ValueError( "The input value of 'num_rows' should be greater than or equal to 0" ) result: list[list[int]] = [[1]] for row_index in range(1, num_rows): temp_row = [0] + result[-1] + [0] row_length = row_index + 1 # Calculate the number of distinct elements in a row distinct_elements = sum(divmod(row_length, 2)) row_first_half = [ temp_row[i - 1] + temp_row[i] for i in range(1, distinct_elements + 1) ] row_second_half = row_first_half[: (row_index + 1) // 2] row_second_half.reverse() row = row_first_half + row_second_half result.append(row) return result def benchmark() -> None: """ Benchmark multiple functions, with three different length int values. """ from collections.abc import Callable from timeit import timeit def benchmark_a_function(func: Callable, value: int) -> None: call = f"{func.__name__}({value})" timing = timeit(f"__main__.{call}", setup="import __main__") # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds") print(f"{call:38} -- {timing:.4f} seconds") for value in range(15): # (1, 7, 14): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(func, value) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/median_matrix.py
matrix/median_matrix.py
""" https://en.wikipedia.org/wiki/Median """ def median(matrix: list[list[int]]) -> int: """ Calculate the median of a sorted matrix. Args: matrix: A 2D matrix of integers. Returns: The median value of the matrix. Examples: >>> matrix = [[1, 3, 5], [2, 6, 9], [3, 6, 9]] >>> median(matrix) 5 >>> matrix = [[1, 2, 3], [4, 5, 6]] >>> median(matrix) 3 """ # Flatten the matrix into a sorted 1D list linear = sorted(num for row in matrix for num in row) # Calculate the middle index mid = (len(linear) - 1) // 2 # Return the median return linear[mid] if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/cramers_rule_2x2.py
matrix/cramers_rule_2x2.py
# https://www.chilimath.com/lessons/advanced-algebra/cramers-rule-with-two-variables # https://en.wikipedia.org/wiki/Cramer%27s_rule def cramers_rule_2x2(equation1: list[int], equation2: list[int]) -> tuple[float, float]: """ Solves the system of linear equation in 2 variables. :param: equation1: list of 3 numbers :param: equation2: list of 3 numbers :return: String of result input format : [a1, b1, d1], [a2, b2, d2] determinant = [[a1, b1], [a2, b2]] determinant_x = [[d1, b1], [d2, b2]] determinant_y = [[a1, d1], [a2, d2]] >>> cramers_rule_2x2([2, 3, 0], [5, 1, 0]) (0.0, 0.0) >>> cramers_rule_2x2([0, 4, 50], [2, 0, 26]) (13.0, 12.5) >>> cramers_rule_2x2([11, 2, 30], [1, 0, 4]) (4.0, -7.0) >>> cramers_rule_2x2([4, 7, 1], [1, 2, 0]) (2.0, -1.0) >>> cramers_rule_2x2([1, 2, 3], [2, 4, 6]) Traceback (most recent call last): ... ValueError: Infinite solutions. (Consistent system) >>> cramers_rule_2x2([1, 2, 3], [2, 4, 7]) Traceback (most recent call last): ... ValueError: No solution. (Inconsistent system) >>> cramers_rule_2x2([1, 2, 3], [11, 22]) Traceback (most recent call last): ... ValueError: Please enter a valid equation. >>> cramers_rule_2x2([0, 1, 6], [0, 0, 3]) Traceback (most recent call last): ... ValueError: No solution. (Inconsistent system) >>> cramers_rule_2x2([0, 0, 6], [0, 0, 3]) Traceback (most recent call last): ... ValueError: Both a & b of two equations can't be zero. >>> cramers_rule_2x2([1, 2, 3], [1, 2, 3]) Traceback (most recent call last): ... ValueError: Infinite solutions. (Consistent system) >>> cramers_rule_2x2([0, 4, 50], [0, 3, 99]) Traceback (most recent call last): ... ValueError: No solution. (Inconsistent system) """ # Check if the input is valid if not len(equation1) == len(equation2) == 3: raise ValueError("Please enter a valid equation.") if equation1[0] == equation1[1] == equation2[0] == equation2[1] == 0: raise ValueError("Both a & b of two equations can't be zero.") # Extract the coefficients a1, b1, c1 = equation1 a2, b2, c2 = equation2 # Calculate the determinants of the matrices determinant = a1 * b2 - a2 * b1 determinant_x = c1 * b2 - c2 * b1 determinant_y = a1 * c2 - a2 * c1 # Check if the system of linear equations has a solution (using Cramer's rule) if determinant == 0: if determinant_x == determinant_y == 0: raise ValueError("Infinite solutions. (Consistent system)") else: raise ValueError("No solution. (Inconsistent system)") elif determinant_x == determinant_y == 0: # Trivial solution (Inconsistent system) return (0.0, 0.0) else: x = determinant_x / determinant y = determinant_y / determinant # Non-Trivial Solution (Consistent system) return (x, y)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/count_paths.py
matrix/count_paths.py
""" Given a grid, where you start from the top left position [0, 0], you want to find how many paths you can take to get to the bottom right position. start here -> 0 0 0 0 1 1 0 0 0 0 0 1 0 1 0 0 <- finish here how many 'distinct' paths can you take to get to the finish? Using a recursive depth-first search algorithm below, you are able to find the number of distinct unique paths (count). '*' will demonstrate a path In the example above, there are two distinct paths: 1. 2. * * * 0 * * * * 1 1 * 0 1 1 * * 0 0 * 1 0 0 * 1 0 1 * * 0 1 * * """ def depth_first_search(grid: list[list[int]], row: int, col: int, visit: set) -> int: """ Recursive Backtracking Depth First Search Algorithm Starting from top left of a matrix, count the number of paths that can reach the bottom right of a matrix. 1 represents a block (inaccessible) 0 represents a valid space (accessible) 0 0 0 0 1 1 0 0 0 0 0 1 0 1 0 0 >>> grid = [[0, 0, 0, 0], [1, 1, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0]] >>> depth_first_search(grid, 0, 0, set()) 2 0 0 0 0 0 0 1 1 1 0 0 1 1 1 0 0 0 0 0 0 >>> grid = [[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]] >>> depth_first_search(grid, 0, 0, set()) 2 """ row_length, col_length = len(grid), len(grid[0]) if ( min(row, col) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col)) count = 0 count += depth_first_search(grid, row + 1, col, visit) count += depth_first_search(grid, row - 1, col, visit) count += depth_first_search(grid, row, col + 1, visit) count += depth_first_search(grid, row, col - 1, visit) visit.remove((row, col)) return count if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/matrix_operation.py
matrix/matrix_operation.py
""" Functions for 2D matrix operations """ from __future__ import annotations from typing import Any def add(*matrix_s: list[list[int]]) -> list[list[int]]: """ >>> add([[1,2],[3,4]],[[2,3],[4,5]]) [[3, 5], [7, 9]] >>> add([[1.2,2.4],[3,4]],[[2,3],[4,5]]) [[3.2, 5.4], [7, 9]] >>> add([[1, 2], [4, 5]], [[3, 7], [3, 4]], [[3, 5], [5, 7]]) [[7, 14], [12, 16]] >>> add([3], [4, 5]) Traceback (most recent call last): ... TypeError: Expected a matrix, got int/list instead """ if all(_check_not_integer(m) for m in matrix_s): for i in matrix_s[1:]: _verify_matrix_sizes(matrix_s[0], i) return [[sum(t) for t in zip(*m)] for m in zip(*matrix_s)] raise TypeError("Expected a matrix, got int/list instead") def subtract(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]: """ >>> subtract([[1,2],[3,4]],[[2,3],[4,5]]) [[-1, -1], [-1, -1]] >>> subtract([[1,2.5],[3,4]],[[2,3],[4,5.5]]) [[-1, -0.5], [-1, -1.5]] >>> subtract([3], [4, 5]) Traceback (most recent call last): ... TypeError: Expected a matrix, got int/list instead """ if ( _check_not_integer(matrix_a) and _check_not_integer(matrix_b) and _verify_matrix_sizes(matrix_a, matrix_b) ): return [[i - j for i, j in zip(*m)] for m in zip(matrix_a, matrix_b)] raise TypeError("Expected a matrix, got int/list instead") def scalar_multiply(matrix: list[list[int]], n: float) -> list[list[float]]: """ >>> scalar_multiply([[1,2],[3,4]],5) [[5, 10], [15, 20]] >>> scalar_multiply([[1.4,2.3],[3,4]],5) [[7.0, 11.5], [15, 20]] """ return [[x * n for x in row] for row in matrix] def multiply(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]: """ >>> multiply([[1,2],[3,4]],[[5,5],[7,5]]) [[19, 15], [43, 35]] >>> multiply([[1,2.5],[3,4.5]],[[5,5],[7,5]]) [[22.5, 17.5], [46.5, 37.5]] >>> multiply([[1, 2, 3]], [[2], [3], [4]]) [[20]] """ if _check_not_integer(matrix_a) and _check_not_integer(matrix_b): rows, cols = _verify_matrix_sizes(matrix_a, matrix_b) if cols[0] != rows[1]: msg = ( "Cannot multiply matrix of dimensions " f"({rows[0]},{cols[0]}) and ({rows[1]},{cols[1]})" ) raise ValueError(msg) return [ [sum(m * n for m, n in zip(i, j)) for j in zip(*matrix_b)] for i in matrix_a ] def identity(n: int) -> list[list[int]]: """ :param n: dimension for nxn matrix :type n: int :return: Identity matrix of shape [n, n] >>> identity(3) [[1, 0, 0], [0, 1, 0], [0, 0, 1]] """ n = int(n) return [[int(row == column) for column in range(n)] for row in range(n)] def transpose( matrix: list[list[int]], return_map: bool = True ) -> list[list[int]] | map[list[int]]: """ >>> transpose([[1,2],[3,4]]) # doctest: +ELLIPSIS <map object at ... >>> transpose([[1,2],[3,4]], return_map=False) [[1, 3], [2, 4]] >>> transpose([1, [2, 3]]) Traceback (most recent call last): ... TypeError: Expected a matrix, got int/list instead """ if _check_not_integer(matrix): if return_map: return map(list, zip(*matrix)) else: return list(map(list, zip(*matrix))) raise TypeError("Expected a matrix, got int/list instead") def minor(matrix: list[list[int]], row: int, column: int) -> list[list[int]]: """ >>> minor([[1, 2], [3, 4]], 1, 1) [[1]] """ minor = matrix[:row] + matrix[row + 1 :] return [row[:column] + row[column + 1 :] for row in minor] def determinant(matrix: list[list[int]]) -> Any: """ >>> determinant([[1, 2], [3, 4]]) -2 >>> determinant([[1.5, 2.5], [3, 4]]) -1.5 """ if len(matrix) == 1: return matrix[0][0] return sum( x * determinant(minor(matrix, 0, i)) * (-1) ** i for i, x in enumerate(matrix[0]) ) def inverse(matrix: list[list[int]]) -> list[list[float]] | None: """ >>> inverse([[1, 2], [3, 4]]) [[-2.0, 1.0], [1.5, -0.5]] >>> inverse([[1, 1], [1, 1]]) """ # https://stackoverflow.com/questions/20047519/python-doctests-test-for-none det = determinant(matrix) if det == 0: return None matrix_minor = [ [determinant(minor(matrix, i, j)) for j in range(len(matrix))] for i in range(len(matrix)) ] cofactors = [ [x * (-1) ** (row + col) for col, x in enumerate(matrix_minor[row])] for row in range(len(matrix)) ] adjugate = list(transpose(cofactors)) return scalar_multiply(adjugate, 1 / det) def _check_not_integer(matrix: list[list[int]]) -> bool: return not isinstance(matrix, int) and not isinstance(matrix[0], int) def _shape(matrix: list[list[int]]) -> tuple[int, int]: return len(matrix), len(matrix[0]) def _verify_matrix_sizes( matrix_a: list[list[int]], matrix_b: list[list[int]] ) -> tuple[tuple[int, int], tuple[int, int]]: shape = _shape(matrix_a) + _shape(matrix_b) if shape[0] != shape[3] or shape[1] != shape[2]: msg = ( "operands could not be broadcast together with shape " f"({shape[0], shape[1]}), ({shape[2], shape[3]})" ) raise ValueError(msg) return (shape[0], shape[2]), (shape[1], shape[3]) def main() -> None: matrix_a = [[12, 10], [3, 9]] matrix_b = [[3, 4], [7, 4]] matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]] matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]] print(f"Add Operation, {add(matrix_a, matrix_b) = } \n") print(f"Multiply Operation, {multiply(matrix_a, matrix_b) = } \n") print(f"Identity: {identity(5)}\n") print(f"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \n") print(f"Determinant of {matrix_b} = {determinant(matrix_b)} \n") print(f"Inverse of {matrix_d} = {inverse(matrix_d)}\n") if __name__ == "__main__": import doctest doctest.testmod() main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/spiral_print.py
matrix/spiral_print.py
""" This program print the matrix in spiral form. This problem has been solved through recursive way. Matrix must satisfy below conditions i) matrix should be only one or two dimensional ii) number of column of all rows should be equal """ def check_matrix(matrix: list[list[int]]) -> bool: # must be matrix = [list(row) for row in matrix] if matrix and isinstance(matrix, list): if isinstance(matrix[0], list): prev_len = 0 for row in matrix: if prev_len == 0: prev_len = len(row) result = True else: result = prev_len == len(row) else: result = True else: result = False return result def spiral_print_clockwise(a: list[list[int]]) -> None: """ >>> spiral_print_clockwise([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) 1 2 3 4 8 12 11 10 9 5 6 7 """ if check_matrix(a) and len(a) > 0: a = [list(row) for row in a] mat_row = len(a) if isinstance(a[0], list): mat_col = len(a[0]) else: for dat in a: print(dat) return # horizotal printing increasing for i in range(mat_col): print(a[0][i]) # vertical printing down for i in range(1, mat_row): print(a[i][mat_col - 1]) # horizotal printing decreasing if mat_row > 1: for i in range(mat_col - 2, -1, -1): print(a[mat_row - 1][i]) # vertical printing up for i in range(mat_row - 2, 0, -1): print(a[i][0]) remain_mat = [row[1 : mat_col - 1] for row in a[1 : mat_row - 1]] if len(remain_mat) > 0: spiral_print_clockwise(remain_mat) else: return else: print("Not a valid matrix") return # Other Easy to understand Approach def spiral_traversal(matrix: list[list]) -> list[int]: """ >>> spiral_traversal([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] Example: matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] Algorithm: Step 1. first pop the 0 index list. (which is [1,2,3,4] and concatenate the output of [step 2]) Step 2. Now perform matrix's Transpose operation (Change rows to column and vice versa) and reverse the resultant matrix. Step 3. Pass the output of [2nd step], to same recursive function till base case hits. Dry Run: Stage 1. [1, 2, 3, 4] + spiral_traversal([ [8, 12], [7, 11], [6, 10], [5, 9]] ]) Stage 2. [1, 2, 3, 4, 8, 12] + spiral_traversal([ [11, 10, 9], [7, 6, 5] ]) Stage 3. [1, 2, 3, 4, 8, 12, 11, 10, 9] + spiral_traversal([ [5], [6], [7] ]) Stage 4. [1, 2, 3, 4, 8, 12, 11, 10, 9, 5] + spiral_traversal([ [5], [6], [7] ]) Stage 5. [1, 2, 3, 4, 8, 12, 11, 10, 9, 5] + spiral_traversal([[6, 7]]) Stage 6. [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] + spiral_traversal([]) """ if matrix: return list(matrix.pop(0)) + spiral_traversal( [list(row) for row in zip(*matrix)][::-1] ) else: return [] # driver code if __name__ == "__main__": import doctest doctest.testmod() a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] spiral_print_clockwise(a)
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/searching_in_sorted_matrix.py
matrix/searching_in_sorted_matrix.py
from __future__ import annotations def search_in_a_sorted_matrix(mat: list[list[int]], m: int, n: int, key: float) -> None: """ >>> search_in_a_sorted_matrix( ... [[2, 5, 7], [4, 8, 13], [9, 11, 15], [12, 17, 20]], 3, 3, 5) Key 5 found at row- 1 column- 2 >>> search_in_a_sorted_matrix( ... [[2, 5, 7], [4, 8, 13], [9, 11, 15], [12, 17, 20]], 3, 3, 21) Key 21 not found >>> search_in_a_sorted_matrix( ... [[2.1, 5, 7], [4, 8, 13], [9, 11, 15], [12, 17, 20]], 3, 3, 2.1) Key 2.1 found at row- 1 column- 1 >>> search_in_a_sorted_matrix( ... [[2.1, 5, 7], [4, 8, 13], [9, 11, 15], [12, 17, 20]], 3, 3, 2.2) Key 2.2 not found """ i, j = m - 1, 0 while i >= 0 and j < n: if key == mat[i][j]: print(f"Key {key} found at row- {i + 1} column- {j + 1}") return if key < mat[i][j]: i -= 1 else: j += 1 print(f"Key {key} not found") def main() -> None: mat = [[2, 5, 7], [4, 8, 13], [9, 11, 15], [12, 17, 20]] x = int(input("Enter the element to be searched:")) print(mat) search_in_a_sorted_matrix(mat, len(mat), len(mat[0]), x) if __name__ == "__main__": import doctest doctest.testmod() main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/matrix_multiplication_recursion.py
matrix/matrix_multiplication_recursion.py
# @Author : ojas-wani # @File : matrix_multiplication_recursion.py # @Date : 10/06/2023 """ Perform matrix multiplication using a recursive algorithm. https://en.wikipedia.org/wiki/Matrix_multiplication """ # type Matrix = list[list[int]] # psf/black currenttly fails on this line Matrix = list[list[int]] matrix_1_to_4 = [ [1, 2], [3, 4], ] matrix_5_to_8 = [ [5, 6], [7, 8], ] matrix_5_to_9_high = [ [5, 6], [7, 8], [9], ] matrix_5_to_9_wide = [ [5, 6], [7, 8, 9], ] matrix_count_up = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], ] matrix_unordered = [ [5, 8, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1], [2, 6, 10, 14], ] matrices = ( matrix_1_to_4, matrix_5_to_8, matrix_5_to_9_high, matrix_5_to_9_wide, matrix_count_up, matrix_unordered, ) def is_square(matrix: Matrix) -> bool: """ >>> is_square([]) True >>> is_square(matrix_1_to_4) True >>> is_square(matrix_5_to_9_high) False """ len_matrix = len(matrix) return all(len(row) == len_matrix for row in matrix) def matrix_multiply(matrix_a: Matrix, matrix_b: Matrix) -> Matrix: """ >>> matrix_multiply(matrix_1_to_4, matrix_5_to_8) [[19, 22], [43, 50]] """ return [ [sum(a * b for a, b in zip(row, col)) for col in zip(*matrix_b)] for row in matrix_a ] def matrix_multiply_recursive(matrix_a: Matrix, matrix_b: Matrix) -> Matrix: """ :param matrix_a: A square Matrix. :param matrix_b: Another square Matrix with the same dimensions as matrix_a. :return: Result of matrix_a * matrix_b. :raises ValueError: If the matrices cannot be multiplied. >>> matrix_multiply_recursive([], []) [] >>> matrix_multiply_recursive(matrix_1_to_4, matrix_5_to_8) [[19, 22], [43, 50]] >>> matrix_multiply_recursive(matrix_count_up, matrix_unordered) [[37, 61, 74, 61], [105, 165, 166, 129], [173, 269, 258, 197], [241, 373, 350, 265]] >>> matrix_multiply_recursive(matrix_1_to_4, matrix_5_to_9_wide) Traceback (most recent call last): ... ValueError: Invalid matrix dimensions >>> matrix_multiply_recursive(matrix_1_to_4, matrix_5_to_9_high) Traceback (most recent call last): ... ValueError: Invalid matrix dimensions >>> matrix_multiply_recursive(matrix_1_to_4, matrix_count_up) Traceback (most recent call last): ... ValueError: Invalid matrix dimensions """ if not matrix_a or not matrix_b: return [] if not all( (len(matrix_a) == len(matrix_b), is_square(matrix_a), is_square(matrix_b)) ): raise ValueError("Invalid matrix dimensions") # Initialize the result matrix with zeros result = [[0] * len(matrix_b[0]) for _ in range(len(matrix_a))] # Recursive multiplication of matrices def multiply( i_loop: int, j_loop: int, k_loop: int, matrix_a: Matrix, matrix_b: Matrix, result: Matrix, ) -> None: """ :param matrix_a: A square Matrix. :param matrix_b: Another square Matrix with the same dimensions as matrix_a. :param result: Result matrix :param i: Index used for iteration during multiplication. :param j: Index used for iteration during multiplication. :param k: Index used for iteration during multiplication. >>> 0 > 1 # Doctests in inner functions are never run True """ if i_loop >= len(matrix_a): return if j_loop >= len(matrix_b[0]): return multiply(i_loop + 1, 0, 0, matrix_a, matrix_b, result) if k_loop >= len(matrix_b): return multiply(i_loop, j_loop + 1, 0, matrix_a, matrix_b, result) result[i_loop][j_loop] += matrix_a[i_loop][k_loop] * matrix_b[k_loop][j_loop] return multiply(i_loop, j_loop, k_loop + 1, matrix_a, matrix_b, result) # Perform the recursive matrix multiplication multiply(0, 0, 0, matrix_a, matrix_b, result) return result if __name__ == "__main__": from doctest import testmod failure_count, test_count = testmod() if not failure_count: matrix_a = matrices[0] for matrix_b in matrices[1:]: print("Multiplying:") for row in matrix_a: print(row) print("By:") for row in matrix_b: print(row) print("Result:") try: result = matrix_multiply_recursive(matrix_a, matrix_b) for row in result: print(row) assert result == matrix_multiply(matrix_a, matrix_b) except ValueError as e: print(f"{e!r}") print() matrix_a = matrix_b print("Benchmark:") from functools import partial from timeit import timeit mytimeit = partial(timeit, globals=globals(), number=100_000) for func in ("matrix_multiply", "matrix_multiply_recursive"): print(f"{func:>25}(): {mytimeit(f'{func}(matrix_count_up, matrix_unordered)')}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/rotate_matrix.py
matrix/rotate_matrix.py
""" In this problem, we want to rotate the matrix elements by 90, 180, 270 (counterclockwise) Discussion in stackoverflow: https://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array """ from __future__ import annotations def make_matrix(row_size: int = 4) -> list[list[int]]: """ >>> make_matrix() [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] >>> make_matrix(1) [[1]] >>> make_matrix(-2) [[1, 2], [3, 4]] >>> make_matrix(3) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> make_matrix() == make_matrix(4) True """ row_size = abs(row_size) or 4 return [[1 + x + y * row_size for x in range(row_size)] for y in range(row_size)] def rotate_90(matrix: list[list[int]]) -> list[list[int]]: """ >>> rotate_90(make_matrix()) [[4, 8, 12, 16], [3, 7, 11, 15], [2, 6, 10, 14], [1, 5, 9, 13]] >>> rotate_90(make_matrix()) == transpose(reverse_column(make_matrix())) True """ return reverse_row(transpose(matrix)) # OR.. transpose(reverse_column(matrix)) def rotate_180(matrix: list[list[int]]) -> list[list[int]]: """ >>> rotate_180(make_matrix()) [[16, 15, 14, 13], [12, 11, 10, 9], [8, 7, 6, 5], [4, 3, 2, 1]] >>> rotate_180(make_matrix()) == reverse_column(reverse_row(make_matrix())) True """ return reverse_row(reverse_column(matrix)) # OR.. reverse_column(reverse_row(matrix)) def rotate_270(matrix: list[list[int]]) -> list[list[int]]: """ >>> rotate_270(make_matrix()) [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]] >>> rotate_270(make_matrix()) == transpose(reverse_row(make_matrix())) True """ return reverse_column(transpose(matrix)) # OR.. transpose(reverse_row(matrix)) def transpose(matrix: list[list[int]]) -> list[list[int]]: matrix[:] = [list(x) for x in zip(*matrix)] return matrix def reverse_row(matrix: list[list[int]]) -> list[list[int]]: matrix[:] = matrix[::-1] return matrix def reverse_column(matrix: list[list[int]]) -> list[list[int]]: matrix[:] = [x[::-1] for x in matrix] return matrix def print_matrix(matrix: list[list[int]]) -> None: for i in matrix: print(*i) if __name__ == "__main__": matrix = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 90 counterclockwise:\n") print_matrix(rotate_90(matrix)) matrix = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 180:\n") print_matrix(rotate_180(matrix)) matrix = make_matrix() print("\norigin:\n") print_matrix(matrix) print("\nrotate 270 counterclockwise:\n") print_matrix(rotate_270(matrix))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/validate_sudoku_board.py
matrix/validate_sudoku_board.py
""" LeetCode 36. Valid Sudoku https://leetcode.com/problems/valid-sudoku/ https://en.wikipedia.org/wiki/Sudoku Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: - Each row must contain the digits 1-9 without repetition. - Each column must contain the digits 1-9 without repetition. - Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition. Note: A Sudoku board (partially filled) could be valid but is not necessarily solvable. Only the filled cells need to be validated according to the mentioned rules. """ from collections import defaultdict NUM_SQUARES = 9 EMPTY_CELL = "." def is_valid_sudoku_board(sudoku_board: list[list[str]]) -> bool: """ This function validates (but does not solve) a sudoku board. The board may be valid but unsolvable. >>> is_valid_sudoku_board([ ... ["5","3",".",".","7",".",".",".","."] ... ,["6",".",".","1","9","5",".",".","."] ... ,[".","9","8",".",".",".",".","6","."] ... ,["8",".",".",".","6",".",".",".","3"] ... ,["4",".",".","8",".","3",".",".","1"] ... ,["7",".",".",".","2",".",".",".","6"] ... ,[".","6",".",".",".",".","2","8","."] ... ,[".",".",".","4","1","9",".",".","5"] ... ,[".",".",".",".","8",".",".","7","9"] ... ]) True >>> is_valid_sudoku_board([ ... ["8","3",".",".","7",".",".",".","."] ... ,["6",".",".","1","9","5",".",".","."] ... ,[".","9","8",".",".",".",".","6","."] ... ,["8",".",".",".","6",".",".",".","3"] ... ,["4",".",".","8",".","3",".",".","1"] ... ,["7",".",".",".","2",".",".",".","6"] ... ,[".","6",".",".",".",".","2","8","."] ... ,[".",".",".","4","1","9",".",".","5"] ... ,[".",".",".",".","8",".",".","7","9"] ... ]) False >>> is_valid_sudoku_board([ ... ["1","2","3","4","5","6","7","8","9"] ... ,["4","5","6","7","8","9","1","2","3"] ... ,["7","8","9","1","2","3","4","5","6"] ... ,[".",".",".",".",".",".",".",".","."] ... ,[".",".",".",".",".",".",".",".","."] ... ,[".",".",".",".",".",".",".",".","."] ... ,[".",".",".",".",".",".",".",".","."] ... ,[".",".",".",".",".",".",".",".","."] ... ,[".",".",".",".",".",".",".",".","."] ... ]) True >>> is_valid_sudoku_board([ ... ["1","2","3",".",".",".",".",".","."] ... ,["4","5","6",".",".",".",".",".","."] ... ,["7","8","9",".",".",".",".",".","."] ... ,[".",".",".","4","5","6",".",".","."] ... ,[".",".",".","7","8","9",".",".","."] ... ,[".",".",".","1","2","3",".",".","."] ... ,[".",".",".",".",".",".","7","8","9"] ... ,[".",".",".",".",".",".","1","2","3"] ... ,[".",".",".",".",".",".","4","5","6"] ... ]) True >>> is_valid_sudoku_board([ ... ["1","2","3",".",".",".","5","6","4"] ... ,["4","5","6",".",".",".","8","9","7"] ... ,["7","8","9",".",".",".","2","3","1"] ... ,[".",".",".","4","5","6",".",".","."] ... ,[".",".",".","7","8","9",".",".","."] ... ,[".",".",".","1","2","3",".",".","."] ... ,["3","1","2",".",".",".","7","8","9"] ... ,["6","4","5",".",".",".","1","2","3"] ... ,["9","7","8",".",".",".","4","5","6"] ... ]) True >>> is_valid_sudoku_board([ ... ["1","2","3","4","5","6","7","8","9"] ... ,["2",".",".",".",".",".",".",".","8"] ... ,["3",".",".",".",".",".",".",".","7"] ... ,["4",".",".",".",".",".",".",".","6"] ... ,["5",".",".",".",".",".",".",".","5"] ... ,["6",".",".",".",".",".",".",".","4"] ... ,["7",".",".",".",".",".",".",".","3"] ... ,["8",".",".",".",".",".",".",".","2"] ... ,["9","8","7","6","5","4","3","2","1"] ... ]) False >>> is_valid_sudoku_board([ ... ["1","2","3","8","9","7","5","6","4"] ... ,["4","5","6","2","3","1","8","9","7"] ... ,["7","8","9","5","6","4","2","3","1"] ... ,["2","3","1","4","5","6","9","7","8"] ... ,["5","6","4","7","8","9","3","1","2"] ... ,["8","9","7","1","2","3","6","4","5"] ... ,["3","1","2","6","4","5","7","8","9"] ... ,["6","4","5","9","7","8","1","2","3"] ... ,["9","7","8","3","1","2","4","5","6"] ... ]) True >>> is_valid_sudoku_board([["1", "2", "3", "4", "5", "6", "7", "8", "9"]]) Traceback (most recent call last): ... ValueError: Sudoku boards must be 9x9 squares. >>> is_valid_sudoku_board( ... [["1"], ["2"], ["3"], ["4"], ["5"], ["6"], ["7"], ["8"], ["9"]] ... ) Traceback (most recent call last): ... ValueError: Sudoku boards must be 9x9 squares. """ if len(sudoku_board) != NUM_SQUARES or ( any(len(row) != NUM_SQUARES for row in sudoku_board) ): error_message = f"Sudoku boards must be {NUM_SQUARES}x{NUM_SQUARES} squares." raise ValueError(error_message) row_values: defaultdict[int, set[str]] = defaultdict(set) col_values: defaultdict[int, set[str]] = defaultdict(set) box_values: defaultdict[tuple[int, int], set[str]] = defaultdict(set) for row in range(NUM_SQUARES): for col in range(NUM_SQUARES): value = sudoku_board[row][col] if value == EMPTY_CELL: continue box = (row // 3, col // 3) if ( value in row_values[row] or value in col_values[col] or value in box_values[box] ): return False row_values[row].add(value) col_values[col].add(value) box_values[box].add(value) return True if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(timeit("is_valid_sudoku_board(valid_board)", globals=globals())) print(timeit("is_valid_sudoku_board(invalid_board)", globals=globals()))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/matrix_equalization.py
matrix/matrix_equalization.py
from sys import maxsize def array_equalization(vector: list[int], step_size: int) -> int: """ This algorithm equalizes all elements of the input vector to a common value, by making the minimal number of "updates" under the constraint of a step size (step_size). >>> array_equalization([1, 1, 6, 2, 4, 6, 5, 1, 7, 2, 2, 1, 7, 2, 2], 4) 4 >>> array_equalization([22, 81, 88, 71, 22, 81, 632, 81, 81, 22, 92], 2) 5 >>> array_equalization([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 5) 0 >>> array_equalization([22, 22, 22, 33, 33, 33], 2) 2 >>> array_equalization([1, 2, 3], 0) Traceback (most recent call last): ValueError: Step size must be positive and non-zero. >>> array_equalization([1, 2, 3], -1) Traceback (most recent call last): ValueError: Step size must be positive and non-zero. >>> array_equalization([1, 2, 3], 0.5) Traceback (most recent call last): ValueError: Step size must be an integer. >>> array_equalization([1, 2, 3], maxsize) 1 """ if step_size <= 0: raise ValueError("Step size must be positive and non-zero.") if not isinstance(step_size, int): raise ValueError("Step size must be an integer.") unique_elements = set(vector) min_updates = maxsize for element in unique_elements: elem_index = 0 updates = 0 while elem_index < len(vector): if vector[elem_index] != element: updates += 1 elem_index += step_size else: elem_index += 1 min_updates = min(min_updates, updates) return min_updates if __name__ == "__main__": from doctest import testmod testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/matrix_class.py
matrix/matrix_class.py
# An OOP approach to representing and manipulating matrices from __future__ import annotations class Matrix: """ Matrix object generated from a 2D array where each element is an array representing a row. Rows can contain type int or float. Common operations and information available. >>> rows = [ ... [1, 2, 3], ... [4, 5, 6], ... [7, 8, 9] ... ] >>> matrix = Matrix(rows) >>> print(matrix) [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.]] Matrix rows and columns are available as 2D arrays >>> matrix.rows [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> matrix.columns() [[1, 4, 7], [2, 5, 8], [3, 6, 9]] Order is returned as a tuple >>> matrix.order (3, 3) Squareness and invertability are represented as bool >>> matrix.is_square True >>> matrix.is_invertable() False Identity, Minors, Cofactors and Adjugate are returned as Matrices. Inverse can be a Matrix or Nonetype >>> print(matrix.identity()) [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]] >>> print(matrix.minors()) [[-3. -6. -3.] [-6. -12. -6.] [-3. -6. -3.]] >>> print(matrix.cofactors()) [[-3. 6. -3.] [6. -12. 6.] [-3. 6. -3.]] >>> # won't be apparent due to the nature of the cofactor matrix >>> print(matrix.adjugate()) [[-3. 6. -3.] [6. -12. 6.] [-3. 6. -3.]] >>> matrix.inverse() Traceback (most recent call last): ... TypeError: Only matrices with a non-zero determinant have an inverse Determinant is an int, float, or Nonetype >>> matrix.determinant() 0 Negation, scalar multiplication, addition, subtraction, multiplication and exponentiation are available and all return a Matrix >>> print(-matrix) [[-1. -2. -3.] [-4. -5. -6.] [-7. -8. -9.]] >>> matrix2 = matrix * 3 >>> print(matrix2) [[3. 6. 9.] [12. 15. 18.] [21. 24. 27.]] >>> print(matrix + matrix2) [[4. 8. 12.] [16. 20. 24.] [28. 32. 36.]] >>> print(matrix - matrix2) [[-2. -4. -6.] [-8. -10. -12.] [-14. -16. -18.]] >>> print(matrix ** 3) [[468. 576. 684.] [1062. 1305. 1548.] [1656. 2034. 2412.]] Matrices can also be modified >>> matrix.add_row([10, 11, 12]) >>> print(matrix) [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.] [10. 11. 12.]] >>> matrix2.add_column([8, 16, 32]) >>> print(matrix2) [[3. 6. 9. 8.] [12. 15. 18. 16.] [21. 24. 27. 32.]] >>> print(matrix * matrix2) [[90. 108. 126. 136.] [198. 243. 288. 304.] [306. 378. 450. 472.] [414. 513. 612. 640.]] """ def __init__(self, rows: list[list[int]]): error = TypeError( "Matrices must be formed from a list of zero or more lists containing at " "least one and the same number of values, each of which must be of type " "int or float." ) if len(rows) != 0: cols = len(rows[0]) if cols == 0: raise error for row in rows: if len(row) != cols: raise error for value in row: if not isinstance(value, (int, float)): raise error self.rows = rows else: self.rows = [] # MATRIX INFORMATION def columns(self) -> list[list[int]]: return [[row[i] for row in self.rows] for i in range(len(self.rows[0]))] @property def num_rows(self) -> int: return len(self.rows) @property def num_columns(self) -> int: return len(self.rows[0]) @property def order(self) -> tuple[int, int]: return self.num_rows, self.num_columns @property def is_square(self) -> bool: return self.order[0] == self.order[1] def identity(self) -> Matrix: values = [ [0 if column_num != row_num else 1 for column_num in range(self.num_rows)] for row_num in range(self.num_rows) ] return Matrix(values) def determinant(self) -> int: if not self.is_square: return 0 if self.order == (0, 0): return 1 if self.order == (1, 1): return int(self.rows[0][0]) if self.order == (2, 2): return int( (self.rows[0][0] * self.rows[1][1]) - (self.rows[0][1] * self.rows[1][0]) ) else: return sum( self.rows[0][column] * self.cofactors().rows[0][column] for column in range(self.num_columns) ) def is_invertable(self) -> bool: return bool(self.determinant()) def get_minor(self, row: int, column: int) -> int: values = [ [ self.rows[other_row][other_column] for other_column in range(self.num_columns) if other_column != column ] for other_row in range(self.num_rows) if other_row != row ] return Matrix(values).determinant() def get_cofactor(self, row: int, column: int) -> int: if (row + column) % 2 == 0: return self.get_minor(row, column) return -1 * self.get_minor(row, column) def minors(self) -> Matrix: return Matrix( [ [self.get_minor(row, column) for column in range(self.num_columns)] for row in range(self.num_rows) ] ) def cofactors(self) -> Matrix: return Matrix( [ [ self.minors().rows[row][column] if (row + column) % 2 == 0 else self.minors().rows[row][column] * -1 for column in range(self.minors().num_columns) ] for row in range(self.minors().num_rows) ] ) def adjugate(self) -> Matrix: values = [ [self.cofactors().rows[column][row] for column in range(self.num_columns)] for row in range(self.num_rows) ] return Matrix(values) def inverse(self) -> Matrix: determinant = self.determinant() if not determinant: raise TypeError("Only matrices with a non-zero determinant have an inverse") return self.adjugate() * (1 / determinant) def __repr__(self) -> str: return str(self.rows) def __str__(self) -> str: if self.num_rows == 0: return "[]" if self.num_rows == 1: return "[[" + ". ".join(str(self.rows[0])) + "]]" return ( "[" + "\n ".join( [ "[" + ". ".join([str(value) for value in row]) + ".]" for row in self.rows ] ) + "]" ) # MATRIX MANIPULATION def add_row(self, row: list[int], position: int | None = None) -> None: type_error = TypeError("Row must be a list containing all ints and/or floats") if not isinstance(row, list): raise type_error for value in row: if not isinstance(value, (int, float)): raise type_error if len(row) != self.num_columns: raise ValueError( "Row must be equal in length to the other rows in the matrix" ) if position is None: self.rows.append(row) else: self.rows = [*self.rows[0:position], row, *self.rows[position:]] def add_column(self, column: list[int], position: int | None = None) -> None: type_error = TypeError( "Column must be a list containing all ints and/or floats" ) if not isinstance(column, list): raise type_error for value in column: if not isinstance(value, (int, float)): raise type_error if len(column) != self.num_rows: raise ValueError( "Column must be equal in length to the other columns in the matrix" ) if position is None: self.rows = [self.rows[i] + [column[i]] for i in range(self.num_rows)] else: self.rows = [ [*self.rows[i][0:position], column[i], *self.rows[i][position:]] for i in range(self.num_rows) ] # MATRIX OPERATIONS def __eq__(self, other: object) -> bool: if not isinstance(other, Matrix): return NotImplemented return self.rows == other.rows def __ne__(self, other: object) -> bool: return not self == other def __neg__(self) -> Matrix: return self * -1 def __add__(self, other: Matrix) -> Matrix: if self.order != other.order: raise ValueError("Addition requires matrices of the same order") return Matrix( [ [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns)] for i in range(self.num_rows) ] ) def __sub__(self, other: Matrix) -> Matrix: if self.order != other.order: raise ValueError("Subtraction requires matrices of the same order") return Matrix( [ [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns)] for i in range(self.num_rows) ] ) def __mul__(self, other: Matrix | float) -> Matrix: if isinstance(other, (int, float)): return Matrix( [[int(element * other) for element in row] for row in self.rows] ) elif isinstance(other, Matrix): if self.num_columns != other.num_rows: raise ValueError( "The number of columns in the first matrix must " "be equal to the number of rows in the second" ) return Matrix( [ [Matrix.dot_product(row, column) for column in other.columns()] for row in self.rows ] ) else: raise TypeError( "A Matrix can only be multiplied by an int, float, or another matrix" ) def __pow__(self, other: int) -> Matrix: if not isinstance(other, int): raise TypeError("A Matrix can only be raised to the power of an int") if not self.is_square: raise ValueError("Only square matrices can be raised to a power") if other == 0: return self.identity() if other < 0: if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ) result = self for _ in range(other - 1): result *= self return result @classmethod def dot_product(cls, row: list[int], column: list[int]) -> int: return sum(row[i] * column[i] for i in range(len(row))) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/__init__.py
matrix/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/count_negative_numbers_in_sorted_matrix.py
matrix/count_negative_numbers_in_sorted_matrix.py
""" Given an matrix of numbers in which all rows and all columns are sorted in decreasing order, return the number of negative numbers in grid. Reference: https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix """ def generate_large_matrix() -> list[list[int]]: """ >>> generate_large_matrix() # doctest: +ELLIPSIS [[1000, ..., -999], [999, ..., -1001], ..., [2, ..., -1998]] """ return [list(range(1000 - i, -1000 - i, -1)) for i in range(1000)] grid = generate_large_matrix() test_grids = ( [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]], [[3, 2], [1, 0]], [[7, 7, 6]], [[7, 7, 6], [-1, -2, -3]], grid, ) def validate_grid(grid: list[list[int]]) -> None: """ Validate that the rows and columns of the grid is sorted in decreasing order. >>> for grid in test_grids: ... validate_grid(grid) """ assert all(row == sorted(row, reverse=True) for row in grid) assert all(list(col) == sorted(col, reverse=True) for col in zip(*grid)) def find_negative_index(array: list[int]) -> int: """ Find the smallest negative index >>> find_negative_index([0,0,0,0]) 4 >>> find_negative_index([4,3,2,-1]) 3 >>> find_negative_index([1,0,-1,-10]) 2 >>> find_negative_index([0,0,0,-1]) 3 >>> find_negative_index([11,8,7,-3,-5,-9]) 3 >>> find_negative_index([-1,-1,-2,-3]) 0 >>> find_negative_index([5,1,0]) 3 >>> find_negative_index([-5,-5,-5]) 0 >>> find_negative_index([0]) 1 >>> find_negative_index([]) 0 """ left = 0 right = len(array) - 1 # Edge cases such as no values or all numbers are negative. if not array or array[0] < 0: return 0 while right + 1 > left: mid = (left + right) // 2 num = array[mid] # Num must be negative and the index must be greater than or equal to 0. if num < 0 and array[mid - 1] >= 0: return mid if num >= 0: left = mid + 1 else: right = mid - 1 # No negative numbers so return the last index of the array + 1 which is the length. return len(array) def count_negatives_binary_search(grid: list[list[int]]) -> int: """ An O(m logn) solution that uses binary search in order to find the boundary between positive and negative numbers >>> [count_negatives_binary_search(grid) for grid in test_grids] [8, 0, 0, 3, 1498500] """ total = 0 bound = len(grid[0]) for i in range(len(grid)): bound = find_negative_index(grid[i][:bound]) total += bound return (len(grid) * len(grid[0])) - total def count_negatives_brute_force(grid: list[list[int]]) -> int: """ This solution is O(n^2) because it iterates through every column and row. >>> [count_negatives_brute_force(grid) for grid in test_grids] [8, 0, 0, 3, 1498500] """ return len([number for row in grid for number in row if number < 0]) def count_negatives_brute_force_with_break(grid: list[list[int]]) -> int: """ Similar to the brute force solution above but uses break in order to reduce the number of iterations. >>> [count_negatives_brute_force_with_break(grid) for grid in test_grids] [8, 0, 0, 3, 1498500] """ total = 0 for row in grid: for i, number in enumerate(row): if number < 0: total += len(row) - i break return total def benchmark() -> None: """Benchmark our functions next to each other""" from timeit import timeit print("Running benchmarks") setup = ( "from __main__ import count_negatives_binary_search, " "count_negatives_brute_force, count_negatives_brute_force_with_break, grid" ) for func in ( "count_negatives_binary_search", # took 0.7727 seconds "count_negatives_brute_force_with_break", # took 4.6505 seconds "count_negatives_brute_force", # took 12.8160 seconds ): time = timeit(f"{func}(grid=grid)", setup=setup, number=500) print(f"{func}() took {time:0.4f} seconds") if __name__ == "__main__": import doctest doctest.testmod() benchmark()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/nth_fibonacci_using_matrix_exponentiation.py
matrix/nth_fibonacci_using_matrix_exponentiation.py
""" Implementation of finding nth fibonacci number using matrix exponentiation. Time Complexity is about O(log(n)*8), where 8 is the complexity of matrix multiplication of size 2 by 2. And on the other hand complexity of bruteforce solution is O(n). As we know f[n] = f[n-1] + f[n-1] Converting to matrix, [f(n),f(n-1)] = [[1,1],[1,0]] * [f(n-1),f(n-2)] -> [f(n),f(n-1)] = [[1,1],[1,0]]^2 * [f(n-2),f(n-3)] ... ... -> [f(n),f(n-1)] = [[1,1],[1,0]]^(n-1) * [f(1),f(0)] So we just need the n times multiplication of the matrix [1,1],[1,0]]. We can decrease the n times multiplication by following the divide and conquer approach. """ def multiply(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]: matrix_c = [] n = len(matrix_a) for i in range(n): list_1 = [] for j in range(n): val = 0 for k in range(n): val = val + matrix_a[i][k] * matrix_b[k][j] list_1.append(val) matrix_c.append(list_1) return matrix_c def identity(n: int) -> list[list[int]]: return [[int(row == column) for column in range(n)] for row in range(n)] def nth_fibonacci_matrix(n: int) -> int: """ >>> nth_fibonacci_matrix(100) 354224848179261915075 >>> nth_fibonacci_matrix(-100) -100 """ if n <= 1: return n res_matrix = identity(2) fibonacci_matrix = [[1, 1], [1, 0]] n = n - 1 while n > 0: if n % 2 == 1: res_matrix = multiply(res_matrix, fibonacci_matrix) fibonacci_matrix = multiply(fibonacci_matrix, fibonacci_matrix) n = int(n / 2) return res_matrix[0][0] def nth_fibonacci_bruteforce(n: int) -> int: """ >>> nth_fibonacci_bruteforce(100) 354224848179261915075 >>> nth_fibonacci_bruteforce(-100) -100 """ if n <= 1: return n fib0 = 0 fib1 = 1 for _ in range(2, n + 1): fib0, fib1 = fib1, fib0 + fib1 return fib1 def main() -> None: for ordinal in "0th 1st 2nd 3rd 10th 100th 1000th".split(): n = int("".join(c for c in ordinal if c in "0123456789")) # 1000th --> 1000 print( f"{ordinal} fibonacci number using matrix exponentiation is " f"{nth_fibonacci_matrix(n)} and using bruteforce is " f"{nth_fibonacci_bruteforce(n)}\n" ) # from timeit import timeit # print(timeit("nth_fibonacci_matrix(1000000)", # "from main import nth_fibonacci_matrix", number=5)) # print(timeit("nth_fibonacci_bruteforce(1000000)", # "from main import nth_fibonacci_bruteforce", number=5)) # 2.3342058970001744 # 57.256506615000035 if __name__ == "__main__": import doctest doctest.testmod() main()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/matrix_based_game.py
matrix/matrix_based_game.py
""" Matrix-Based Game Script ========================= This script implements a matrix-based game where players interact with a grid of elements. The primary goals are to: - Identify connected elements of the same type from a selected position. - Remove those elements, adjust the matrix by simulating gravity, and reorganize empty columns. - Calculate and display the score based on the number of elements removed in each move. Functions: ----------- 1. `find_repeat`: Finds all connected elements of the same type. 2. `increment_score`: Calculates the score for a given move. 3. `move_x`: Simulates gravity in a column. 4. `move_y`: Reorganizes the matrix by shifting columns leftward when a column becomes empty. 5. `play`: Executes a single move, updating the matrix and returning the score. Input Format: -------------- 1. Matrix size (`lines`): Integer specifying the size of the matrix (N x N). 2. Matrix content (`matrix`): Rows of the matrix, each consisting of characters. 3. Number of moves (`movs`): Integer indicating the number of moves. 4. List of moves (`movements`): A comma-separated string of coordinates for each move. (0,0) position starts from first left column to last right, and below row to up row Example Input: --------------- 4 RRBG RBBG YYGG XYGG 2 0 1,1 1 Example (0,0) = X Output: -------- The script outputs the total score after processing all moves. Usage: ------- Run the script and provide the required inputs as prompted. """ def validate_matrix_size(size: int) -> None: """ >>> validate_matrix_size(-1) Traceback (most recent call last): ... ValueError: Matrix size must be a positive integer. """ if not isinstance(size, int) or size <= 0: raise ValueError("Matrix size must be a positive integer.") def validate_matrix_content(matrix: list[str], size: int) -> None: """ Validates that the number of elements in the matrix matches the given size. >>> validate_matrix_content(['aaaa', 'aaaa', 'aaaa', 'aaaa'], 3) Traceback (most recent call last): ... ValueError: The matrix dont match with size. >>> validate_matrix_content(['aa%', 'aaa', 'aaa'], 3) Traceback (most recent call last): ... ValueError: Matrix rows can only contain letters and numbers. >>> validate_matrix_content(['aaa', 'aaa', 'aaaa'], 3) Traceback (most recent call last): ... ValueError: Each row in the matrix must have exactly 3 characters. """ print(matrix) if len(matrix) != size: raise ValueError("The matrix dont match with size.") for row in matrix: if len(row) != size: msg = f"Each row in the matrix must have exactly {size} characters." raise ValueError(msg) if not all(char.isalnum() for char in row): raise ValueError("Matrix rows can only contain letters and numbers.") def validate_moves(moves: list[tuple[int, int]], size: int) -> None: """ >>> validate_moves([(1, 2), (-1, 0)], 3) Traceback (most recent call last): ... ValueError: Move is out of bounds for a matrix. """ for move in moves: x, y = move if not (0 <= x < size and 0 <= y < size): raise ValueError("Move is out of bounds for a matrix.") def parse_moves(input_str: str) -> list[tuple[int, int]]: """ >>> parse_moves("0 1, 1 1") [(0, 1), (1, 1)] >>> parse_moves("0 1, 1 1, 2") Traceback (most recent call last): ... ValueError: Each move must have exactly two numbers. >>> parse_moves("0 1, 1 1, 2 4 5 6") Traceback (most recent call last): ... ValueError: Each move must have exactly two numbers. """ moves = [] for pair in input_str.split(","): parts = pair.strip().split() if len(parts) != 2: raise ValueError("Each move must have exactly two numbers.") x, y = map(int, parts) moves.append((x, y)) return moves def find_repeat( matrix_g: list[list[str]], row: int, column: int, size: int ) -> set[tuple[int, int]]: """ Finds all connected elements of the same type from a given position. >>> find_repeat([['A', 'B', 'A'], ['A', 'B', 'A'], ['A', 'A', 'A']], 0, 0, 3) {(1, 2), (2, 1), (0, 0), (2, 0), (0, 2), (2, 2), (1, 0)} >>> find_repeat([['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']], 1, 1, 3) set() """ column = size - 1 - column visited = set() repeated = set() if (color := matrix_g[column][row]) != "-": def dfs(row_n: int, column_n: int) -> None: if row_n < 0 or row_n >= size or column_n < 0 or column_n >= size: return if (row_n, column_n) in visited: return visited.add((row_n, column_n)) if matrix_g[row_n][column_n] == color: repeated.add((row_n, column_n)) dfs(row_n - 1, column_n) dfs(row_n + 1, column_n) dfs(row_n, column_n - 1) dfs(row_n, column_n + 1) dfs(column, row) return repeated def increment_score(count: int) -> int: """ Calculates the score for a move based on the number of elements removed. >>> increment_score(3) 6 >>> increment_score(0) 0 """ return int(count * (count + 1) / 2) def move_x(matrix_g: list[list[str]], column: int, size: int) -> list[list[str]]: """ Simulates gravity in a specific column. >>> move_x([['-', 'A'], ['-', '-'], ['-', 'C']], 1, 2) [['-', '-'], ['-', 'A'], ['-', 'C']] """ new_list = [] for row in range(size): if matrix_g[row][column] != "-": new_list.append(matrix_g[row][column]) else: new_list.insert(0, matrix_g[row][column]) for row in range(size): matrix_g[row][column] = new_list[row] return matrix_g def move_y(matrix_g: list[list[str]], size: int) -> list[list[str]]: """ Shifts all columns leftward when an entire column becomes empty. >>> move_y([['-', 'A'], ['-', '-'], ['-', 'C']], 2) [['A', '-'], ['-', '-'], ['-', 'C']] """ empty_columns = [] for column in range(size - 1, -1, -1): if all(matrix_g[row][column] == "-" for row in range(size)): empty_columns.append(column) for column in empty_columns: for col in range(column + 1, size): for row in range(size): matrix_g[row][col - 1] = matrix_g[row][col] for row in range(size): matrix_g[row][-1] = "-" return matrix_g def play( matrix_g: list[list[str]], pos_x: int, pos_y: int, size: int ) -> tuple[list[list[str]], int]: """ Processes a single move, updating the matrix and calculating the score. >>> play([['R', 'G'], ['R', 'G']], 0, 0, 2) ([['G', '-'], ['G', '-']], 3) """ same_colors = find_repeat(matrix_g, pos_x, pos_y, size) if len(same_colors) != 0: for pos in same_colors: matrix_g[pos[0]][pos[1]] = "-" for column in range(size): matrix_g = move_x(matrix_g, column, size) matrix_g = move_y(matrix_g, size) return (matrix_g, increment_score(len(same_colors))) def process_game(size: int, matrix: list[str], moves: list[tuple[int, int]]) -> int: """Processes the game logic for the given matrix and moves. Args: size (int): Size of the game board. matrix (List[str]): Initial game matrix. moves (List[Tuple[int, int]]): List of moves as (x, y) coordinates. Returns: int: The total score obtained. >>> process_game(3, ['aaa', 'bbb', 'ccc'], [(0, 0)]) 6 """ game_matrix = [list(row) for row in matrix] total_score = 0 for move in moves: pos_x, pos_y = move game_matrix, score = play(game_matrix, pos_x, pos_y, size) total_score += score return total_score if __name__ == "__main__": import doctest doctest.testmod(verbose=True) try: size = int(input("Enter the size of the matrix: ")) validate_matrix_size(size) print(f"Enter the {size} rows of the matrix:") matrix = [input(f"Row {i + 1}: ") for i in range(size)] validate_matrix_content(matrix, size) moves_input = input("Enter the moves (e.g., '0 0, 1 1'): ") moves = parse_moves(moves_input) validate_moves(moves, size) score = process_game(size, matrix, moves) print(f"Total score: {score}") except ValueError as e: print(f"{e}")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/binary_search_matrix.py
matrix/binary_search_matrix.py
def binary_search(array: list, lower_bound: int, upper_bound: int, value: int) -> int: """ This function carries out Binary search on a 1d array and return -1 if it do not exist array: A 1d sorted array value : the value meant to be searched >>> matrix = [1, 4, 7, 11, 15] >>> binary_search(matrix, 0, len(matrix) - 1, 1) 0 >>> binary_search(matrix, 0, len(matrix) - 1, 23) -1 """ r = int((lower_bound + upper_bound) // 2) if array[r] == value: return r if lower_bound >= upper_bound: return -1 if array[r] < value: return binary_search(array, r + 1, upper_bound, value) else: return binary_search(array, lower_bound, r - 1, value) def mat_bin_search(value: int, matrix: list) -> list: """ This function loops over a 2d matrix and calls binarySearch on the selected 1d array and returns [-1, -1] is it do not exist value : value meant to be searched matrix = a sorted 2d matrix >>> matrix = [[1, 4, 7, 11, 15], ... [2, 5, 8, 12, 19], ... [3, 6, 9, 16, 22], ... [10, 13, 14, 17, 24], ... [18, 21, 23, 26, 30]] >>> target = 1 >>> mat_bin_search(target, matrix) [0, 0] >>> target = 34 >>> mat_bin_search(target, matrix) [-1, -1] """ index = 0 if matrix[index][0] == value: return [index, 0] while index < len(matrix) and matrix[index][0] < value: r = binary_search(matrix[index], 0, len(matrix[index]) - 1, value) if r != -1: return [index, r] index += 1 return [-1, -1] if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/inverse_of_matrix.py
matrix/inverse_of_matrix.py
from __future__ import annotations from decimal import Decimal from numpy import array def inverse_of_matrix(matrix: list[list[float]]) -> list[list[float]]: """ A matrix multiplied with its inverse gives the identity matrix. This function finds the inverse of a 2x2 and 3x3 matrix. If the determinant of a matrix is 0, its inverse does not exist. Sources for fixing inaccurate float arithmetic: https://stackoverflow.com/questions/6563058/how-do-i-use-accurate-float-arithmetic-in-python https://docs.python.org/3/library/decimal.html Doctests for 2x2 >>> inverse_of_matrix([[2, 5], [2, 0]]) [[0.0, 0.5], [0.2, -0.2]] >>> inverse_of_matrix([[2.5, 5], [1, 2]]) Traceback (most recent call last): ... ValueError: This matrix has no inverse. >>> inverse_of_matrix([[12, -16], [-9, 0]]) [[0.0, -0.1111111111111111], [-0.0625, -0.08333333333333333]] >>> inverse_of_matrix([[12, 3], [16, 8]]) [[0.16666666666666666, -0.0625], [-0.3333333333333333, 0.25]] >>> inverse_of_matrix([[10, 5], [3, 2.5]]) [[0.25, -0.5], [-0.3, 1.0]] Doctests for 3x3 >>> inverse_of_matrix([[2, 5, 7], [2, 0, 1], [1, 2, 3]]) [[2.0, 5.0, -4.0], [1.0, 1.0, -1.0], [-5.0, -12.0, 10.0]] >>> inverse_of_matrix([[1, 2, 2], [1, 2, 2], [3, 2, -1]]) Traceback (most recent call last): ... ValueError: This matrix has no inverse. >>> inverse_of_matrix([[],[]]) Traceback (most recent call last): ... ValueError: Please provide a matrix of size 2x2 or 3x3. >>> inverse_of_matrix([[1, 2], [3, 4], [5, 6]]) Traceback (most recent call last): ... ValueError: Please provide a matrix of size 2x2 or 3x3. >>> inverse_of_matrix([[1, 2, 1], [0,3, 4]]) Traceback (most recent call last): ... ValueError: Please provide a matrix of size 2x2 or 3x3. >>> inverse_of_matrix([[1, 2, 3], [7, 8, 9], [7, 8, 9]]) Traceback (most recent call last): ... ValueError: This matrix has no inverse. >>> inverse_of_matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] """ d = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(matrix) == 2 and len(matrix[0]) == 2 and len(matrix[1]) == 2: # Calculate the determinant of the matrix determinant = float( d(matrix[0][0]) * d(matrix[1][1]) - d(matrix[1][0]) * d(matrix[0][1]) ) if determinant == 0: raise ValueError("This matrix has no inverse.") # Creates a copy of the matrix with swapped positions of the elements swapped_matrix = [[0.0, 0.0], [0.0, 0.0]] swapped_matrix[0][0], swapped_matrix[1][1] = matrix[1][1], matrix[0][0] swapped_matrix[1][0], swapped_matrix[0][1] = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(n)) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(matrix) == 3 and len(matrix[0]) == 3 and len(matrix[1]) == 3 and len(matrix[2]) == 3 ): # Calculate the determinant of the matrix using Sarrus rule determinant = float( ( (d(matrix[0][0]) * d(matrix[1][1]) * d(matrix[2][2])) + (d(matrix[0][1]) * d(matrix[1][2]) * d(matrix[2][0])) + (d(matrix[0][2]) * d(matrix[1][0]) * d(matrix[2][1])) ) - ( (d(matrix[0][2]) * d(matrix[1][1]) * d(matrix[2][0])) + (d(matrix[0][1]) * d(matrix[1][0]) * d(matrix[2][2])) + (d(matrix[0][0]) * d(matrix[1][2]) * d(matrix[2][1])) ) ) if determinant == 0: raise ValueError("This matrix has no inverse.") # Creating cofactor matrix cofactor_matrix = [ [d(0.0), d(0.0), d(0.0)], [d(0.0), d(0.0), d(0.0)], [d(0.0), d(0.0), d(0.0)], ] cofactor_matrix[0][0] = (d(matrix[1][1]) * d(matrix[2][2])) - ( d(matrix[1][2]) * d(matrix[2][1]) ) cofactor_matrix[0][1] = -( (d(matrix[1][0]) * d(matrix[2][2])) - (d(matrix[1][2]) * d(matrix[2][0])) ) cofactor_matrix[0][2] = (d(matrix[1][0]) * d(matrix[2][1])) - ( d(matrix[1][1]) * d(matrix[2][0]) ) cofactor_matrix[1][0] = -( (d(matrix[0][1]) * d(matrix[2][2])) - (d(matrix[0][2]) * d(matrix[2][1])) ) cofactor_matrix[1][1] = (d(matrix[0][0]) * d(matrix[2][2])) - ( d(matrix[0][2]) * d(matrix[2][0]) ) cofactor_matrix[1][2] = -( (d(matrix[0][0]) * d(matrix[2][1])) - (d(matrix[0][1]) * d(matrix[2][0])) ) cofactor_matrix[2][0] = (d(matrix[0][1]) * d(matrix[1][2])) - ( d(matrix[0][2]) * d(matrix[1][1]) ) cofactor_matrix[2][1] = -( (d(matrix[0][0]) * d(matrix[1][2])) - (d(matrix[0][2]) * d(matrix[1][0])) ) cofactor_matrix[2][2] = (d(matrix[0][0]) * d(matrix[1][1])) - ( d(matrix[0][1]) * d(matrix[1][0]) ) # Transpose the cofactor matrix (Adjoint matrix) adjoint_matrix = array(cofactor_matrix) for i in range(3): for j in range(3): adjoint_matrix[i][j] = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix inverse_matrix = array(cofactor_matrix) for i in range(3): for j in range(3): inverse_matrix[i][j] /= d(determinant) # Calculate the inverse of the matrix return [[float(d(n)) or 0.0 for n in row] for row in inverse_matrix] raise ValueError("Please provide a matrix of size 2x2 or 3x3.")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/count_islands_in_matrix.py
matrix/count_islands_in_matrix.py
# An island in matrix is a group of linked areas, all having the same value. # This code counts number of islands in a given matrix, with including diagonal # connections. class Matrix: # Public class to implement a graph def __init__(self, row: int, col: int, graph: list[list[bool]]) -> None: self.ROW = row self.COL = col self.graph = graph def is_safe(self, i: int, j: int, visited: list[list[bool]]) -> bool: return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def diffs(self, i: int, j: int, visited: list[list[bool]]) -> None: # Checking all 8 elements surrounding nth element row_nbr = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order col_nbr = [-1, 0, 1, -1, 1, -1, 0, 1] visited[i][j] = True # Make those cells visited for k in range(8): if self.is_safe(i + row_nbr[k], j + col_nbr[k], visited): self.diffs(i + row_nbr[k], j + col_nbr[k], visited) def count_islands(self) -> int: # And finally, count all islands. visited = [[False for j in range(self.COL)] for i in range(self.ROW)] count = 0 for i in range(self.ROW): for j in range(self.COL): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(i, j, visited) count += 1 return count
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/tests/__init__.py
matrix/tests/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/matrix/tests/test_matrix_operation.py
matrix/tests/test_matrix_operation.py
""" Testing here assumes that numpy and linalg is ALWAYS correct!!!! If running from PyCharm you can place the following line in "Additional Arguments" for the pytest run configuration -vv -m mat_ops -p no:cacheprovider """ import logging # standard libraries import sys import numpy as np import pytest # Custom/local libraries from matrix import matrix_operation as matop mat_a = [[12, 10], [3, 9]] mat_b = [[3, 4], [7, 4]] mat_c = [[3, 0, 2], [2, 0, -2], [0, 1, 1]] mat_d = [[3, 0, -2], [2, 0, 2], [0, 1, 1]] mat_e = [[3, 0, 2], [2, 0, -2], [0, 1, 1], [2, 0, -2]] mat_f = [1] mat_h = [2] logger = logging.getLogger() logger.level = logging.DEBUG stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) @pytest.mark.mat_ops @pytest.mark.parametrize( ("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)] ) def test_addition(mat1, mat2): if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2): logger.info(f"\n\t{test_addition.__name__} returned integer") with pytest.raises(TypeError): matop.add(mat1, mat2) elif (np.array(mat1)).shape == (np.array(mat2)).shape: logger.info(f"\n\t{test_addition.__name__} with same matrix dims") act = (np.array(mat1) + np.array(mat2)).tolist() theo = matop.add(mat1, mat2) assert theo == act else: logger.info(f"\n\t{test_addition.__name__} with different matrix dims") with pytest.raises(ValueError): matop.add(mat1, mat2) @pytest.mark.mat_ops @pytest.mark.parametrize( ("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)] ) def test_subtraction(mat1, mat2): if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2): logger.info(f"\n\t{test_subtraction.__name__} returned integer") with pytest.raises(TypeError): matop.subtract(mat1, mat2) elif (np.array(mat1)).shape == (np.array(mat2)).shape: logger.info(f"\n\t{test_subtraction.__name__} with same matrix dims") act = (np.array(mat1) - np.array(mat2)).tolist() theo = matop.subtract(mat1, mat2) assert theo == act else: logger.info(f"\n\t{test_subtraction.__name__} with different matrix dims") with pytest.raises(ValueError): assert matop.subtract(mat1, mat2) @pytest.mark.mat_ops @pytest.mark.parametrize( ("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)] ) def test_multiplication(mat1, mat2): if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2): logger.info(f"\n\t{test_multiplication.__name__} returned integer") with pytest.raises(TypeError): matop.add(mat1, mat2) elif (np.array(mat1)).shape == (np.array(mat2)).shape: logger.info(f"\n\t{test_multiplication.__name__} meets dim requirements") act = (np.matmul(mat1, mat2)).tolist() theo = matop.multiply(mat1, mat2) assert theo == act else: logger.info( f"\n\t{test_multiplication.__name__} does not meet dim requirements" ) with pytest.raises(ValueError): assert matop.subtract(mat1, mat2) @pytest.mark.mat_ops def test_scalar_multiply(): act = (3.5 * np.array(mat_a)).tolist() theo = matop.scalar_multiply(mat_a, 3.5) assert theo == act @pytest.mark.mat_ops def test_identity(): act = (np.identity(5)).tolist() theo = matop.identity(5) assert theo == act @pytest.mark.mat_ops @pytest.mark.parametrize("mat", [mat_a, mat_b, mat_c, mat_d, mat_e, mat_f]) def test_transpose(mat): if (np.array(mat)).shape < (2, 2): logger.info(f"\n\t{test_transpose.__name__} returned integer") with pytest.raises(TypeError): matop.transpose(mat) else: act = (np.transpose(mat)).tolist() theo = matop.transpose(mat, return_map=False) assert theo == act
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphics/digital_differential_analyzer_line.py
graphics/digital_differential_analyzer_line.py
import matplotlib.pyplot as plt def digital_differential_analyzer_line( p1: tuple[int, int], p2: tuple[int, int] ) -> list[tuple[int, int]]: """ Draws a line between two points using the DDA algorithm. Args: - p1: Coordinates of the starting point. - p2: Coordinates of the ending point. Returns: - List of coordinate points that form the line. >>> digital_differential_analyzer_line((1, 1), (4, 4)) [(2, 2), (3, 3), (4, 4)] """ x1, y1 = p1 x2, y2 = p2 dx = x2 - x1 dy = y2 - y1 steps = max(abs(dx), abs(dy)) x_increment = dx / float(steps) y_increment = dy / float(steps) coordinates = [] x: float = x1 y: float = y1 for _ in range(steps): x += x_increment y += y_increment coordinates.append((round(x), round(y))) return coordinates if __name__ == "__main__": import doctest doctest.testmod() x1 = int(input("Enter the x-coordinate of the starting point: ")) y1 = int(input("Enter the y-coordinate of the starting point: ")) x2 = int(input("Enter the x-coordinate of the ending point: ")) y2 = int(input("Enter the y-coordinate of the ending point: ")) coordinates = digital_differential_analyzer_line((x1, y1), (x2, y2)) x_points, y_points = zip(*coordinates) plt.plot(x_points, y_points, marker="o") plt.title("Digital Differential Analyzer Line Drawing Algorithm") plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.grid() plt.show()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphics/butterfly_pattern.py
graphics/butterfly_pattern.py
def butterfly_pattern(n: int) -> str: """ Creates a butterfly pattern of size n and returns it as a string. >>> print(butterfly_pattern(3)) * * ** ** ***** ** ** * * >>> print(butterfly_pattern(5)) * * ** ** *** *** **** **** ********* **** **** *** *** ** ** * * """ result = [] # Upper part for i in range(1, n): left_stars = "*" * i spaces = " " * (2 * (n - i) - 1) right_stars = "*" * i result.append(left_stars + spaces + right_stars) # Middle part result.append("*" * (2 * n - 1)) # Lower part for i in range(n - 1, 0, -1): left_stars = "*" * i spaces = " " * (2 * (n - i) - 1) right_stars = "*" * i result.append(left_stars + spaces + right_stars) return "\n".join(result) if __name__ == "__main__": n = int(input("Enter the size of the butterfly pattern: ")) print(butterfly_pattern(n))
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphics/__init__.py
graphics/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphics/vector3_for_2d_rendering.py
graphics/vector3_for_2d_rendering.py
""" render 3d points for 2d surfaces. """ from __future__ import annotations import math __version__ = "2020.9.26" __author__ = "xcodz-dot, cclaus, dhruvmanila" def convert_to_2d( x: float, y: float, z: float, scale: float, distance: float ) -> tuple[float, float]: """ Converts 3d point to a 2d drawable point >>> convert_to_2d(1.0, 2.0, 3.0, 10.0, 10.0) (7.6923076923076925, 15.384615384615385) >>> convert_to_2d(1, 2, 3, 10, 10) (7.6923076923076925, 15.384615384615385) >>> convert_to_2d("1", 2, 3, 10, 10) # '1' is str Traceback (most recent call last): ... TypeError: Input values must either be float or int: ['1', 2, 3, 10, 10] """ if not all(isinstance(val, (float, int)) for val in locals().values()): msg = f"Input values must either be float or int: {list(locals().values())}" raise TypeError(msg) projected_x = ((x * distance) / (z + distance)) * scale projected_y = ((y * distance) / (z + distance)) * scale return projected_x, projected_y def rotate( x: float, y: float, z: float, axis: str, angle: float ) -> tuple[float, float, float]: """ rotate a point around a certain axis with a certain angle angle can be any integer between 1, 360 and axis can be any one of 'x', 'y', 'z' >>> rotate(1.0, 2.0, 3.0, 'y', 90.0) (3.130524675073759, 2.0, 0.4470070007889556) >>> rotate(1, 2, 3, "z", 180) (0.999736015495891, -2.0001319704760485, 3) >>> rotate('1', 2, 3, "z", 90.0) # '1' is str Traceback (most recent call last): ... TypeError: Input values except axis must either be float or int: ['1', 2, 3, 90.0] >>> rotate(1, 2, 3, "n", 90) # 'n' is not a valid axis Traceback (most recent call last): ... ValueError: not a valid axis, choose one of 'x', 'y', 'z' >>> rotate(1, 2, 3, "x", -90) (1, -2.5049096187183877, -2.5933429780983657) >>> rotate(1, 2, 3, "x", 450) # 450 wrap around to 90 (1, 3.5776792428178217, -0.44744970165427644) """ if not isinstance(axis, str): raise TypeError("Axis must be a str") input_variables = locals() del input_variables["axis"] if not all(isinstance(val, (float, int)) for val in input_variables.values()): msg = ( "Input values except axis must either be float or int: " f"{list(input_variables.values())}" ) raise TypeError(msg) angle = (angle % 360) / 450 * 180 / math.pi if axis == "z": new_x = x * math.cos(angle) - y * math.sin(angle) new_y = y * math.cos(angle) + x * math.sin(angle) new_z = z elif axis == "x": new_y = y * math.cos(angle) - z * math.sin(angle) new_z = z * math.cos(angle) + y * math.sin(angle) new_x = x elif axis == "y": new_x = x * math.cos(angle) - z * math.sin(angle) new_z = z * math.cos(angle) + x * math.sin(angle) new_y = y else: raise ValueError("not a valid axis, choose one of 'x', 'y', 'z'") return new_x, new_y, new_z if __name__ == "__main__": import doctest doctest.testmod() print(f"{convert_to_2d(1.0, 2.0, 3.0, 10.0, 10.0) = }") print(f"{rotate(1.0, 2.0, 3.0, 'y', 90.0) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/graphics/bezier_curve.py
graphics/bezier_curve.py
# https://en.wikipedia.org/wiki/B%C3%A9zier_curve # https://www.tutorialspoint.com/computer_graphics/computer_graphics_curves.htm from __future__ import annotations from scipy.special import comb class BezierCurve: """ Bezier curve is a weighted sum of a set of control points. Generate Bezier curves from a given set of control points. This implementation works only for 2d coordinates in the xy plane. """ def __init__(self, list_of_points: list[tuple[float, float]]): """ list_of_points: Control points in the xy plane on which to interpolate. These points control the behavior (shape) of the Bezier curve. """ self.list_of_points = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. self.degree = len(list_of_points) - 1 def basis_function(self, t: float) -> list[float]: """ The basis function determines the weight of each control point at time t. t: time value between 0 and 1 inclusive at which to evaluate the basis of the curve. returns the x, y values of basis function at time t >>> curve = BezierCurve([(1,1), (1,2)]) >>> [float(x) for x in curve.basis_function(0)] [1.0, 0.0] >>> [float(x) for x in curve.basis_function(1)] [0.0, 1.0] """ assert 0 <= t <= 1, "Time t must be between 0 and 1." output_values: list[float] = [] for i in range(len(self.list_of_points)): # basis function for each i output_values.append( comb(self.degree, i) * ((1 - t) ** (self.degree - i)) * (t**i) ) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(output_values), 5) == 1 return output_values def bezier_curve_function(self, t: float) -> tuple[float, float]: """ The function to produce the values of the Bezier curve at time t. t: the value of time t at which to evaluate the Bezier function Returns the x, y coordinates of the Bezier curve at time t. The first point in the curve is when t = 0. The last point in the curve is when t = 1. >>> curve = BezierCurve([(1,1), (1,2)]) >>> tuple(float(x) for x in curve.bezier_curve_function(0)) (1.0, 1.0) >>> tuple(float(x) for x in curve.bezier_curve_function(1)) (1.0, 2.0) """ assert 0 <= t <= 1, "Time t must be between 0 and 1." basis_function = self.basis_function(t) x = 0.0 y = 0.0 for i in range(len(self.list_of_points)): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def plot_curve(self, step_size: float = 0.01): """ Plots the Bezier curve using matplotlib plotting capabilities. step_size: defines the step(s) at which to evaluate the Bezier curve. The smaller the step size, the finer the curve produced. """ from matplotlib import pyplot as plt to_plot_x: list[float] = [] # x coordinates of points to plot to_plot_y: list[float] = [] # y coordinates of points to plot t = 0.0 while t <= 1: value = self.bezier_curve_function(t) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size x = [i[0] for i in self.list_of_points] y = [i[1] for i in self.list_of_points] plt.plot( to_plot_x, to_plot_y, color="blue", label="Curve of Degree " + str(self.degree), ) plt.scatter(x, y, color="red", label="Control Points") plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/geometry/__init__.py
geometry/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/geometry/geometry.py
geometry/geometry.py
from __future__ import annotations import math from dataclasses import dataclass, field from types import NoneType from typing import Self # Building block classes @dataclass class Angle: """ An Angle in degrees (unit of measurement) >>> Angle() Angle(degrees=90) >>> Angle(45.5) Angle(degrees=45.5) >>> Angle(-1) Traceback (most recent call last): ... TypeError: degrees must be a numeric value between 0 and 360. >>> Angle(361) Traceback (most recent call last): ... TypeError: degrees must be a numeric value between 0 and 360. """ degrees: float = 90 def __post_init__(self) -> None: if not isinstance(self.degrees, (int, float)) or not 0 <= self.degrees <= 360: raise TypeError("degrees must be a numeric value between 0 and 360.") @dataclass class Side: """ A side of a two dimensional Shape such as Polygon, etc. adjacent_sides: a list of sides which are adjacent to the current side angle: the angle in degrees between each adjacent side length: the length of the current side in meters >>> Side(5) Side(length=5, angle=Angle(degrees=90), next_side=None) >>> Side(5, Angle(45.6)) Side(length=5, angle=Angle(degrees=45.6), next_side=None) >>> Side(5, Angle(45.6), Side(1, Angle(2))) # doctest: +ELLIPSIS Side(length=5, angle=Angle(degrees=45.6), next_side=Side(length=1, angle=Angle(d... >>> Side(-1) Traceback (most recent call last): ... TypeError: length must be a positive numeric value. >>> Side(5, None) Traceback (most recent call last): ... TypeError: angle must be an Angle object. >>> Side(5, Angle(90), "Invalid next_side") Traceback (most recent call last): ... TypeError: next_side must be a Side or None. """ length: float angle: Angle = field(default_factory=Angle) next_side: Side | None = None def __post_init__(self) -> None: if not isinstance(self.length, (int, float)) or self.length <= 0: raise TypeError("length must be a positive numeric value.") if not isinstance(self.angle, Angle): raise TypeError("angle must be an Angle object.") if not isinstance(self.next_side, (Side, NoneType)): raise TypeError("next_side must be a Side or None.") @dataclass class Ellipse: """ A geometric Ellipse on a 2D surface >>> Ellipse(5, 10) Ellipse(major_radius=5, minor_radius=10) >>> Ellipse(5, 10) is Ellipse(5, 10) False >>> Ellipse(5, 10) == Ellipse(5, 10) True """ major_radius: float minor_radius: float @property def area(self) -> float: """ >>> Ellipse(5, 10).area 157.07963267948966 """ return math.pi * self.major_radius * self.minor_radius @property def perimeter(self) -> float: """ >>> Ellipse(5, 10).perimeter 47.12388980384689 """ return math.pi * (self.major_radius + self.minor_radius) class Circle(Ellipse): """ A geometric Circle on a 2D surface >>> Circle(5) Circle(radius=5) >>> Circle(5) is Circle(5) False >>> Circle(5) == Circle(5) True >>> Circle(5).area 78.53981633974483 >>> Circle(5).perimeter 31.41592653589793 """ def __init__(self, radius: float) -> None: super().__init__(radius, radius) self.radius = radius def __repr__(self) -> str: return f"Circle(radius={self.radius})" @property def diameter(self) -> float: """ >>> Circle(5).diameter 10 """ return self.radius * 2 def max_parts(self, num_cuts: float) -> float: """ Return the maximum number of parts that circle can be divided into if cut 'num_cuts' times. >>> circle = Circle(5) >>> circle.max_parts(0) 1.0 >>> circle.max_parts(7) 29.0 >>> circle.max_parts(54) 1486.0 >>> circle.max_parts(22.5) 265.375 >>> circle.max_parts(-222) Traceback (most recent call last): ... TypeError: num_cuts must be a positive numeric value. >>> circle.max_parts("-222") Traceback (most recent call last): ... TypeError: num_cuts must be a positive numeric value. """ if not isinstance(num_cuts, (int, float)) or num_cuts < 0: raise TypeError("num_cuts must be a positive numeric value.") return (num_cuts + 2 + num_cuts**2) * 0.5 @dataclass class Polygon: """ An abstract class which represents Polygon on a 2D surface. >>> Polygon() Polygon(sides=[]) >>> polygon = Polygon() >>> polygon.add_side(Side(5)).get_side(0) Side(length=5, angle=Angle(degrees=90), next_side=None) >>> polygon.get_side(1) Traceback (most recent call last): ... IndexError: list index out of range >>> polygon.set_side(0, Side(10)).get_side(0) Side(length=10, angle=Angle(degrees=90), next_side=None) >>> polygon.set_side(1, Side(10)) Traceback (most recent call last): ... IndexError: list assignment index out of range """ sides: list[Side] = field(default_factory=list) def add_side(self, side: Side) -> Self: """ >>> Polygon().add_side(Side(5)) Polygon(sides=[Side(length=5, angle=Angle(degrees=90), next_side=None)]) """ self.sides.append(side) return self def get_side(self, index: int) -> Side: """ >>> Polygon().get_side(0) Traceback (most recent call last): ... IndexError: list index out of range >>> Polygon().add_side(Side(5)).get_side(-1) Side(length=5, angle=Angle(degrees=90), next_side=None) """ return self.sides[index] def set_side(self, index: int, side: Side) -> Self: """ >>> Polygon().set_side(0, Side(5)) Traceback (most recent call last): ... IndexError: list assignment index out of range >>> Polygon().add_side(Side(5)).set_side(0, Side(10)) Polygon(sides=[Side(length=10, angle=Angle(degrees=90), next_side=None)]) """ self.sides[index] = side return self class Rectangle(Polygon): """ A geometric rectangle on a 2D surface. >>> rectangle_one = Rectangle(5, 10) >>> rectangle_one.perimeter() 30 >>> rectangle_one.area() 50 >>> Rectangle(-5, 10) Traceback (most recent call last): ... TypeError: length must be a positive numeric value. """ def __init__(self, short_side_length: float, long_side_length: float) -> None: super().__init__() self.short_side_length = short_side_length self.long_side_length = long_side_length self.post_init() def post_init(self) -> None: """ >>> Rectangle(5, 10) # doctest: +NORMALIZE_WHITESPACE Rectangle(sides=[Side(length=5, angle=Angle(degrees=90), next_side=None), Side(length=10, angle=Angle(degrees=90), next_side=None)]) """ self.short_side = Side(self.short_side_length) self.long_side = Side(self.long_side_length) super().add_side(self.short_side) super().add_side(self.long_side) def perimeter(self) -> float: return (self.short_side.length + self.long_side.length) * 2 def area(self) -> float: return self.short_side.length * self.long_side.length @dataclass class Square(Rectangle): """ a structure which represents a geometrical square on a 2D surface >>> square_one = Square(5) >>> square_one.perimeter() 20 >>> square_one.area() 25 """ def __init__(self, side_length: float) -> None: super().__init__(side_length, side_length) def perimeter(self) -> float: return super().perimeter() def area(self) -> float: return super().area() if __name__ == "__main__": __import__("doctest").testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/rgb_hsv_conversion.py
conversions/rgb_hsv_conversion.py
""" The RGB color model is an additive color model in which red, green, and blue light are added together in various ways to reproduce a broad array of colors. The name of the model comes from the initials of the three additive primary colors, red, green, and blue. Meanwhile, the HSV representation models how colors appear under light. In it, colors are represented using three components: hue, saturation and (brightness-)value. This file provides functions for converting colors from one representation to the other. (description adapted from https://en.wikipedia.org/wiki/RGB_color_model and https://en.wikipedia.org/wiki/HSL_and_HSV). """ def hsv_to_rgb(hue: float, saturation: float, value: float) -> list[int]: """ Conversion from the HSV-representation to the RGB-representation. Expected RGB-values taken from https://www.rapidtables.com/convert/color/hsv-to-rgb.html >>> hsv_to_rgb(0, 0, 0) [0, 0, 0] >>> hsv_to_rgb(0, 0, 1) [255, 255, 255] >>> hsv_to_rgb(0, 1, 1) [255, 0, 0] >>> hsv_to_rgb(60, 1, 1) [255, 255, 0] >>> hsv_to_rgb(120, 1, 1) [0, 255, 0] >>> hsv_to_rgb(240, 1, 1) [0, 0, 255] >>> hsv_to_rgb(300, 1, 1) [255, 0, 255] >>> hsv_to_rgb(180, 0.5, 0.5) [64, 128, 128] >>> hsv_to_rgb(234, 0.14, 0.88) [193, 196, 224] >>> hsv_to_rgb(330, 0.75, 0.5) [128, 32, 80] """ if hue < 0 or hue > 360: raise Exception("hue should be between 0 and 360") if saturation < 0 or saturation > 1: raise Exception("saturation should be between 0 and 1") if value < 0 or value > 1: raise Exception("value should be between 0 and 1") chroma = value * saturation hue_section = hue / 60 second_largest_component = chroma * (1 - abs(hue_section % 2 - 1)) match_value = value - chroma if hue_section >= 0 and hue_section <= 1: red = round(255 * (chroma + match_value)) green = round(255 * (second_largest_component + match_value)) blue = round(255 * (match_value)) elif hue_section > 1 and hue_section <= 2: red = round(255 * (second_largest_component + match_value)) green = round(255 * (chroma + match_value)) blue = round(255 * (match_value)) elif hue_section > 2 and hue_section <= 3: red = round(255 * (match_value)) green = round(255 * (chroma + match_value)) blue = round(255 * (second_largest_component + match_value)) elif hue_section > 3 and hue_section <= 4: red = round(255 * (match_value)) green = round(255 * (second_largest_component + match_value)) blue = round(255 * (chroma + match_value)) elif hue_section > 4 and hue_section <= 5: red = round(255 * (second_largest_component + match_value)) green = round(255 * (match_value)) blue = round(255 * (chroma + match_value)) else: red = round(255 * (chroma + match_value)) green = round(255 * (match_value)) blue = round(255 * (second_largest_component + match_value)) return [red, green, blue] def rgb_to_hsv(red: int, green: int, blue: int) -> list[float]: """ Conversion from the RGB-representation to the HSV-representation. The tested values are the reverse values from the hsv_to_rgb-doctests. Function "approximately_equal_hsv" is needed because of small deviations due to rounding for the RGB-values. >>> approximately_equal_hsv(rgb_to_hsv(0, 0, 0), [0, 0, 0]) True >>> approximately_equal_hsv(rgb_to_hsv(255, 255, 255), [0, 0, 1]) True >>> approximately_equal_hsv(rgb_to_hsv(255, 0, 0), [0, 1, 1]) True >>> approximately_equal_hsv(rgb_to_hsv(255, 255, 0), [60, 1, 1]) True >>> approximately_equal_hsv(rgb_to_hsv(0, 255, 0), [120, 1, 1]) True >>> approximately_equal_hsv(rgb_to_hsv(0, 0, 255), [240, 1, 1]) True >>> approximately_equal_hsv(rgb_to_hsv(255, 0, 255), [300, 1, 1]) True >>> approximately_equal_hsv(rgb_to_hsv(64, 128, 128), [180, 0.5, 0.5]) True >>> approximately_equal_hsv(rgb_to_hsv(193, 196, 224), [234, 0.14, 0.88]) True >>> approximately_equal_hsv(rgb_to_hsv(128, 32, 80), [330, 0.75, 0.5]) True """ if red < 0 or red > 255: raise Exception("red should be between 0 and 255") if green < 0 or green > 255: raise Exception("green should be between 0 and 255") if blue < 0 or blue > 255: raise Exception("blue should be between 0 and 255") float_red = red / 255 float_green = green / 255 float_blue = blue / 255 value = max(float_red, float_green, float_blue) chroma = value - min(float_red, float_green, float_blue) saturation = 0 if value == 0 else chroma / value if chroma == 0: hue = 0.0 elif value == float_red: hue = 60 * (0 + (float_green - float_blue) / chroma) elif value == float_green: hue = 60 * (2 + (float_blue - float_red) / chroma) else: hue = 60 * (4 + (float_red - float_green) / chroma) hue = (hue + 360) % 360 return [hue, saturation, value] def approximately_equal_hsv(hsv_1: list[float], hsv_2: list[float]) -> bool: """ Utility-function to check that two hsv-colors are approximately equal >>> approximately_equal_hsv([0, 0, 0], [0, 0, 0]) True >>> approximately_equal_hsv([180, 0.5, 0.3], [179.9999, 0.500001, 0.30001]) True >>> approximately_equal_hsv([0, 0, 0], [1, 0, 0]) False >>> approximately_equal_hsv([180, 0.5, 0.3], [179.9999, 0.6, 0.30001]) False """ check_hue = abs(hsv_1[0] - hsv_2[0]) < 0.2 check_saturation = abs(hsv_1[1] - hsv_2[1]) < 0.002 check_value = abs(hsv_1[2] - hsv_2[2]) < 0.002 return check_hue and check_saturation and check_value
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/binary_to_octal.py
conversions/binary_to_octal.py
""" The function below will convert any binary string to the octal equivalent. >>> bin_to_octal("1111") '17' >>> bin_to_octal("101010101010011") '52523' >>> bin_to_octal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> bin_to_octal("a-1") Traceback (most recent call last): ... ValueError: Non-binary value was passed to the function """ def bin_to_octal(bin_string: str) -> str: if not all(char in "01" for char in bin_string): raise ValueError("Non-binary value was passed to the function") if not bin_string: raise ValueError("Empty string was passed to the function") oct_string = "" while len(bin_string) % 3 != 0: bin_string = "0" + bin_string bin_string_in_3_list = [ bin_string[index : index + 3] for index in range(len(bin_string)) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: oct_val = 0 for index, val in enumerate(bin_group): oct_val += int(2 ** (2 - index) * int(val)) oct_string += str(oct_val) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/hex_to_bin.py
conversions/hex_to_bin.py
def hex_to_bin(hex_num: str) -> int: """ Convert a hexadecimal value to its binary equivalent #https://stackoverflow.com/questions/1425493/convert-hex-to-binary Here, we have used the bitwise right shift operator: >> Shifts the bits of the number to the right and fills 0 on voids left as a result. Similar effect as of dividing the number with some power of two. Example: a = 10 a >> 1 = 5 >>> hex_to_bin("AC") 10101100 >>> hex_to_bin("9A4") 100110100100 >>> hex_to_bin(" 12f ") 100101111 >>> hex_to_bin("FfFf") 1111111111111111 >>> hex_to_bin("-fFfF") -1111111111111111 >>> hex_to_bin("F-f") Traceback (most recent call last): ... ValueError: Invalid value was passed to the function >>> hex_to_bin("") Traceback (most recent call last): ... ValueError: No value was passed to the function """ hex_num = hex_num.strip() if not hex_num: raise ValueError("No value was passed to the function") is_negative = hex_num[0] == "-" if is_negative: hex_num = hex_num[1:] try: int_num = int(hex_num, 16) except ValueError: raise ValueError("Invalid value was passed to the function") bin_str = "" while int_num > 0: bin_str = str(int_num % 2) + bin_str int_num >>= 1 return int(("-" + bin_str) if is_negative else bin_str) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/ipv4_conversion.py
conversions/ipv4_conversion.py
# https://www.geeksforgeeks.org/convert-ip-address-to-integer-and-vice-versa/ def ipv4_to_decimal(ipv4_address: str) -> int: """ Convert an IPv4 address to its decimal representation. Args: ip_address: A string representing an IPv4 address (e.g., "192.168.0.1"). Returns: int: The decimal representation of the IP address. >>> ipv4_to_decimal("192.168.0.1") 3232235521 >>> ipv4_to_decimal("10.0.0.255") 167772415 >>> ipv4_to_decimal("10.0.255") Traceback (most recent call last): ... ValueError: Invalid IPv4 address format >>> ipv4_to_decimal("10.0.0.256") Traceback (most recent call last): ... ValueError: Invalid IPv4 octet 256 """ octets = [int(octet) for octet in ipv4_address.split(".")] if len(octets) != 4: raise ValueError("Invalid IPv4 address format") decimal_ipv4 = 0 for octet in octets: if not 0 <= octet <= 255: raise ValueError(f"Invalid IPv4 octet {octet}") # noqa: EM102 decimal_ipv4 = (decimal_ipv4 << 8) + int(octet) return decimal_ipv4 def alt_ipv4_to_decimal(ipv4_address: str) -> int: """ >>> alt_ipv4_to_decimal("192.168.0.1") 3232235521 >>> alt_ipv4_to_decimal("10.0.0.255") 167772415 """ return int("0x" + "".join(f"{int(i):02x}" for i in ipv4_address.split(".")), 16) def decimal_to_ipv4(decimal_ipv4: int) -> str: """ Convert a decimal representation of an IP address to its IPv4 format. Args: decimal_ipv4: An integer representing the decimal IP address. Returns: The IPv4 representation of the decimal IP address. >>> decimal_to_ipv4(3232235521) '192.168.0.1' >>> decimal_to_ipv4(167772415) '10.0.0.255' >>> decimal_to_ipv4(-1) Traceback (most recent call last): ... ValueError: Invalid decimal IPv4 address """ if not (0 <= decimal_ipv4 <= 4294967295): raise ValueError("Invalid decimal IPv4 address") ip_parts = [] for _ in range(4): ip_parts.append(str(decimal_ipv4 & 255)) decimal_ipv4 >>= 8 return ".".join(reversed(ip_parts)) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/excel_title_to_column.py
conversions/excel_title_to_column.py
def excel_title_to_column(column_title: str) -> int: """ Given a string column_title that represents the column title in an Excel sheet, return its corresponding column number. >>> excel_title_to_column("A") 1 >>> excel_title_to_column("B") 2 >>> excel_title_to_column("AB") 28 >>> excel_title_to_column("Z") 26 """ assert column_title.isupper() answer = 0 index = len(column_title) - 1 power = 0 while index >= 0: value = (ord(column_title[index]) - 64) * pow(26, power) answer += value power += 1 index -= 1 return answer if __name__ == "__main__": from doctest import testmod testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/molecular_chemistry.py
conversions/molecular_chemistry.py
""" Functions useful for doing molecular chemistry: * molarity_to_normality * moles_to_pressure * moles_to_volume * pressure_and_volume_to_temperature """ def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float: """ Convert molarity to normality. Volume is taken in litres. Wikipedia reference: https://en.wikipedia.org/wiki/Equivalent_concentration Wikipedia reference: https://en.wikipedia.org/wiki/Molar_concentration >>> molarity_to_normality(2, 3.1, 0.31) 20 >>> molarity_to_normality(4, 11.4, 5.7) 8 """ return round(float(moles / volume) * nfactor) def moles_to_pressure(volume: float, moles: float, temperature: float) -> float: """ Convert moles to pressure. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> moles_to_pressure(0.82, 3, 300) 90 >>> moles_to_pressure(8.2, 5, 200) 10 """ return round(float((moles * 0.0821 * temperature) / (volume))) def moles_to_volume(pressure: float, moles: float, temperature: float) -> float: """ Convert moles to volume. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> moles_to_volume(0.82, 3, 300) 90 >>> moles_to_volume(8.2, 5, 200) 10 """ return round(float((moles * 0.0821 * temperature) / (pressure))) def pressure_and_volume_to_temperature( pressure: float, moles: float, volume: float ) -> float: """ Convert pressure and volume to temperature. Ideal gas laws are used. Temperature is taken in kelvin. Volume is taken in litres. Pressure has atm as SI unit. Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws Wikipedia reference: https://en.wikipedia.org/wiki/Pressure Wikipedia reference: https://en.wikipedia.org/wiki/Temperature >>> pressure_and_volume_to_temperature(0.82, 1, 2) 20 >>> pressure_and_volume_to_temperature(8.2, 5, 3) 60 """ return round(float((pressure * volume) / (0.0821 * moles))) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/prefix_conversions.py
conversions/prefix_conversions.py
""" Convert International System of Units (SI) and Binary prefixes """ from __future__ import annotations from enum import Enum class SIUnit(Enum): yotta = 24 zetta = 21 exa = 18 peta = 15 tera = 12 giga = 9 mega = 6 kilo = 3 hecto = 2 deca = 1 deci = -1 centi = -2 milli = -3 micro = -6 nano = -9 pico = -12 femto = -15 atto = -18 zepto = -21 yocto = -24 class BinaryUnit(Enum): yotta = 8 zetta = 7 exa = 6 peta = 5 tera = 4 giga = 3 mega = 2 kilo = 1 def convert_si_prefix( known_amount: float, known_prefix: str | SIUnit, unknown_prefix: str | SIUnit, ) -> float: """ Wikipedia reference: https://en.wikipedia.org/wiki/Binary_prefix Wikipedia reference: https://en.wikipedia.org/wiki/International_System_of_Units >>> convert_si_prefix(1, SIUnit.giga, SIUnit.mega) 1000 >>> convert_si_prefix(1, SIUnit.mega, SIUnit.giga) 0.001 >>> convert_si_prefix(1, SIUnit.kilo, SIUnit.kilo) 1 >>> convert_si_prefix(1, 'giga', 'mega') 1000 >>> convert_si_prefix(1, 'gIGa', 'mEGa') 1000 """ if isinstance(known_prefix, str): known_prefix = SIUnit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix = SIUnit[unknown_prefix.lower()] unknown_amount: float = known_amount * ( 10 ** (known_prefix.value - unknown_prefix.value) ) return unknown_amount def convert_binary_prefix( known_amount: float, known_prefix: str | BinaryUnit, unknown_prefix: str | BinaryUnit, ) -> float: """ Wikipedia reference: https://en.wikipedia.org/wiki/Metric_prefix >>> convert_binary_prefix(1, BinaryUnit.giga, BinaryUnit.mega) 1024 >>> convert_binary_prefix(1, BinaryUnit.mega, BinaryUnit.giga) 0.0009765625 >>> convert_binary_prefix(1, BinaryUnit.kilo, BinaryUnit.kilo) 1 >>> convert_binary_prefix(1, 'giga', 'mega') 1024 >>> convert_binary_prefix(1, 'gIGa', 'mEGa') 1024 """ if isinstance(known_prefix, str): known_prefix = BinaryUnit[known_prefix.lower()] if isinstance(unknown_prefix, str): unknown_prefix = BinaryUnit[unknown_prefix.lower()] unknown_amount: float = known_amount * ( 2 ** ((known_prefix.value - unknown_prefix.value) * 10) ) return unknown_amount if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/convert_number_to_words.py
conversions/convert_number_to_words.py
from enum import Enum from typing import Literal class NumberingSystem(Enum): SHORT = ( (15, "quadrillion"), (12, "trillion"), (9, "billion"), (6, "million"), (3, "thousand"), (2, "hundred"), ) LONG = ( (15, "billiard"), (9, "milliard"), (6, "million"), (3, "thousand"), (2, "hundred"), ) INDIAN = ( (14, "crore crore"), (12, "lakh crore"), (7, "crore"), (5, "lakh"), (3, "thousand"), (2, "hundred"), ) @classmethod def max_value(cls, system: str) -> int: """ Gets the max value supported by the given number system. >>> NumberingSystem.max_value("short") == 10**18 - 1 True >>> NumberingSystem.max_value("long") == 10**21 - 1 True >>> NumberingSystem.max_value("indian") == 10**19 - 1 True """ match system_enum := cls[system.upper()]: case cls.SHORT: max_exp = system_enum.value[0][0] + 3 case cls.LONG: max_exp = system_enum.value[0][0] + 6 case cls.INDIAN: max_exp = 19 case _: raise ValueError("Invalid numbering system") return 10**max_exp - 1 class NumberWords(Enum): ONES = { # noqa: RUF012 0: "", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", } TEENS = { # noqa: RUF012 0: "ten", 1: "eleven", 2: "twelve", 3: "thirteen", 4: "fourteen", 5: "fifteen", 6: "sixteen", 7: "seventeen", 8: "eighteen", 9: "nineteen", } TENS = { # noqa: RUF012 2: "twenty", 3: "thirty", 4: "forty", 5: "fifty", 6: "sixty", 7: "seventy", 8: "eighty", 9: "ninety", } def convert_small_number(num: int) -> str: """ Converts small, non-negative integers with irregular constructions in English (i.e., numbers under 100) into words. >>> convert_small_number(0) 'zero' >>> convert_small_number(5) 'five' >>> convert_small_number(10) 'ten' >>> convert_small_number(15) 'fifteen' >>> convert_small_number(20) 'twenty' >>> convert_small_number(25) 'twenty-five' >>> convert_small_number(-1) Traceback (most recent call last): ... ValueError: This function only accepts non-negative integers >>> convert_small_number(123) Traceback (most recent call last): ... ValueError: This function only converts numbers less than 100 """ if num < 0: raise ValueError("This function only accepts non-negative integers") if num >= 100: raise ValueError("This function only converts numbers less than 100") tens, ones = divmod(num, 10) if tens == 0: return NumberWords.ONES.value[ones] or "zero" if tens == 1: return NumberWords.TEENS.value[ones] return ( NumberWords.TENS.value[tens] + ("-" if NumberWords.ONES.value[ones] else "") + NumberWords.ONES.value[ones] ) def convert_number( num: int, system: Literal["short", "long", "indian"] = "short" ) -> str: """ Converts an integer to English words. :param num: The integer to be converted :param system: The numbering system (short, long, or Indian) >>> convert_number(0) 'zero' >>> convert_number(1) 'one' >>> convert_number(100) 'one hundred' >>> convert_number(-100) 'negative one hundred' >>> convert_number(123_456_789_012_345) # doctest: +NORMALIZE_WHITESPACE 'one hundred twenty-three trillion four hundred fifty-six billion seven hundred eighty-nine million twelve thousand three hundred forty-five' >>> convert_number(123_456_789_012_345, "long") # doctest: +NORMALIZE_WHITESPACE 'one hundred twenty-three thousand four hundred fifty-six milliard seven hundred eighty-nine million twelve thousand three hundred forty-five' >>> convert_number(12_34_56_78_90_12_345, "indian") # doctest: +NORMALIZE_WHITESPACE 'one crore crore twenty-three lakh crore forty-five thousand six hundred seventy-eight crore ninety lakh twelve thousand three hundred forty-five' >>> convert_number(10**18) Traceback (most recent call last): ... ValueError: Input number is too large >>> convert_number(10**21, "long") Traceback (most recent call last): ... ValueError: Input number is too large >>> convert_number(10**19, "indian") Traceback (most recent call last): ... ValueError: Input number is too large """ word_groups = [] if num < 0: word_groups.append("negative") num *= -1 if num > NumberingSystem.max_value(system): raise ValueError("Input number is too large") for power, unit in NumberingSystem[system.upper()].value: digit_group, num = divmod(num, 10**power) if digit_group > 0: word_group = ( convert_number(digit_group, system) if digit_group >= 100 else convert_small_number(digit_group) ) word_groups.append(f"{word_group} {unit}") if num > 0 or not word_groups: # word_groups is only empty if input num was 0 word_groups.append(convert_small_number(num)) return " ".join(word_groups) if __name__ == "__main__": import doctest doctest.testmod() print(f"{convert_number(123456789) = }")
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/roman_numerals.py
conversions/roman_numerals.py
ROMAN = [ (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ] def roman_to_int(roman: str) -> int: """ LeetCode No. 13 Roman to Integer Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. https://en.wikipedia.org/wiki/Roman_numerals >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999} >>> all(roman_to_int(key) == value for key, value in tests.items()) True """ vals = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} total = 0 place = 0 while place < len(roman): if (place + 1 < len(roman)) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def int_to_roman(number: int) -> str: """ Given a integer, convert it to an roman numeral. https://en.wikipedia.org/wiki/Roman_numerals >>> tests = {"III": 3, "CLIV": 154, "MIX": 1009, "MMD": 2500, "MMMCMXCIX": 3999} >>> all(int_to_roman(value) == key for key, value in tests.items()) True """ result = [] for arabic, roman in ROMAN: (factor, number) = divmod(number, arabic) result.append(roman * factor) if number == 0: break return "".join(result) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/temperature_conversions.py
conversions/temperature_conversions.py
"""Convert between different units of temperature""" def celsius_to_fahrenheit(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> celsius_to_fahrenheit(273.354, 3) 524.037 >>> celsius_to_fahrenheit(273.354, 0) 524.0 >>> celsius_to_fahrenheit(-40.0) -40.0 >>> celsius_to_fahrenheit(-20.0) -4.0 >>> celsius_to_fahrenheit(0) 32.0 >>> celsius_to_fahrenheit(20) 68.0 >>> celsius_to_fahrenheit("40") 104.0 >>> celsius_to_fahrenheit("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round((float(celsius) * 9 / 5) + 32, ndigits) def celsius_to_kelvin(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> celsius_to_kelvin(273.354, 3) 546.504 >>> celsius_to_kelvin(273.354, 0) 547.0 >>> celsius_to_kelvin(0) 273.15 >>> celsius_to_kelvin(20.0) 293.15 >>> celsius_to_kelvin("40") 313.15 >>> celsius_to_kelvin("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round(float(celsius) + 273.15, ndigits) def celsius_to_rankine(celsius: float, ndigits: int = 2) -> float: """ Convert a given value from Celsius to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Celsius Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> celsius_to_rankine(273.354, 3) 983.707 >>> celsius_to_rankine(273.354, 0) 984.0 >>> celsius_to_rankine(0) 491.67 >>> celsius_to_rankine(20.0) 527.67 >>> celsius_to_rankine("40") 563.67 >>> celsius_to_rankine("celsius") Traceback (most recent call last): ... ValueError: could not convert string to float: 'celsius' """ return round((float(celsius) * 9 / 5) + 491.67, ndigits) def fahrenheit_to_celsius(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> fahrenheit_to_celsius(273.354, 3) 134.086 >>> fahrenheit_to_celsius(273.354, 0) 134.0 >>> fahrenheit_to_celsius(0) -17.78 >>> fahrenheit_to_celsius(20.0) -6.67 >>> fahrenheit_to_celsius(40.0) 4.44 >>> fahrenheit_to_celsius(60) 15.56 >>> fahrenheit_to_celsius(80) 26.67 >>> fahrenheit_to_celsius("100") 37.78 >>> fahrenheit_to_celsius("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round((float(fahrenheit) - 32) * 5 / 9, ndigits) def fahrenheit_to_kelvin(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> fahrenheit_to_kelvin(273.354, 3) 407.236 >>> fahrenheit_to_kelvin(273.354, 0) 407.0 >>> fahrenheit_to_kelvin(0) 255.37 >>> fahrenheit_to_kelvin(20.0) 266.48 >>> fahrenheit_to_kelvin(40.0) 277.59 >>> fahrenheit_to_kelvin(60) 288.71 >>> fahrenheit_to_kelvin(80) 299.82 >>> fahrenheit_to_kelvin("100") 310.93 >>> fahrenheit_to_kelvin("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round(((float(fahrenheit) - 32) * 5 / 9) + 273.15, ndigits) def fahrenheit_to_rankine(fahrenheit: float, ndigits: int = 2) -> float: """ Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> fahrenheit_to_rankine(273.354, 3) 733.024 >>> fahrenheit_to_rankine(273.354, 0) 733.0 >>> fahrenheit_to_rankine(0) 459.67 >>> fahrenheit_to_rankine(20.0) 479.67 >>> fahrenheit_to_rankine(40.0) 499.67 >>> fahrenheit_to_rankine(60) 519.67 >>> fahrenheit_to_rankine(80) 539.67 >>> fahrenheit_to_rankine("100") 559.67 >>> fahrenheit_to_rankine("fahrenheit") Traceback (most recent call last): ... ValueError: could not convert string to float: 'fahrenheit' """ return round(float(fahrenheit) + 459.67, ndigits) def kelvin_to_celsius(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> kelvin_to_celsius(273.354, 3) 0.204 >>> kelvin_to_celsius(273.354, 0) 0.0 >>> kelvin_to_celsius(273.15) 0.0 >>> kelvin_to_celsius(300) 26.85 >>> kelvin_to_celsius("315.5") 42.35 >>> kelvin_to_celsius("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round(float(kelvin) - 273.15, ndigits) def kelvin_to_fahrenheit(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> kelvin_to_fahrenheit(273.354, 3) 32.367 >>> kelvin_to_fahrenheit(273.354, 0) 32.0 >>> kelvin_to_fahrenheit(273.15) 32.0 >>> kelvin_to_fahrenheit(300) 80.33 >>> kelvin_to_fahrenheit("315.5") 108.23 >>> kelvin_to_fahrenheit("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round(((float(kelvin) - 273.15) * 9 / 5) + 32, ndigits) def kelvin_to_rankine(kelvin: float, ndigits: int = 2) -> float: """ Convert a given value from Kelvin to Rankine and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale >>> kelvin_to_rankine(273.354, 3) 492.037 >>> kelvin_to_rankine(273.354, 0) 492.0 >>> kelvin_to_rankine(0) 0.0 >>> kelvin_to_rankine(20.0) 36.0 >>> kelvin_to_rankine("40") 72.0 >>> kelvin_to_rankine("kelvin") Traceback (most recent call last): ... ValueError: could not convert string to float: 'kelvin' """ return round((float(kelvin) * 9 / 5), ndigits) def rankine_to_celsius(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Celsius and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Celsius >>> rankine_to_celsius(273.354, 3) -121.287 >>> rankine_to_celsius(273.354, 0) -121.0 >>> rankine_to_celsius(273.15) -121.4 >>> rankine_to_celsius(300) -106.48 >>> rankine_to_celsius("315.5") -97.87 >>> rankine_to_celsius("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round((float(rankine) - 491.67) * 5 / 9, ndigits) def rankine_to_fahrenheit(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Fahrenheit and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit >>> rankine_to_fahrenheit(273.15) -186.52 >>> rankine_to_fahrenheit(300) -159.67 >>> rankine_to_fahrenheit("315.5") -144.17 >>> rankine_to_fahrenheit("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round(float(rankine) - 459.67, ndigits) def rankine_to_kelvin(rankine: float, ndigits: int = 2) -> float: """ Convert a given value from Rankine to Kelvin and round it to 2 decimal places. Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin >>> rankine_to_kelvin(0) 0.0 >>> rankine_to_kelvin(20.0) 11.11 >>> rankine_to_kelvin("40") 22.22 >>> rankine_to_kelvin("rankine") Traceback (most recent call last): ... ValueError: could not convert string to float: 'rankine' """ return round((float(rankine) * 5 / 9), ndigits) def reaumur_to_kelvin(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to Kelvin and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_kelvin(0) 273.15 >>> reaumur_to_kelvin(20.0) 298.15 >>> reaumur_to_kelvin(40) 323.15 >>> reaumur_to_kelvin("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 1.25 + 273.15), ndigits) def reaumur_to_fahrenheit(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to fahrenheit and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_fahrenheit(0) 32.0 >>> reaumur_to_fahrenheit(20.0) 77.0 >>> reaumur_to_fahrenheit(40) 122.0 >>> reaumur_to_fahrenheit("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 2.25 + 32), ndigits) def reaumur_to_celsius(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to celsius and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_celsius(0) 0.0 >>> reaumur_to_celsius(20.0) 25.0 >>> reaumur_to_celsius(40) 50.0 >>> reaumur_to_celsius("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 1.25), ndigits) def reaumur_to_rankine(reaumur: float, ndigits: int = 2) -> float: """ Convert a given value from reaumur to rankine and round it to 2 decimal places. Reference:- http://www.csgnetwork.com/temp2conv.html >>> reaumur_to_rankine(0) 491.67 >>> reaumur_to_rankine(20.0) 536.67 >>> reaumur_to_rankine(40) 581.67 >>> reaumur_to_rankine("reaumur") Traceback (most recent call last): ... ValueError: could not convert string to float: 'reaumur' """ return round((float(reaumur) * 2.25 + 32 + 459.67), ndigits) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/length_conversion.py
conversions/length_conversion.py
""" Conversion of length units. Available Units:- Metre,Kilometre,Feet,Inch,Centimeter,Yard,Foot,Mile,Millimeter USAGE : -> Import this file into their respective project. -> Use the function length_conversion() for conversion of length units. -> Parameters : -> value : The number of from units you want to convert -> from_type : From which type you want to convert -> to_type : To which type you want to convert REFERENCES : -> Wikipedia reference: https://en.wikipedia.org/wiki/Meter -> Wikipedia reference: https://en.wikipedia.org/wiki/Kilometer -> Wikipedia reference: https://en.wikipedia.org/wiki/Feet -> Wikipedia reference: https://en.wikipedia.org/wiki/Inch -> Wikipedia reference: https://en.wikipedia.org/wiki/Centimeter -> Wikipedia reference: https://en.wikipedia.org/wiki/Yard -> Wikipedia reference: https://en.wikipedia.org/wiki/Foot -> Wikipedia reference: https://en.wikipedia.org/wiki/Mile -> Wikipedia reference: https://en.wikipedia.org/wiki/Millimeter """ from typing import NamedTuple class FromTo(NamedTuple): from_factor: float to_factor: float TYPE_CONVERSION = { "millimeter": "mm", "centimeter": "cm", "meter": "m", "kilometer": "km", "inch": "in", "inche": "in", # Trailing 's' has been stripped off "feet": "ft", "foot": "ft", "yard": "yd", "mile": "mi", } METRIC_CONVERSION = { "mm": FromTo(0.001, 1000), "cm": FromTo(0.01, 100), "m": FromTo(1, 1), "km": FromTo(1000, 0.001), "in": FromTo(0.0254, 39.3701), "ft": FromTo(0.3048, 3.28084), "yd": FromTo(0.9144, 1.09361), "mi": FromTo(1609.34, 0.000621371), } def length_conversion(value: float, from_type: str, to_type: str) -> float: """ Conversion between length units. >>> length_conversion(4, "METER", "FEET") 13.12336 >>> length_conversion(4, "M", "FT") 13.12336 >>> length_conversion(1, "meter", "kilometer") 0.001 >>> length_conversion(1, "kilometer", "inch") 39370.1 >>> length_conversion(3, "kilometer", "mile") 1.8641130000000001 >>> length_conversion(2, "feet", "meter") 0.6096 >>> length_conversion(4, "feet", "yard") 1.333329312 >>> length_conversion(1, "inch", "meter") 0.0254 >>> length_conversion(2, "inch", "mile") 3.15656468e-05 >>> length_conversion(2, "centimeter", "millimeter") 20.0 >>> length_conversion(2, "centimeter", "yard") 0.0218722 >>> length_conversion(4, "yard", "meter") 3.6576 >>> length_conversion(4, "yard", "kilometer") 0.0036576 >>> length_conversion(3, "foot", "meter") 0.9144000000000001 >>> length_conversion(3, "foot", "inch") 36.00001944 >>> length_conversion(4, "mile", "kilometer") 6.43736 >>> length_conversion(2, "miles", "InChEs") 126719.753468 >>> length_conversion(3, "millimeter", "centimeter") 0.3 >>> length_conversion(3, "mm", "in") 0.1181103 >>> length_conversion(4, "wrongUnit", "inch") Traceback (most recent call last): ... ValueError: Invalid 'from_type' value: 'wrongUnit'. Conversion abbreviations are: mm, cm, m, km, in, ft, yd, mi """ new_from = from_type.lower().rstrip("s") new_from = TYPE_CONVERSION.get(new_from, new_from) new_to = to_type.lower().rstrip("s") new_to = TYPE_CONVERSION.get(new_to, new_to) if new_from not in METRIC_CONVERSION: msg = ( f"Invalid 'from_type' value: {from_type!r}.\n" f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}" ) raise ValueError(msg) if new_to not in METRIC_CONVERSION: msg = ( f"Invalid 'to_type' value: {to_type!r}.\n" f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}" ) raise ValueError(msg) return ( value * METRIC_CONVERSION[new_from].from_factor * METRIC_CONVERSION[new_to].to_factor ) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/speed_conversions.py
conversions/speed_conversions.py
""" Convert speed units https://en.wikipedia.org/wiki/Kilometres_per_hour https://en.wikipedia.org/wiki/Miles_per_hour https://en.wikipedia.org/wiki/Knot_(unit) https://en.wikipedia.org/wiki/Metre_per_second """ speed_chart: dict[str, float] = { "km/h": 1.0, "m/s": 3.6, "mph": 1.609344, "knot": 1.852, } speed_chart_inverse: dict[str, float] = { "km/h": 1.0, "m/s": 0.277777778, "mph": 0.621371192, "knot": 0.539956803, } def convert_speed(speed: float, unit_from: str, unit_to: str) -> float: """ Convert speed from one unit to another using the speed_chart above. "km/h": 1.0, "m/s": 3.6, "mph": 1.609344, "knot": 1.852, >>> convert_speed(100, "km/h", "m/s") 27.778 >>> convert_speed(100, "km/h", "mph") 62.137 >>> convert_speed(100, "km/h", "knot") 53.996 >>> convert_speed(100, "m/s", "km/h") 360.0 >>> convert_speed(100, "m/s", "mph") 223.694 >>> convert_speed(100, "m/s", "knot") 194.384 >>> convert_speed(100, "mph", "km/h") 160.934 >>> convert_speed(100, "mph", "m/s") 44.704 >>> convert_speed(100, "mph", "knot") 86.898 >>> convert_speed(100, "knot", "km/h") 185.2 >>> convert_speed(100, "knot", "m/s") 51.444 >>> convert_speed(100, "knot", "mph") 115.078 """ if unit_to not in speed_chart or unit_from not in speed_chart_inverse: msg = ( f"Incorrect 'from_type' or 'to_type' value: {unit_from!r}, {unit_to!r}\n" f"Valid values are: {', '.join(speed_chart_inverse)}" ) raise ValueError(msg) return round(speed * speed_chart[unit_from] * speed_chart_inverse[unit_to], 3) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/octal_to_decimal.py
conversions/octal_to_decimal.py
def oct_to_decimal(oct_string: str) -> int: """ Convert a octal value to its decimal equivalent >>> oct_to_decimal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> oct_to_decimal("-") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function >>> oct_to_decimal("e") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function >>> oct_to_decimal("8") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function >>> oct_to_decimal("-e") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function >>> oct_to_decimal("-8") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function >>> oct_to_decimal("1") 1 >>> oct_to_decimal("-1") -1 >>> oct_to_decimal("12") 10 >>> oct_to_decimal(" 12 ") 10 >>> oct_to_decimal("-45") -37 >>> oct_to_decimal("-") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function >>> oct_to_decimal("0") 0 >>> oct_to_decimal("-4055") -2093 >>> oct_to_decimal("2-0Fm") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function >>> oct_to_decimal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> oct_to_decimal("19") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function """ oct_string = str(oct_string).strip() if not oct_string: raise ValueError("Empty string was passed to the function") is_negative = oct_string[0] == "-" if is_negative: oct_string = oct_string[1:] if not oct_string.isdigit() or not all(0 <= int(char) <= 7 for char in oct_string): raise ValueError("Non-octal value was passed to the function") decimal_number = 0 for char in oct_string: decimal_number = 8 * decimal_number + int(char) if is_negative: decimal_number = -decimal_number return decimal_number if __name__ == "__main__": from doctest import testmod testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/decimal_to_hexadecimal.py
conversions/decimal_to_hexadecimal.py
"""Convert Base 10 (Decimal) Values to Hexadecimal Representations""" # set decimal value for each hexadecimal digit values = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f", } def decimal_to_hexadecimal(decimal: float) -> str: """ take integer decimal value, return hexadecimal representation as str beginning with 0x >>> decimal_to_hexadecimal(5) '0x5' >>> decimal_to_hexadecimal(15) '0xf' >>> decimal_to_hexadecimal(37) '0x25' >>> decimal_to_hexadecimal(255) '0xff' >>> decimal_to_hexadecimal(4096) '0x1000' >>> decimal_to_hexadecimal(999098) '0xf3eba' >>> # negatives work too >>> decimal_to_hexadecimal(-256) '-0x100' >>> # floats are acceptable if equivalent to an int >>> decimal_to_hexadecimal(17.0) '0x11' >>> # other floats will error >>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError >>> # strings will error as well >>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError >>> # results are the same when compared to Python's default hex function >>> decimal_to_hexadecimal(-256) == hex(-256) True """ assert isinstance(decimal, (int, float)) assert decimal == int(decimal) decimal = int(decimal) hexadecimal = "" negative = False if decimal < 0: negative = True decimal *= -1 while decimal > 0: decimal, remainder = divmod(decimal, 16) hexadecimal = values[remainder] + hexadecimal hexadecimal = "0x" + hexadecimal if negative: hexadecimal = "-" + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/prefix_conversions_string.py
conversions/prefix_conversions_string.py
""" * Author: Manuel Di Lullo (https://github.com/manueldilullo) * Description: Convert a number to use the correct SI or Binary unit prefix. Inspired by prefix_conversion.py file in this repository by lance-pyles URL: https://en.wikipedia.org/wiki/Metric_prefix#List_of_SI_prefixes URL: https://en.wikipedia.org/wiki/Binary_prefix """ from __future__ import annotations from enum import Enum, unique from typing import TypeVar # Create a generic variable that can be 'Enum', or any subclass. T = TypeVar("T", bound="Enum") @unique class BinaryUnit(Enum): yotta = 80 zetta = 70 exa = 60 peta = 50 tera = 40 giga = 30 mega = 20 kilo = 10 @unique class SIUnit(Enum): yotta = 24 zetta = 21 exa = 18 peta = 15 tera = 12 giga = 9 mega = 6 kilo = 3 hecto = 2 deca = 1 deci = -1 centi = -2 milli = -3 micro = -6 nano = -9 pico = -12 femto = -15 atto = -18 zepto = -21 yocto = -24 @classmethod def get_positive(cls) -> dict: """ Returns a dictionary with only the elements of this enum that has a positive value >>> from itertools import islice >>> positive = SIUnit.get_positive() >>> inc = iter(positive.items()) >>> dict(islice(inc, len(positive) // 2)) {'yotta': 24, 'zetta': 21, 'exa': 18, 'peta': 15, 'tera': 12} >>> dict(inc) {'giga': 9, 'mega': 6, 'kilo': 3, 'hecto': 2, 'deca': 1} """ return {unit.name: unit.value for unit in cls if unit.value > 0} @classmethod def get_negative(cls) -> dict: """ Returns a dictionary with only the elements of this enum that has a negative value @example >>> from itertools import islice >>> negative = SIUnit.get_negative() >>> inc = iter(negative.items()) >>> dict(islice(inc, len(negative) // 2)) {'deci': -1, 'centi': -2, 'milli': -3, 'micro': -6, 'nano': -9} >>> dict(inc) {'pico': -12, 'femto': -15, 'atto': -18, 'zepto': -21, 'yocto': -24} """ return {unit.name: unit.value for unit in cls if unit.value < 0} def add_si_prefix(value: float) -> str: """ Function that converts a number to his version with SI prefix @input value (an integer) @example: >>> add_si_prefix(10000) '10.0 kilo' """ prefixes = SIUnit.get_positive() if value > 0 else SIUnit.get_negative() for name_prefix, value_prefix in prefixes.items(): numerical_part = value / (10**value_prefix) if numerical_part > 1: return f"{numerical_part!s} {name_prefix}" return str(value) def add_binary_prefix(value: float) -> str: """ Function that converts a number to his version with Binary prefix @input value (an integer) @example: >>> add_binary_prefix(65536) '64.0 kilo' """ for prefix in BinaryUnit: numerical_part = value / (2**prefix.value) if numerical_part > 1: return f"{numerical_part!s} {prefix.name}" return str(value) if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/__init__.py
conversions/__init__.py
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/astronomical_length_scale_conversion.py
conversions/astronomical_length_scale_conversion.py
""" Conversion of length units. Available Units: Metre, Kilometre, Megametre, Gigametre, Terametre, Petametre, Exametre, Zettametre, Yottametre USAGE : -> Import this file into their respective project. -> Use the function length_conversion() for conversion of length units. -> Parameters : -> value : The number of from units you want to convert -> from_type : From which type you want to convert -> to_type : To which type you want to convert REFERENCES : -> Wikipedia reference: https://en.wikipedia.org/wiki/Meter -> Wikipedia reference: https://en.wikipedia.org/wiki/Kilometer -> Wikipedia reference: https://en.wikipedia.org/wiki/Orders_of_magnitude_(length) """ UNIT_SYMBOL = { "meter": "m", "kilometer": "km", "megametre": "Mm", "gigametre": "Gm", "terametre": "Tm", "petametre": "Pm", "exametre": "Em", "zettametre": "Zm", "yottametre": "Ym", } # Exponent of the factor(meter) METRIC_CONVERSION = { "m": 0, "km": 3, "Mm": 6, "Gm": 9, "Tm": 12, "Pm": 15, "Em": 18, "Zm": 21, "Ym": 24, } def length_conversion(value: float, from_type: str, to_type: str) -> float: """ Conversion between astronomical length units. >>> length_conversion(1, "meter", "kilometer") 0.001 >>> length_conversion(1, "meter", "megametre") 1e-06 >>> length_conversion(1, "gigametre", "meter") 1000000000 >>> length_conversion(1, "gigametre", "terametre") 0.001 >>> length_conversion(1, "petametre", "terametre") 1000 >>> length_conversion(1, "petametre", "exametre") 0.001 >>> length_conversion(1, "terametre", "zettametre") 1e-09 >>> length_conversion(1, "yottametre", "zettametre") 1000 >>> length_conversion(4, "wrongUnit", "inch") Traceback (most recent call last): ... ValueError: Invalid 'from_type' value: 'wrongUnit'. Conversion abbreviations are: m, km, Mm, Gm, Tm, Pm, Em, Zm, Ym """ from_sanitized = from_type.lower().strip("s") to_sanitized = to_type.lower().strip("s") from_sanitized = UNIT_SYMBOL.get(from_sanitized, from_sanitized) to_sanitized = UNIT_SYMBOL.get(to_sanitized, to_sanitized) if from_sanitized not in METRIC_CONVERSION: msg = ( f"Invalid 'from_type' value: {from_type!r}.\n" f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}" ) raise ValueError(msg) if to_sanitized not in METRIC_CONVERSION: msg = ( f"Invalid 'to_type' value: {to_type!r}.\n" f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}" ) raise ValueError(msg) from_exponent = METRIC_CONVERSION[from_sanitized] to_exponent = METRIC_CONVERSION[to_sanitized] exponent = 1 if from_exponent > to_exponent: exponent = from_exponent - to_exponent else: exponent = -(to_exponent - from_exponent) return value * pow(10, exponent) if __name__ == "__main__": from doctest import testmod testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/octal_to_binary.py
conversions/octal_to_binary.py
""" * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) * Description: Convert a Octal number to Binary. References for better understanding: https://en.wikipedia.org/wiki/Binary_number https://en.wikipedia.org/wiki/Octal """ def octal_to_binary(octal_number: str) -> str: """ Convert an Octal number to Binary. >>> octal_to_binary("17") '001111' >>> octal_to_binary("7") '111' >>> octal_to_binary("Av") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function >>> octal_to_binary("@#") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function >>> octal_to_binary("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function """ if not octal_number: raise ValueError("Empty string was passed to the function") binary_number = "" octal_digits = "01234567" for digit in octal_number: if digit not in octal_digits: raise ValueError("Non-octal value was passed to the function") binary_digit = "" value = int(digit) for _ in range(3): binary_digit = str(value % 2) + binary_digit value //= 2 binary_number += binary_digit return binary_number if __name__ == "__main__": import doctest doctest.testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/binary_to_decimal.py
conversions/binary_to_decimal.py
def bin_to_decimal(bin_string: str) -> int: """ Convert a binary value to its decimal equivalent >>> bin_to_decimal("101") 5 >>> bin_to_decimal(" 1010 ") 10 >>> bin_to_decimal("-11101") -29 >>> bin_to_decimal("0") 0 >>> bin_to_decimal("a") Traceback (most recent call last): ... ValueError: Non-binary value was passed to the function >>> bin_to_decimal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> bin_to_decimal("39") Traceback (most recent call last): ... ValueError: Non-binary value was passed to the function """ bin_string = str(bin_string).strip() if not bin_string: raise ValueError("Empty string was passed to the function") is_negative = bin_string[0] == "-" if is_negative: bin_string = bin_string[1:] if not all(char in "01" for char in bin_string): raise ValueError("Non-binary value was passed to the function") decimal_number = 0 for char in bin_string: decimal_number = 2 * decimal_number + int(char) return -decimal_number if is_negative else decimal_number if __name__ == "__main__": from doctest import testmod testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/hexadecimal_to_decimal.py
conversions/hexadecimal_to_decimal.py
hex_table = {hex(i)[2:]: i for i in range(16)} # Use [:2] to strip off the leading '0x' def hex_to_decimal(hex_string: str) -> int: """ Convert a hexadecimal value to its decimal equivalent #https://www.programiz.com/python-programming/methods/built-in/hex >>> hex_to_decimal("a") 10 >>> hex_to_decimal("12f") 303 >>> hex_to_decimal(" 12f ") 303 >>> hex_to_decimal("FfFf") 65535 >>> hex_to_decimal("-Ff") -255 >>> hex_to_decimal("F-f") Traceback (most recent call last): ... ValueError: Non-hexadecimal value was passed to the function >>> hex_to_decimal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> hex_to_decimal("12m") Traceback (most recent call last): ... ValueError: Non-hexadecimal value was passed to the function """ hex_string = hex_string.strip().lower() if not hex_string: raise ValueError("Empty string was passed to the function") is_negative = hex_string[0] == "-" if is_negative: hex_string = hex_string[1:] if not all(char in hex_table for char in hex_string): raise ValueError("Non-hexadecimal value was passed to the function") decimal_number = 0 for char in hex_string: decimal_number = 16 * decimal_number + hex_table[char] return -decimal_number if is_negative else decimal_number if __name__ == "__main__": from doctest import testmod testmod()
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false
TheAlgorithms/Python
https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/conversions/decimal_to_any.py
conversions/decimal_to_any.py
"""Convert a positive Decimal Number to Any Other Representation""" from string import ascii_uppercase ALPHABET_VALUES = {str(ord(c) - 55): c for c in ascii_uppercase} def decimal_to_any(num: int, base: int) -> str: """ Convert a positive integer to another base as str. >>> decimal_to_any(0, 2) '0' >>> decimal_to_any(5, 4) '11' >>> decimal_to_any(20, 3) '202' >>> decimal_to_any(58, 16) '3A' >>> decimal_to_any(243, 17) 'E5' >>> decimal_to_any(34923, 36) 'QY3' >>> decimal_to_any(10, 11) 'A' >>> decimal_to_any(16, 16) '10' >>> decimal_to_any(36, 36) '10' >>> # negatives will error >>> decimal_to_any(-45, 8) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: parameter must be positive int >>> # floats will error >>> decimal_to_any(34.4, 6) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: int() can't convert non-string with explicit base >>> # a float base will error >>> decimal_to_any(5, 2.5) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> # a str base will error >>> decimal_to_any(10, '16') # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'str' object cannot be interpreted as an integer >>> # a base less than 2 will error >>> decimal_to_any(7, 0) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: base must be >= 2 >>> # a base greater than 36 will error >>> decimal_to_any(34, 37) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: base must be <= 36 """ if isinstance(num, float): raise TypeError("int() can't convert non-string with explicit base") if num < 0: raise ValueError("parameter must be positive int") if isinstance(base, str): raise TypeError("'str' object cannot be interpreted as an integer") if isinstance(base, float): raise TypeError("'float' object cannot be interpreted as an integer") if base in (0, 1): raise ValueError("base must be >= 2") if base > 36: raise ValueError("base must be <= 36") new_value = "" mod = 0 div = 0 while div != 1: div, mod = divmod(num, base) if base >= 11 and 9 < mod < 36: actual_value = ALPHABET_VALUES[str(mod)] else: actual_value = str(mod) new_value += actual_value div = num // base num = div if div == 0: return str(new_value[::-1]) elif div == 1: new_value += str(div) return str(new_value[::-1]) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 37): for num in range(1000): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
python
MIT
2c15b8c54eb8130e83640fe1d911c10eb6cd70d4
2026-01-04T14:38:15.231112Z
false