instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Generate docstrings for each module | # -*- coding: utf-8 -*-
import re
import sys
import random
from typing import List, Tuple
import requests
from requests.models import Response
def find_links_in_text(text: str) -> List[str]:
link_pattern = re.compile(r'((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()... | --- +++ @@ -10,6 +10,7 @@
def find_links_in_text(text: str) -> List[str]:
+ """Find links in a text and return a list of URLs."""
link_pattern = re.compile(r'((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`... | https://raw.githubusercontent.com/public-apis/public-apis/HEAD/scripts/validate/links.py |
Add docstrings that explain purpose and usage | #!/usr/bin/env python3
import sys
import os
import argparse
import re
import yaml
from bidi.algorithm import get_display
def load_config(path):
# Default configuration values
default = {
'ltr_keywords': [],
'ltr_symbols': [],
'pure_ltr_pattern': r"^[\u0000-\u007F]+$", # Matches ASCII ... | --- +++ @@ -1,4 +1,23 @@ #!/usr/bin/env python3
+"""
+RTL/LTR Markdown Linter.
+
+This script analyzes Markdown files to identify potential issues
+in the display of mixed Right-To-Left (RTL) and Left-To-Right (LTR) text.
+It reads configuration from a `rtl_linter_config.yml` file located in the same
+directory as the ... | https://raw.githubusercontent.com/EbookFoundation/free-programming-books/HEAD/scripts/rtl_ltr_linter.py |
Write docstrings that follow conventions | from abc import ABCMeta, abstractmethod
from enum import Enum
import sys
class Suit(Enum):
HEART = 0
DIAMOND = 1
CLUBS = 2
SPADE = 3
class Card(metaclass=ABCMeta):
def __init__(self, value, suit):
self.value = value
self.suit = suit
self.is_available = True
@proper... | --- +++ @@ -38,6 +38,7 @@ return True if self._value == 1 else False
def is_face_card(self):
+ """Jack = 11, Queen = 12, King = 13"""
return True if 10 < self._value <= 13 else False
@property
@@ -90,6 +91,7 @@ return max_under if max_under != -sys.MAXSIZE else min_over
... | https://raw.githubusercontent.com/donnemartin/system-design-primer/HEAD/solutions/object_oriented_design/deck_of_cards/deck_of_cards.py |
Create docstrings for reusable components | # -*- coding: utf-8 -*-
class QueryApi(object):
def __init__(self, memory_cache, reverse_index_cluster):
self.memory_cache = memory_cache
self.reverse_index_cluster = reverse_index_cluster
def parse_query(self, query):
...
def process_query(self, query):
query = self.par... | --- +++ @@ -8,6 +8,9 @@ self.reverse_index_cluster = reverse_index_cluster
def parse_query(self, query):
+ """Remove markup, break text into terms, deal with typos,
+ normalize capitalization, convert to use boolean operations.
+ """
...
def process_query(self, query)... | https://raw.githubusercontent.com/donnemartin/system-design-primer/HEAD/solutions/system_design/query_cache/query_cache_snippets.py |
Provide clean and structured docstrings | from abc import ABCMeta, abstractmethod
from enum import Enum
class VehicleSize(Enum):
MOTORCYCLE = 0
COMPACT = 1
LARGE = 2
class Vehicle(metaclass=ABCMeta):
def __init__(self, vehicle_size, license_plate, spot_size):
self.vehicle_size = vehicle_size
self.license_plate = license_pl... | --- +++ @@ -92,9 +92,11 @@ return spot
def _find_available_spot(self, vehicle):
+ """Find an available spot where vehicle can fit, or return None"""
pass
def _park_starting_at_spot(self, spot, vehicle):
+ """Occupy starting at spot.spot_number to vehicle.spot_size."""
... | https://raw.githubusercontent.com/donnemartin/system-design-primer/HEAD/solutions/object_oriented_design/parking_lot/parking_lot.py |
Help me comply with documentation standards | class Node(object):
def __init__(self, results):
self.results = results
self.next = next
class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def move_to_front(self, node):
pass
def append_to_front(self, node):
pass
de... | --- +++ @@ -30,6 +30,10 @@ self.linked_list = LinkedList()
def get(self, query):
+ """Get the stored query result from the cache.
+
+ Accessing a node updates its position to the front of the LRU list.
+ """
node = self.lookup.get(query)
if node is None:
... | https://raw.githubusercontent.com/donnemartin/system-design-primer/HEAD/solutions/object_oriented_design/lru_cache/lru_cache.py |
Add detailed docstrings explaining each function | # -*- coding: utf-8 -*-
class PagesDataStore(object):
def __init__(self, db):
self.db = db
pass
def add_link_to_crawl(self, url):
pass
def remove_link_to_crawl(self, url):
pass
def reduce_priority_link_to_crawl(self, url):
pass
def extract_max_priority_... | --- +++ @@ -8,21 +8,27 @@ pass
def add_link_to_crawl(self, url):
+ """Add the given link to `links_to_crawl`."""
pass
def remove_link_to_crawl(self, url):
+ """Remove the given link from `links_to_crawl`."""
pass
def reduce_priority_link_to_crawl(self, url):
... | https://raw.githubusercontent.com/donnemartin/system-design-primer/HEAD/solutions/system_design/web_crawler/web_crawler_snippets.py |
Write reusable docstrings | # -*- coding: utf-8 -*-
from mrjob.job import MRJob
class SalesRanker(MRJob):
def within_past_week(self, timestamp):
...
def mapper(self, _, line):
timestamp, product_id, category, quantity = line.split('\t')
if self.within_past_week(timestamp):
yield (category, product_... | --- +++ @@ -6,17 +6,56 @@ class SalesRanker(MRJob):
def within_past_week(self, timestamp):
+ """Return True if timestamp is within past week, False otherwise."""
...
def mapper(self, _, line):
+ """Parse each log line, extract and transform relevant lines.
+
+ Emit key value ... | https://raw.githubusercontent.com/donnemartin/system-design-primer/HEAD/solutions/system_design/sales_rank/sales_rank_mapreduce.py |
Add docstrings to incomplete code | # -*- coding: utf-8 -*-
from mrjob.job import MRJob
class SpendingByCategory(MRJob):
def __init__(self, categorizer):
self.categorizer = categorizer
...
def current_year_month(self):
...
def extract_year_month(self, timestamp):
...
def handle_budget_notifications(s... | --- +++ @@ -10,26 +10,43 @@ ...
def current_year_month(self):
+ """Return the current year and month."""
...
def extract_year_month(self, timestamp):
+ """Return the year and month portions of the timestamp."""
...
def handle_budget_notifications(self, key, t... | https://raw.githubusercontent.com/donnemartin/system-design-primer/HEAD/solutions/system_design/mint/mint_mapreduce.py |
Create simple docstrings for beginners | # -*- coding: utf-8 -*-
from mrjob.job import MRJob
class HitCounts(MRJob):
def extract_url(self, line):
pass
def extract_year_month(self, line):
pass
def mapper(self, _, line):
url = self.extract_url(line)
period = self.extract_year_month(line)
yield (period, u... | --- +++ @@ -6,20 +6,36 @@ class HitCounts(MRJob):
def extract_url(self, line):
+ """Extract the generated url from the log line."""
pass
def extract_year_month(self, line):
+ """Return the year and month portions of the timestamp."""
pass
def mapper(self, _, line):
+... | https://raw.githubusercontent.com/donnemartin/system-design-primer/HEAD/solutions/system_design/pastebin/pastebin.py |
Add docstrings for better understanding | #!/usr/bin/env python3
import json
import os
import re
import sys
from datetime import datetime, timezone
from pathlib import Path
import httpx
from build import extract_github_repo, load_stars
CACHE_MAX_AGE_HOURS = 12
DATA_DIR = Path(__file__).parent / "data"
CACHE_FILE = DATA_DIR / "github_stars.json"
README_PATH... | --- +++ @@ -1,4 +1,5 @@ #!/usr/bin/env python3
+"""Fetch GitHub star counts and owner info for all GitHub repos in README.md."""
import json
import os
@@ -20,6 +21,7 @@
def extract_github_repos(text: str) -> set[str]:
+ """Extract unique owner/repo pairs from GitHub URLs in markdown text."""
repos = set... | https://raw.githubusercontent.com/vinta/awesome-python/HEAD/website/fetch_github_stars.py |
Document all public functions with docstrings |
from __future__ import annotations
import re
from typing import TypedDict
from markdown_it import MarkdownIt
from markdown_it.tree import SyntaxTreeNode
from markupsafe import escape
class AlsoSee(TypedDict):
name: str
url: str
class ParsedEntry(TypedDict):
name: str
url: str
description: str... | --- +++ @@ -1,3 +1,4 @@+"""Parse README.md into structured section data using markdown-it-py AST."""
from __future__ import annotations
@@ -39,6 +40,7 @@
def slugify(name: str) -> str:
+ """Convert a category name to a URL-friendly slug."""
slug = name.lower()
slug = _SLUG_NON_ALNUM_RE.sub("", slu... | https://raw.githubusercontent.com/vinta/awesome-python/HEAD/website/readme_parser.py |
Help me document legacy Python code | #!/usr/bin/env python3
import json
import re
import shutil
from pathlib import Path
from typing import TypedDict
from jinja2 import Environment, FileSystemLoader
from readme_parser import parse_readme, slugify
# Thematic grouping of categories. Each category name must match exactly
# as it appears in README.md (the ... | --- +++ @@ -1,4 +1,5 @@ #!/usr/bin/env python3
+"""Build a single-page HTML site from README.md for the awesome-python website."""
import json
import re
@@ -153,6 +154,7 @@ categories: list[dict],
resources: list[dict],
) -> list[dict]:
+ """Organize categories and resources into thematic section group... | https://raw.githubusercontent.com/vinta/awesome-python/HEAD/website/build.py |
Generate docstrings with examples | from __future__ import annotations
class IIRFilter:
def __init__(self, order: int) -> None:
self.order = order
# a_{0} ... a_{k}
self.a_coeffs = [1.0] + [0.0] * order
# b_{0} ... b_{k}
self.b_coeffs = [1.0] + [0.0] * order
# x[n-1] ... x[n-k]
self.input_h... | --- +++ @@ -2,6 +2,26 @@
class IIRFilter:
+ r"""
+ N-Order IIR filter
+ Assumes working with float samples normalized on [-1, 1]
+
+ ---
+
+ Implementation details:
+ Based on the 2nd-order function from
+ https://en.wikipedia.org/wiki/Digital_biquad_filter,
+ this generalized N-order functi... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/audio_filters/iir_filter.py |
Add docstrings to make code maintainable |
def backtrack(
partial: str, open_count: int, close_count: int, n: int, result: list[str]
) -> None:
if len(partial) == 2 * n:
# When the combination is complete, add it to the result.
result.append(partial)
return
if open_count < n:
# If we can add an open parenthesis, do... | --- +++ @@ -1,8 +1,35 @@+"""
+author: Aayush Soni
+Given n pairs of parentheses, write a function to generate all
+combinations of well-formed parentheses.
+Input: n = 2
+Output: ["(())","()()"]
+Leetcode link: https://leetcode.com/problems/generate-parentheses/description/
+"""
def backtrack(
partial: str, o... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/generate_parentheses.py |
Add missing documentation to my Python functions |
def backtrack(
needed_sum: int,
power: int,
current_number: int,
current_sum: int,
solutions_count: int,
) -> tuple[int, int]:
if current_sum == needed_sum:
# If the sum of the powers is equal to needed_sum, then we have a solution.
solutions_count += 1
return current_s... | --- +++ @@ -1,3 +1,10 @@+"""
+Problem source: https://www.hackerrank.com/challenges/the-power-sum/problem
+Find the number of ways that a given integer X, can be expressed as the sum
+of the Nth powers of unique, natural numbers. For example, if X=13 and N=2.
+We have to find all combinations of unique squares adding u... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/power_sum.py |
Document my Python code with docstrings |
from __future__ import annotations
from typing import Any
def generate_all_subsequences(sequence: list[Any]) -> None:
create_state_space_tree(sequence, [], 0)
def create_state_space_tree(
sequence: list[Any], current_subsequence: list[Any], index: int
) -> None:
if index == len(sequence):
pri... | --- +++ @@ -1,3 +1,10 @@+"""
+In this problem, we want to determine all possible subsequences
+of the given sequence. We use backtracking to solve this problem.
+
+Time complexity: O(2^n),
+where n denotes the length of the given sequence.
+"""
from __future__ import annotations
@@ -11,6 +18,61 @@ def create_state... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/all_subsequences.py |
Add missing documentation to my Python functions |
from __future__ import annotations
solution = []
def is_safe(board: list[list[int]], row: int, column: int) -> bool:
n = len(board) # Size of the board
# Check if there is any queen in the same upper column,
# left upper diagonal and right upper diagonal
return (
all(board[i][j] != 1 for ... | --- +++ @@ -1,3 +1,12 @@+"""
+
+The nqueens problem is of placing N queens on a N * N
+chess board such that no queen can attack any other queens placed
+on that chess board.
+This means that one queen cannot have any other queen on its horizontal, vertical and
+diagonal lines.
+
+"""
from __future__ import annotati... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/n_queens.py |
Write docstrings including parameters and return values | from math import cos, sin, sqrt, tau
from audio_filters.iir_filter import IIRFilter
"""
Create 2nd-order IIR filters with Butterworth design.
Code based on https://webaudio.github.io/Audio-EQ-Cookbook/audio-eq-cookbook.html
Alternatively you can use scipy.signal.butter, which should yield the same results.
"""
def... | --- +++ @@ -15,6 +15,14 @@ samplerate: int,
q_factor: float = 1 / sqrt(2),
) -> IIRFilter:
+ """
+ Creates a low-pass filter
+
+ >>> filter = make_lowpass(1000, 48000)
+ >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE
+ [1.0922959556412573, -1.9828897227476208, 0.9077040... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/audio_filters/butterworth_filter.py |
Create docstrings for each class method |
from __future__ import annotations
def generate_all_permutations(sequence: list[int | str]) -> None:
create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))])
def create_state_space_tree(
sequence: list[int | str],
current_sequence: list[int | str],
index: int,
index_used: lis... | --- +++ @@ -1,3 +1,10 @@+"""
+In this problem, we want to determine all possible permutations
+of the given sequence. We use backtracking to solve this problem.
+
+Time complexity: O(n! * n),
+where n denotes the length of the given sequence.
+"""
from __future__ import annotations
@@ -12,6 +19,47 @@ index: in... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/all_permutations.py |
Write docstrings that follow conventions |
import string
def backtrack(
current_word: str, path: list[str], end_word: str, word_set: set[str]
) -> list[str]:
# Base case: If the current word is the end word, return the path
if current_word == end_word:
return path
# Try all possible single-letter transformations
for i in range(l... | --- +++ @@ -1,3 +1,13 @@+"""
+Word Ladder is a classic problem in computer science.
+The problem is to transform a start word into an end word
+by changing one letter at a time.
+Each intermediate word must be a valid word from a given list of words.
+The goal is to find a transformation sequence
+from the start word t... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/word_ladder.py |
Add docstrings for utility scripts |
from __future__ import annotations
from itertools import combinations
def combination_lists(n: int, k: int) -> list[list[int]]:
return [list(x) for x in combinations(range(1, n + 1), k)]
def generate_all_combinations(n: int, k: int) -> list[list[int]]:
if k < 0:
raise ValueError("k must not be neg... | --- +++ @@ -1,3 +1,9 @@+"""
+In this problem, we want to determine all possible combinations of k
+numbers out of 1 ... n. We use backtracking to solve this problem.
+
+Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!))),
+"""
from __future__ import annotations
@@ -5,10 +11,46 @@
def co... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/all_combinations.py |
Insert docstrings into my code |
def valid_connection(
graph: list[list[int]], next_ver: int, curr_ind: int, path: list[int]
) -> bool:
# 1. Validate that path exists between current and next vertices
if graph[path[curr_ind - 1]][next_ver] == 0:
return False
# 2. Validate that next vertex is not already in path
return n... | --- +++ @@ -1,8 +1,42 @@+"""
+A Hamiltonian cycle (Hamiltonian circuit) is a graph cycle
+through a graph that visits each node exactly once.
+Determining whether such paths and cycles exist in graphs
+is the 'Hamiltonian path problem', which is NP-complete.
+
+Wikipedia: https://en.wikipedia.org/wiki/Hamiltonian_path
... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/hamiltonian_cycle.py |
Create documentation for each function signature |
from __future__ import annotations
import math
def minimax(
depth: int, node_index: int, is_max: bool, scores: list[int], height: float
) -> int:
if depth < 0:
raise ValueError("Depth cannot be less than 0")
if len(scores) == 0:
raise ValueError("Scores cannot be empty")
# Base cas... | --- +++ @@ -1,3 +1,12 @@+"""
+Minimax helps to achieve maximum score in a game by checking all possible moves
+depth is current depth in game tree.
+
+nodeIndex is index of current node in scores[].
+if move is of maximizer return true else false
+leaves of game tree is stored in scores[]
+height is maximum height of G... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/minimax.py |
Document my Python code with docstrings |
from __future__ import annotations
def depth_first_search(
possible_board: list[int],
diagonal_right_collisions: list[int],
diagonal_left_collisions: list[int],
boards: list[list[str]],
n: int,
) -> None:
# Get next row in the current board (possible_board) to fill it with a queen
row = ... | --- +++ @@ -1,3 +1,80 @@+r"""
+Problem:
+
+The n queens problem is: placing N queens on a N * N chess board such that no queen
+can attack any other queens placed on that chess board. This means that one queen
+cannot have any other queen on its horizontal, vertical and diagonal lines.
+
+Solution:
+
+To solve this pr... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/n_queens_math.py |
Turn comments into proper docstrings | from __future__ import annotations
def solve_maze(
maze: list[list[int]],
source_row: int,
source_column: int,
destination_row: int,
destination_column: int,
) -> list[list[int]]:
size = len(maze)
# Check if source and destination coordinates are Invalid.
if not (0 <= source_row <= siz... | --- +++ @@ -8,6 +8,117 @@ destination_row: int,
destination_column: int,
) -> list[list[int]]:
+ """
+ This method solves the "rat in maze" problem.
+ Parameters :
+ - maze: A two dimensional matrix of zeros and ones.
+ - source_row: The row index of the starting point.
+ - sourc... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/rat_in_maze.py |
Please document this code using docstrings |
def get_point_key(len_board: int, len_board_column: int, row: int, column: int) -> int:
return len_board * len_board_column * row + column
def exits_word(
board: list[list[str]],
word: str,
row: int,
column: int,
word_index: int,
visited_points_set: set[int],
) -> bool:
if board[ro... | --- +++ @@ -1,6 +1,45 @@+"""
+Author : Alexander Pantyukhin
+Date : November 24, 2022
+
+Task:
+Given an m x n grid of characters board and a string word,
+return true if word exists in the grid.
+
+The word can be constructed from letters of sequentially adjacent cells,
+where adjacent cells are horizontally or ve... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/word_search.py |
Add docstrings to my Python code | # Knight Tour Intro: https://www.youtube.com/watch?v=ab_dY3dZFHM
from __future__ import annotations
def get_valid_pos(position: tuple[int, int], n: int) -> list[tuple[int, int]]:
y, x = position
positions = [
(y + 1, x + 2),
(y - 1, x + 2),
(y + 1, x - 2),
(y - 1, x - 2),
... | --- +++ @@ -4,6 +4,12 @@
def get_valid_pos(position: tuple[int, int], n: int) -> list[tuple[int, int]]:
+ """
+ Find all the valid positions a knight can move to from the current position.
+
+ >>> get_valid_pos((1, 3), 4)
+ [(2, 1), (0, 1), (3, 2)]
+ """
y, x = position
positions = [
@@ -... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/knight_tour.py |
Generate helpful docstrings for debugging |
def backtrack(input_string: str, word_dict: set[str], start: int) -> bool:
# Base case: if the starting index has reached the end of the string
if start == len(input_string):
return True
# Try every possible substring from 'start' to 'end'
for end in range(start + 1, len(input_string) + 1):
... | --- +++ @@ -1,6 +1,35 @@+"""
+Word Break Problem is a well-known problem in computer science.
+Given a string and a dictionary of words, the task is to determine if
+the string can be segmented into a sequence of one or more dictionary words.
+
+Wikipedia: https://en.wikipedia.org/wiki/Word_break_problem
+"""
def ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/word_break.py |
Write docstrings including parameters and return values |
from __future__ import annotations
Matrix = list[list[int]]
# assigning initial values to the grid
initial_grid: Matrix = [
[3, 0, 6, 5, 0, 8, 4, 0, 0],
[5, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0,... | --- +++ @@ -1,3 +1,14 @@+"""
+Given a partially filled 9x9 2D array, the objective is to fill a 9x9
+square grid with digits numbered 1 to 9, so that every row, column, and
+and each of the nine 3x3 sub-grids contains all of the digits.
+
+This can be solved using Backtracking and is similar to n-queens.
+We check to s... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/sudoku.py |
Add docstrings to make code maintainable |
def valid_coloring(
neighbours: list[int], colored_vertices: list[int], color: int
) -> bool:
# Does any neighbour not satisfy the constraints
return not any(
neighbour == 1 and colored_vertices[i] == color
for i, neighbour in enumerate(neighbours)
)
def util_color(
graph: list[l... | --- +++ @@ -1,8 +1,31 @@+"""
+Graph Coloring also called "m coloring problem"
+consists of coloring a given graph with at most m colors
+such that no adjacent vertices are assigned the same color
+
+Wikipedia: https://en.wikipedia.org/wiki/Graph_coloring
+"""
def valid_coloring(
neighbours: list[int], colored... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/coloring.py |
Generate documentation strings for clarity |
def backtrack(
candidates: list, path: list, answer: list, target: int, previous_index: int
) -> None:
if target == 0:
answer.append(path.copy())
else:
for index in range(previous_index, len(candidates)):
if target >= candidates[index]:
path.append(candidates[in... | --- +++ @@ -1,8 +1,33 @@+"""
+In the Combination Sum problem, we are given a list consisting of distinct integers.
+We need to find all the combinations whose sum equals to target given.
+We can use an element more than one.
+
+Time complexity(Average Case): O(n!)
+
+Constraints:
+1 <= candidates.length <= 30
+2 <= can... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/combination_sum.py |
Add return value explanations in docstrings | # https://www.geeksforgeeks.org/solve-crossword-puzzle/
def is_valid(
puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool
) -> bool:
for i in range(len(word)):
if vertical:
if row + i >= len(puzzle) or puzzle[row + i][col] != "":
return False
elif... | --- +++ @@ -4,6 +4,26 @@ def is_valid(
puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool
) -> bool:
+ """
+ Check if a word can be placed at the given position.
+
+ >>> puzzle = [
+ ... ['', '', '', ''],
+ ... ['', '', '', ''],
+ ... ['', '', '', ''],
+ ... ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/crossword_puzzle_solver.py |
Generate descriptive docstrings automatically | from __future__ import annotations
from abc import abstractmethod
from math import pi
from typing import Protocol
import matplotlib.pyplot as plt
import numpy as np
class FilterType(Protocol):
@abstractmethod
def process(self, sample: float) -> float:
def get_bounds(
fft_results: np.ndarray, samplerat... | --- +++ @@ -11,17 +11,38 @@ class FilterType(Protocol):
@abstractmethod
def process(self, sample: float) -> float:
+ """
+ Calculate y[n]
+
+ >>> issubclass(FilterType, Protocol)
+ True
+ """
def get_bounds(
fft_results: np.ndarray, samplerate: int
) -> tuple[int ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/audio_filters/show_response.py |
Add docstrings to incomplete code |
def generate_sum_of_subsets_solutions(nums: list[int], max_sum: int) -> list[list[int]]:
result: list[list[int]] = []
path: list[int] = []
num_index = 0
remaining_nums_sum = sum(nums)
create_state_space_tree(nums, max_sum, num_index, path, result, remaining_nums_sum)
return result
def creat... | --- +++ @@ -1,6 +1,25 @@+"""
+The sum-of-subsets problem states that a set of non-negative integers, and a
+value M, determine all possible subsets of the given set whose summation sum
+equal to given M.
+
+Summation of the chosen numbers must be equal to given number M and one number
+can be used only once.
+"""
... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/sum_of_subsets.py |
Generate docstrings for script automation | def gray_code(bit_count: int) -> list:
# bit count represents no. of bits in the gray code
if bit_count < 0:
raise ValueError("The given input must be positive")
# get the generated string sequence
sequence = gray_code_sequence_string(bit_count)
#
# convert them to integers
for i i... | --- +++ @@ -1,4 +1,37 @@ def gray_code(bit_count: int) -> list:
+ """
+ Takes in an integer n and returns a n-bit
+ gray code sequence
+ An n-bit gray code sequence is a sequence of 2^n
+ integers where:
+
+ a) Every integer is between [0,2^n -1] inclusive
+ b) The sequence begins with 0
+ c) An... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/bit_manipulation/gray_code_sequence.py |
Provide clean and structured docstrings | def match_word_pattern(pattern: str, input_string: str) -> bool:
def backtrack(pattern_index: int, str_index: int) -> bool:
if pattern_index == len(pattern) and str_index == len(input_string):
return True
if pattern_index == len(pattern) or str_index == len(input_string):
re... | --- +++ @@ -1,6 +1,32 @@ def match_word_pattern(pattern: str, input_string: str) -> bool:
+ """
+ Determine if a given pattern matches a string using backtracking.
+
+ pattern: The pattern to match.
+ input_string: The string to match against the pattern.
+ return: True if the pattern matches the string,... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/backtracking/match_word_pattern.py |
Help me comply with documentation standards |
def xor_gate(input_1: int, input_2: int) -> int:
return (input_1, input_2).count(0) % 2
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,10 +1,37 @@+"""
+A XOR Gate is a logic gate in boolean algebra which results to 1 (True) if only one of
+the two inputs is 1, and 0 (False) if an even number of inputs are 1.
+Following is the truth table of a XOR Gate:
+ ------------------------------
+ | Input 1 | Input 2 | Output |
+ ---------... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/boolean_algebra/xor_gate.py |
Write docstrings for algorithm functions |
def and_gate(input_1: int, input_2: int) -> int:
return int(input_1 and input_2)
def n_input_and_gate(inputs: list[int]) -> int:
return int(all(inputs))
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,14 +1,50 @@+"""
+An AND Gate is a logic gate in boolean algebra which results to 1 (True) if all the
+inputs are 1 (True), and 0 (False) otherwise.
+
+Following is the truth table of a Two Input AND Gate:
+ ------------------------------
+ | Input 1 | Input 2 | Output |
+ ------------------------... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/boolean_algebra/and_gate.py |
Insert docstrings into my code |
B32_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
def base32_encode(data: bytes) -> bytes:
binary_data = "".join(bin(ord(d))[2:].zfill(8) for d in data.decode("utf-8"))
binary_data = binary_data.ljust(5 * ((len(binary_data) // 5) + 1), "0")
b32_chunks = map("".join, zip(*[iter(binary_data)] * 5))
b32_... | --- +++ @@ -1,8 +1,21 @@+"""
+Base32 encoding and decoding
+
+https://en.wikipedia.org/wiki/Base32
+"""
B32_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
def base32_encode(data: bytes) -> bytes:
+ """
+ >>> base32_encode(b"Hello World!")
+ b'JBSWY3DPEBLW64TMMQQQ===='
+ >>> base32_encode(b"123456")
+ ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/base32.py |
Generate NumPy-style docstrings |
def imply_gate(input_1: int, input_2: int) -> int:
return int(input_1 == 0 or input_2 == 1)
def recursive_imply_list(input_list: list[int]) -> int:
if len(input_list) < 2:
raise ValueError("Input list must contain at least two elements")
first_implication = imply_gate(input_list[0], input_list[1... | --- +++ @@ -1,10 +1,81 @@+"""
+An IMPLY Gate is a logic gate in boolean algebra which results to 1 if
+either input 1 is 0, or if input 1 is 1, then the output is 1 only if input 2 is 1.
+It is true if input 1 implies input 2.
+
+Following is the truth table of an IMPLY Gate:
+ ------------------------------
+ | ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/boolean_algebra/imply_gate.py |
Generate docstrings for this script | from __future__ import annotations
from collections.abc import Sequence
from typing import Literal
def compare_string(string1: str, string2: str) -> str | Literal[False]:
list1 = list(string1)
list2 = list(string2)
count = 0
for i in range(len(list1)):
if list1[i] != list2[i]:
cou... | --- +++ @@ -5,6 +5,13 @@
def compare_string(string1: str, string2: str) -> str | Literal[False]:
+ """
+ >>> compare_string('0010','0110')
+ '0_10'
+
+ >>> compare_string('0110','1101')
+ False
+ """
list1 = list(string1)
list2 = list(string2)
count = 0
@@ -19,6 +26,10 @@
def ch... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/boolean_algebra/quine_mc_cluskey.py |
Add docstrings for better understanding |
from random import randint, random
def construct_highway(
number_of_cells: int,
frequency: int,
initial_speed: int,
random_frequency: bool = False,
random_speed: bool = False,
max_speed: int = 5,
) -> list:
highway = [[-1] * number_of_cells] # Create a highway without any car
i = 0
... | --- +++ @@ -1,3 +1,29 @@+"""
+Simulate the evolution of a highway with only one road that is a loop.
+The highway is divided in cells, each cell can have at most one car in it.
+The highway is a loop so when a car comes to one end, it will come out on the other.
+Each car is represented by its speed (from 0 to 5).
+
+S... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/cellular_automata/nagel_schrekenberg.py |
Write documentation strings for class attributes |
def bitwise_addition_recursive(number: int, other_number: int) -> int:
if not isinstance(number, int) or not isinstance(other_number, int):
raise TypeError("Both arguments MUST be integers!")
if number < 0 or other_number < 0:
raise ValueError("Both arguments MUST be non-negative!")
bit... | --- +++ @@ -1,6 +1,38 @@+"""
+Calculates the sum of two non-negative integers using bitwise operators
+Wikipedia explanation: https://en.wikipedia.org/wiki/Binary_number
+"""
def bitwise_addition_recursive(number: int, other_number: int) -> int:
+ """
+ >>> bitwise_addition_recursive(4, 5)
+ 9
+ >>> bi... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/bit_manipulation/bitwise_addition_recursive.py |
Add verbose docstrings with examples |
def largest_pow_of_two_le_num(number: int) -> int:
if isinstance(number, float):
raise TypeError("Input value must be a 'int' type")
if number <= 0:
return 0
res = 1
while (res << 1) <= number:
res <<= 1
return res
if __name__ == "__main__":
import doctest
doctes... | --- +++ @@ -1,6 +1,49 @@+"""
+Author : Naman Sharma
+Date : October 2, 2023
+
+Task:
+To Find the largest power of 2 less than or equal to a given number.
+
+Implementation notes: Use bit manipulation.
+We start from 1 & left shift the set bit to check if (res<<1)<=number.
+Each left bit shift represents a pow of 2... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/bit_manipulation/largest_pow_of_two_le_num.py |
Generate docstrings with examples |
def simplify_kmap(kmap: list[list[int]]) -> str:
simplified_f = []
for a, row in enumerate(kmap):
for b, item in enumerate(row):
if item:
term = ("A" if a else "A'") + ("B" if b else "B'")
simplified_f.append(term)
return " + ".join(simplified_f)
def m... | --- +++ @@ -1,6 +1,25 @@+"""
+https://en.wikipedia.org/wiki/Karnaugh_map
+https://www.allaboutcircuits.com/technical-articles/karnaugh-map-boolean-algebraic-simplification-technique
+"""
def simplify_kmap(kmap: list[list[int]]) -> str:
+ """
+ Simplify the Karnaugh map.
+ >>> simplify_kmap(kmap=[[0, 1], [... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/boolean_algebra/karnaugh_map_simplification.py |
Generate docstrings for this script |
def power_of_4(number: int) -> bool:
if not isinstance(number, int):
raise TypeError("number must be an integer")
if number <= 0:
raise ValueError("number must be positive")
if number & (number - 1) == 0:
c = 0
while number:
c += 1
number >>= 1
... | --- +++ @@ -1,6 +1,52 @@+"""
+
+Task:
+Given a positive int number. Return True if this number is power of 4
+or False otherwise.
+
+Implementation notes: Use bit manipulation.
+For example if the number is the power of 2 it's bits representation:
+n = 0..100..00
+n - 1 = 0..011..11
+
+n & (n - 1) - no intersection... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/bit_manipulation/power_of_4.py |
Generate descriptive docstrings automatically | #!/usr/bin/env python3
def set_bit(number: int, position: int) -> int:
return number | (1 << position)
def clear_bit(number: int, position: int) -> int:
return number & ~(1 << position)
def flip_bit(number: int, position: int) -> int:
return number ^ (1 << position)
def is_bit_set(number: int, posi... | --- +++ @@ -1,28 +1,100 @@ #!/usr/bin/env python3
+"""Provide the functionality to manipulate a single bit."""
def set_bit(number: int, position: int) -> int:
+ """
+ Set the bit at position to 1.
+
+ Details: perform bitwise or for given number and X.
+ Where X is a number with all the bits - zeroes... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/bit_manipulation/single_bit_manipulation_operations.py |
Generate consistent docstrings | def get_reverse_bit_string(number: int) -> str:
if not isinstance(number, int):
msg = (
"operation can not be conducted on an object of type "
f"{type(number).__name__}"
)
raise TypeError(msg)
bit_string = ""
for _ in range(32):
bit_string += str(numbe... | --- +++ @@ -1,4 +1,20 @@ def get_reverse_bit_string(number: int) -> str:
+ """
+ Return the reverse bit string of a 32 bit integer
+
+ >>> get_reverse_bit_string(9)
+ '10010000000000000000000000000000'
+ >>> get_reverse_bit_string(43)
+ '11010100000000000000000000000000'
+ >>> get_reverse_bit_strin... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/bit_manipulation/reverse_bits.py |
Create documentation strings for testing functions |
def nimply_gate(input_1: int, input_2: int) -> int:
return int(input_1 == 1 and input_2 == 0)
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,10 +1,39 @@+"""
+An NIMPLY Gate is a logic gate in boolean algebra which results to 0 if
+either input 1 is 0, or if input 1 is 1, then it is 0 only if input 2 is 1.
+It is false if input 1 implies input 2. It is the negated form of imply
+
+Following is the truth table of an NIMPLY Gate:
+ -----------... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/boolean_algebra/nimply_gate.py |
Include argument descriptions in docstrings |
def or_gate(input_1: int, input_2: int) -> int:
return int((input_1, input_2).count(1) != 0)
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,10 +1,35 @@-
-
-def or_gate(input_1: int, input_2: int) -> int:
- return int((input_1, input_2).count(1) != 0)
-
-
-if __name__ == "__main__":
- import doctest
-
- doctest.testmod()+"""
+An OR Gate is a logic gate in boolean algebra which results to 0 (False) if both the
+inputs are 0, and 1 (T... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/boolean_algebra/or_gate.py |
Insert docstrings into my code |
import string
MORSE_CODE_DICT = {
"A": ".-",
"B": "-...",
"C": "-.-.",
"D": "-..",
"E": ".",
"F": "..-.",
"G": "--.",
"H": "....",
"I": "..",
"J": ".---",
"K": "-.-",
"L": ".-..",
"M": "--",
"N": "-.",
"O": "---",
"P": ".--.",
"Q": "--.-",
"R": "... | --- +++ @@ -1,3 +1,13 @@+"""
+Python program for the Fractionated Morse Cipher.
+
+The Fractionated Morse cipher first converts the plaintext to Morse code,
+then enciphers fixed-size blocks of Morse code back to letters.
+This procedure means plaintext letters are mixed into the ciphertext letters,
+making it more sec... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/fractionated_morse_cipher.py |
Add docstrings to improve readability | B64_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def base64_encode(data: bytes) -> bytes:
# Make sure the supplied data is a bytes-like object
if not isinstance(data, bytes):
msg = f"a bytes-like object is required, not '{data.__class__.__name__}'"
raise TypeErr... | --- +++ @@ -2,6 +2,36 @@
def base64_encode(data: bytes) -> bytes:
+ """Encodes data according to RFC4648.
+
+ The data is first transformed to binary and appended with binary digits so that its
+ length becomes a multiple of 6, then each 6 binary digits will match a character in
+ the B64_CHARSET string... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/base64_cipher.py |
Add minimal docstrings for each function |
def miller_rabin(n: int, allow_probable: bool = False) -> bool:
if n == 2:
return True
if not n % 2 or n < 2:
return False
if n > 5 and n % 10 not in (1, 3, 7, 9): # can quickly check last digit
return False
if n > 3_317_044_064_679_887_385_961_981 and not allow_probable:
... | --- +++ @@ -1,6 +1,33 @@+"""Created by Nathan Damon, @bizzfitch on github
+>>> test_miller_rabin()
+"""
def miller_rabin(n: int, allow_probable: bool = False) -> bool:
+ """Deterministic Miller-Rabin algorithm for primes ~< 3.32e24.
+
+ Uses numerical analysis results to return whether or not the passed numb... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/deterministic_miller_rabin.py |
Write beginner-friendly docstrings | # Information on binary shifts:
# https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types
# https://www.interviewcake.com/concept/java/bit-shift
def logical_left_shift(number: int, shift_amount: int) -> str:
if number < 0 or shift_amount < 0:
raise ValueError("both inputs must ... | --- +++ @@ -4,6 +4,27 @@
def logical_left_shift(number: int, shift_amount: int) -> str:
+ """
+ Take in 2 positive integers.
+ 'number' is the integer to be logically left shifted 'shift_amount' times.
+ i.e. (number << shift_amount)
+ Return the shifted binary representation.
+
+ >>> logical_left... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/bit_manipulation/binary_shifts.py |
Improve documentation using docstrings |
def nand_gate(input_1: int, input_2: int) -> int:
return int(not (input_1 and input_2))
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,10 +1,36 @@-
-
-def nand_gate(input_1: int, input_2: int) -> int:
- return int(not (input_1 and input_2))
-
-
-if __name__ == "__main__":
- import doctest
-
- doctest.testmod()+"""
+A NAND Gate is a logic gate in boolean algebra which results to 0 (False) if both
+the inputs are 1, and 1 (True)... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/boolean_algebra/nand_gate.py |
Replace inline comments with docstrings | from __future__ import annotations
from maths.greatest_common_divisor import greatest_common_divisor
def diophantine(a: int, b: int, c: int) -> tuple[float, float]:
assert (
c % greatest_common_divisor(a, b) == 0
) # greatest_common_divisor(a,b) is in maths directory
(d, x, y) = extended_gcd(a,... | --- +++ @@ -4,6 +4,23 @@
def diophantine(a: int, b: int, c: int) -> tuple[float, float]:
+ """
+ Diophantine Equation : Given integers a,b,c ( at least one of a and b != 0), the
+ diophantine equation a*x + b*y = c has a solution (where x and y are integers)
+ iff greatest_common_divisor(a,b) divides c.... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/blockchain/diophantine_equation.py |
Write docstrings for data processing functions |
from collections.abc import Callable
def nor_gate(input_1: int, input_2: int) -> int:
return int(input_1 == input_2 == 0)
def truth_table(func: Callable) -> str:
def make_table_row(items: list | tuple) -> str:
return f"| {' | '.join(f'{item:^8}' for item in items)} |"
return "\n".join(
... | --- +++ @@ -1,14 +1,55 @@+"""
+A NOR Gate is a logic gate in boolean algebra which results in false(0) if any of the
+inputs is 1, and True(1) if all inputs are 0.
+Following is the truth table of a NOR Gate:
+ Truth Table of NOR Gate:
+ | Input 1 | Input 2 | Output |
+ | 0 | 0 | 1 |
+... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/boolean_algebra/nor_gate.py |
Write docstrings for algorithm functions |
def different_signs(num1: int, num2: int) -> bool:
return num1 ^ num2 < 0
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,10 +1,39 @@+"""
+Author : Alexander Pantyukhin
+Date : November 30, 2022
+
+Task:
+Given two int numbers. Return True these numbers have opposite signs
+or False otherwise.
+
+Implementation notes: Use bit manipulation.
+Use XOR for two numbers.
+"""
def different_signs(num1: int, num2: int) -> b... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/bit_manipulation/numbers_different_signs.py |
Generate docstrings for each module |
import random
import sys
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap
usage_doc = "Usage of script: script_name <size_of_canvas:int>"
choice = [0] * 100 + [1] * 10
random.shuffle(choice)
def create_canvas(size: int) -> list[list[bool]]:
canvas = [[False ... | --- +++ @@ -1,3 +1,32 @@+"""Conway's Game Of Life, Author Anurag Kumar(mailto:anuragkumarak95@gmail.com)
+
+Requirements:
+ - numpy
+ - random
+ - time
+ - matplotlib
+
+Python:
+ - 3.5
+
+Usage:
+ - $python3 game_of_life <canvas_size:int>
+
+Game-Of-Life Rules:
+
+ 1.
+ Any live cell with fewer than two live nei... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/cellular_automata/game_of_life.py |
Write docstrings including parameters and return values |
from collections.abc import Callable
from random import randint, shuffle
from time import sleep
from typing import Literal
WIDTH = 50 # Width of the Wa-Tor planet
HEIGHT = 50 # Height of the Wa-Tor planet
PREY_INITIAL_COUNT = 30 # The initial number of prey entities
PREY_REPRODUCTION_TIME = 5 # The chronons befo... | --- +++ @@ -1,3 +1,16 @@+"""
+Wa-Tor algorithm (1984)
+
+| @ https://en.wikipedia.org/wiki/Wa-Tor
+| @ https://beltoforion.de/en/wator/
+| @ https://beltoforion.de/en/wator/images/wator_medium.webm
+
+This solution aims to completely remove any systematic approach
+to the Wa-Tor planet, and utilise fully random methods... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/cellular_automata/wa_tor.py |
Add docstrings to meet PEP guidelines |
from __future__ import annotations
from PIL import Image
# Define the first generation of cells
# fmt: off
CELLS = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
# fmt: on
def format_ruleset(ruleset: int) -> list[int]:
return [int(c) for c in f"{rulese... | --- +++ @@ -1,3 +1,8 @@+"""
+Return an image of 16 generations of one-dimensional cellular automata based on a given
+ruleset number
+https://mathworld.wolfram.com/ElementaryCellularAutomaton.html
+"""
from __future__ import annotations
@@ -11,6 +16,14 @@
def format_ruleset(ruleset: int) -> list[int]:
+ """... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/cellular_automata/one_dimensional.py |
Write docstrings for backend logic |
import string
import numpy as np
from maths.greatest_common_divisor import greatest_common_divisor
class HillCipher:
key_string = string.ascii_uppercase + string.digits
# This cipher takes alphanumerics into account
# i.e. a total of 36 characters
# take x and return x % len(key_string)
modulu... | --- +++ @@ -1,3 +1,40 @@+"""
+
+Hill Cipher:
+The 'HillCipher' class below implements the Hill Cipher algorithm which uses
+modern linear algebra techniques to encode and decode text using an encryption
+key matrix.
+
+Algorithm:
+Let the order of the encryption key be N (as it is a square matrix).
+Your text is divide... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/hill_cipher.py |
Create docstrings for all classes and functions |
def _base10_to_85(d: int) -> str:
return "".join(chr(d % 85 + 33)) + _base10_to_85(d // 85) if d > 0 else ""
def _base85_to_10(digits: list) -> int:
return sum(char * 85**i for i, char in enumerate(reversed(digits)))
def ascii85_encode(data: bytes) -> bytes:
binary_data = "".join(bin(ord(d))[2:].zfill... | --- +++ @@ -1,3 +1,8 @@+"""
+Base85 (Ascii85) encoding and decoding
+
+https://en.wikipedia.org/wiki/Ascii85
+"""
def _base10_to_85(d: int) -> str:
@@ -9,6 +14,14 @@
def ascii85_encode(data: bytes) -> bytes:
+ """
+ >>> ascii85_encode(b"")
+ b''
+ >>> ascii85_encode(b"12345")
+ b'0etOA2#'
+ >... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/base85.py |
Write docstrings including parameters and return values |
def not_gate(input_1: int) -> int:
return 1 if input_1 == 0 else 0
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,11 +1,30 @@-
-
-def not_gate(input_1: int) -> int:
-
- return 1 if input_1 == 0 else 0
-
-
-if __name__ == "__main__":
- import doctest
-
- doctest.testmod()+"""
+A NOT Gate is a logic gate in boolean algebra which results to 0 (False) if the
+input is high, and 1 (True) if the input is low.
+... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/boolean_algebra/not_gate.py |
Add professional docstrings to my codebase |
import string
def atbash_slow(sequence: str) -> str:
output = ""
for i in sequence:
extract = ord(i)
if 65 <= extract <= 90:
output += chr(155 - extract)
elif 97 <= extract <= 122:
output += chr(219 - extract)
else:
output += i
return ou... | --- +++ @@ -1,8 +1,16 @@+"""https://en.wikipedia.org/wiki/Atbash"""
import string
def atbash_slow(sequence: str) -> str:
+ """
+ >>> atbash_slow("ABCDEFG")
+ 'ZYXWVUT'
+
+ >>> atbash_slow("aW;;123BX")
+ 'zD;;123YC'
+ """
output = ""
for i in sequence:
extract = ord(i)
@@ -16... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/atbash.py |
Add missing documentation to my Python functions |
def is_power_of_two(number: int) -> bool:
if number < 0:
raise ValueError("number must not be negative")
return number & (number - 1) == 0
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,6 +1,51 @@+"""
+Author : Alexander Pantyukhin
+Date : November 1, 2022
+
+Task:
+Given a positive int number. Return True if this number is power of 2
+or False otherwise.
+
+Implementation notes: Use bit manipulation.
+For example if the number is the power of two it's bits representation:
+n = 0... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/bit_manipulation/is_power_of_two.py |
Add docstrings explaining edge cases |
encode_dict = {
"a": "AAAAA",
"b": "AAAAB",
"c": "AAABA",
"d": "AAABB",
"e": "AABAA",
"f": "AABAB",
"g": "AABBA",
"h": "AABBB",
"i": "ABAAA",
"j": "BBBAA",
"k": "ABAAB",
"l": "ABABA",
"m": "ABABB",
"n": "ABBAA",
"o": "ABBAB",
"p": "ABBBA",
"q": "ABBBB... | --- +++ @@ -1,3 +1,7 @@+"""
+Program to encode and decode Baconian or Bacon's Cipher
+Wikipedia reference : https://en.wikipedia.org/wiki/Bacon%27s_cipher
+"""
encode_dict = {
"a": "AAAAA",
@@ -34,6 +38,18 @@
def encode(word: str) -> str:
+ """
+ Encodes to Baconian cipher
+
+ >>> encode("hello")
+... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/baconian_cipher.py |
Write docstrings for algorithm functions | def base16_encode(data: bytes) -> str:
# Turn the data into a list of integers (where each integer is a byte),
# Then turn each byte into its hexadecimal representation, make sure
# it is uppercase, and then join everything together and return it.
return "".join([hex(byte)[2:].zfill(2).upper() for byte ... | --- +++ @@ -1,4 +1,14 @@ def base16_encode(data: bytes) -> str:
+ """
+ Encodes the given bytes into base16.
+
+ >>> base16_encode(b'Hello World!')
+ '48656C6C6F20576F726C6421'
+ >>> base16_encode(b'HELLO WORLD!')
+ '48454C4C4F20574F524C4421'
+ >>> base16_encode(b'')
+ ''
+ """
# Turn th... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/base16.py |
Improve my code by adding docstrings |
from __future__ import annotations
RotorPositionT = tuple[int, int, int]
RotorSelectionT = tuple[str, str, str]
# used alphabet --------------------------
# from string.ascii_uppercase
abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# -------------------------- default selection --------------------------
# rotors ------------... | --- +++ @@ -1,3 +1,21 @@+"""
+| Wikipedia: https://en.wikipedia.org/wiki/Enigma_machine
+| Video explanation: https://youtu.be/QwQVMqfoB2E
+| Also check out Numberphile's and Computerphile's videos on this topic
+
+This module contains function ``enigma`` which emulates
+the famous Enigma machine from WWII.
+
+Module i... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/enigma_machine2.py |
Write docstrings for algorithm functions | def show_bits(before: int, after: int) -> str:
return f"{before:>5}: {before:08b}\n{after:>5}: {after:08b}"
def swap_odd_even_bits(num: int) -> int:
# Get all even bits - 0xAAAAAAAA is a 32-bit number with all even bits set to 1
even_bits = num & 0xAAAAAAAA
# Get all odd bits - 0x55555555 is a 32-bit... | --- +++ @@ -1,8 +1,45 @@ def show_bits(before: int, after: int) -> str:
+ """
+ >>> print(show_bits(0, 0xFFFF))
+ 0: 00000000
+ 65535: 1111111111111111
+ """
return f"{before:>5}: {before:08b}\n{after:>5}: {after:08b}"
def swap_odd_even_bits(num: int) -> int:
+ """
+ 1. We use bitwise... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/bit_manipulation/swap_all_odd_and_even_bits.py |
Write proper docstrings for these functions |
from __future__ import annotations
def encode(plain: str) -> list[int]:
return [ord(elem) - 96 for elem in plain]
def decode(encoded: list[int]) -> str:
return "".join(chr(elem + 96) for elem in encoded)
def main() -> None:
encoded = encode(input("-> ").strip().lower())
print("Encoded: ", encoded... | --- +++ @@ -1,12 +1,27 @@+"""
+Convert a string of characters to a sequence of numbers
+corresponding to the character's position in the alphabet.
+
+https://www.dcode.fr/letter-number-cipher
+http://bestcodes.weebly.com/a1z26.html
+"""
from __future__ import annotations
def encode(plain: str) -> list[int]:
+ ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/a1z26.py |
Annotate my code with docstrings |
from string import ascii_uppercase
dict1 = {char: i for i, char in enumerate(ascii_uppercase)}
dict2 = dict(enumerate(ascii_uppercase))
# This function generates the key in
# a cyclic manner until it's length isn't
# equal to the length of original text
def generate_key(message: str, key: str) -> str:
x = len(m... | --- +++ @@ -1,3 +1,6 @@+"""
+Author: Mohit Radadiya
+"""
from string import ascii_uppercase
@@ -9,6 +12,10 @@ # a cyclic manner until it's length isn't
# equal to the length of original text
def generate_key(message: str, key: str) -> str:
+ """
+ >>> generate_key("THE GERMAN ATTACK","SECRET")
+ 'SECRET... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/beaufort_cipher.py |
Add detailed docstrings explaining each function |
from functools import partial
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
WIDTH = 80
HEIGHT = 80
class LangtonsAnt:
def __init__(self, width: int, height: int) -> None:
# Each square is either True or False where True is white and False is black
self.boa... | --- +++ @@ -1,3 +1,9 @@+"""
+Langton's ant
+
+@ https://en.wikipedia.org/wiki/Langton%27s_ant
+@ https://upload.wikimedia.org/wikipedia/commons/0/09/LangtonsAntAnimated.gif
+"""
from functools import partial
@@ -9,6 +15,15 @@
class LangtonsAnt:
+ """
+ Represents the main LangonsAnt algorithm.
+
+ >>>... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/cellular_automata/langtons_ant.py |
Write proper docstrings for these functions |
def encrypt(plaintext: str, key: str) -> str:
if not isinstance(plaintext, str):
raise TypeError("plaintext must be a string")
if not isinstance(key, str):
raise TypeError("key must be a string")
if not plaintext:
raise ValueError("plaintext is empty")
if not key:
rais... | --- +++ @@ -1,6 +1,40 @@+"""
+https://en.wikipedia.org/wiki/Autokey_cipher
+
+An autokey cipher (also known as the autoclave cipher) is a cipher that
+incorporates the message (the plaintext) into the key.
+The key is generated from the message in some automated fashion,
+sometimes by selecting certain letters from the... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/autokey.py |
Add docstrings that explain inputs and outputs | #!/usr/bin/env python3
import numpy as np
SQUARE = [
["a", "b", "c", "d", "e"],
["f", "g", "h", "i", "k"],
["l", "m", "n", "o", "p"],
["q", "r", "s", "t", "u"],
["v", "w", "x", "y", "z"],
]
class BifidCipher:
def __init__(self) -> None:
self.SQUARE = np.array(SQUARE)
def letter... | --- +++ @@ -1,5 +1,11 @@ #!/usr/bin/env python3
+"""
+The Bifid Cipher uses a Polybius Square to encipher a message in a way that
+makes it fairly difficult to decipher without knowing the secret.
+
+https://www.braingle.com/brainteasers/codes/bifid.php
+"""
import numpy as np
@@ -17,15 +23,47 @@ self.SQ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/bifid.py |
Document classes and their methods | from __future__ import annotations
from string import ascii_letters
def encrypt(input_string: str, key: int, alphabet: str | None = None) -> str:
# Set default alphabet to lower and upper case english chars
alpha = alphabet or ascii_letters
# The final result string
result = ""
for character in... | --- +++ @@ -4,6 +4,70 @@
def encrypt(input_string: str, key: int, alphabet: str | None = None) -> str:
+ """
+ encrypt
+ =======
+
+ Encodes a given string with the caesar cipher and returns the encoded
+ message
+
+ Parameters:
+ -----------
+
+ * `input_string`: the plain-text that needs... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/caesar_cipher.py |
Create docstrings for all classes and functions |
def xnor_gate(input_1: int, input_2: int) -> int:
return 1 if input_1 == input_2 else 0
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,10 +1,37 @@-
-
-def xnor_gate(input_1: int, input_2: int) -> int:
- return 1 if input_1 == input_2 else 0
-
-
-if __name__ == "__main__":
- import doctest
-
- doctest.testmod()+"""
+A XNOR Gate is a logic gate in boolean algebra which results to 0 (False) if both the
+inputs are different, and ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/boolean_algebra/xnor_gate.py |
Generate docstrings for each module |
from __future__ import annotations
from PIL import Image
# Define glider example
GLIDER = [
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0... | --- +++ @@ -1,3 +1,7 @@+"""
+Conway's Game of Life implemented in Python.
+https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
+"""
from __future__ import annotations
@@ -20,6 +24,11 @@
def new_generation(cells: list[list[int]]) -> list[list[int]]:
+ """
+ Generates the next generation for a given stat... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/cellular_automata/conways_game_of_life.py |
Create docstrings for each class method | from timeit import timeit
def get_set_bits_count_using_brian_kernighans_algorithm(number: int) -> int:
if number < 0:
raise ValueError("the value of input must not be negative")
result = 0
while number:
number &= number - 1
result += 1
return result
def get_set_bits_count_usi... | --- +++ @@ -2,6 +2,25 @@
def get_set_bits_count_using_brian_kernighans_algorithm(number: int) -> int:
+ """
+ Count the number of set bits in a 32 bit integer
+ >>> get_set_bits_count_using_brian_kernighans_algorithm(25)
+ 3
+ >>> get_set_bits_count_using_brian_kernighans_algorithm(37)
+ 3
+ >>... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/bit_manipulation/count_number_of_one_bits.py |
Add docstrings with type hints explained | import random
import sys
from maths.greatest_common_divisor import gcd_by_iterative
from . import cryptomath_module as cryptomath
SYMBOLS = (
r""" !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`"""
r"""abcdefghijklmnopqrstuvwxyz{|}~"""
)
def check_keys(key_a: int, key_b: int, mode: str) ->... | --- +++ @@ -36,6 +36,11 @@
def encrypt_message(key: int, message: str) -> str:
+ """
+ >>> encrypt_message(4545, 'The affine cipher is a type of monoalphabetic '
+ ... 'substitution cipher.')
+ 'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF{xIp~{HL}Gi'
+ """
key_a... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/affine_cipher.py |
Generate consistent documentation across files | from typing import Literal
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def translate_message(
key: str, message: str, mode: Literal["encrypt", "decrypt"]
) -> str:
chars_a = LETTERS if mode == "decrypt" else key
chars_b = key if mode == "decrypt" else LETTERS
translated = ""
# loop through each symbol... | --- +++ @@ -6,6 +6,10 @@ def translate_message(
key: str, message: str, mode: Literal["encrypt", "decrypt"]
) -> str:
+ """
+ >>> translate_message("QWERTYUIOPASDFGHJKLZXCVBNM","Hello World","encrypt")
+ 'Pcssi Bidsm'
+ """
chars_a = LETTERS if mode == "decrypt" else key
chars_b = key if mod... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/mono_alphabetic_ciphers.py |
Annotate my code with docstrings | #!/usr/bin/env python3
import numpy as np
SQUARE = [
["a", "b", "c", "d", "e"],
["f", "g", "h", "i", "k"],
["l", "m", "n", "o", "p"],
["q", "r", "s", "t", "u"],
["v", "w", "x", "y", "z"],
]
class PolybiusCipher:
def __init__(self) -> None:
self.SQUARE = np.array(SQUARE)
def let... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python3
+"""
+A Polybius Square is a table that allows someone to translate letters into numbers.
+
+https://www.braingle.com/brainteasers/codes/polybius.php
+"""
import numpy as np
@@ -17,14 +22,42 @@ self.SQUARE = np.array(SQUARE)
def letter_to_numbers(sel... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/polybius.py |
Add docstrings explaining edge cases |
import random
def generate_valid_block_size(message_length: int) -> int:
block_sizes = [
block_size
for block_size in range(2, message_length + 1)
if message_length % block_size == 0
]
return random.choice(block_sizes)
def generate_permutation_key(block_size: int) -> list[int]:
... | --- +++ @@ -1,8 +1,31 @@+"""
+The permutation cipher, also called the transposition cipher, is a simple encryption
+technique that rearranges the characters in a message based on a secret key. It
+divides the message into blocks and applies a permutation to the characters within
+each block according to the key. The ke... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/permutation_cipher.py |
Write docstrings describing each step | #!/usr/bin/env python3
# fmt: off
MORSE_CODE_DICT = {
"A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.",
"H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.",
"O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-",
... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python3
+"""
+Python program to translate to and from Morse code.
+
+https://en.wikipedia.org/wiki/Morse_code
+"""
# fmt: off
MORSE_CODE_DICT = {
@@ -18,14 +23,29 @@
def encrypt(message: str) -> str:
+ """
+ >>> encrypt("Sos!")
+ '... --- ... -.-.--'
+ >>> e... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/morse_code.py |
Add docstrings explaining edge cases |
from typing import SupportsIndex
import numpy as np
from scipy.ndimage import convolve
def warp(
image: np.ndarray, horizontal_flow: np.ndarray, vertical_flow: np.ndarray
) -> np.ndarray:
flow = np.stack((horizontal_flow, vertical_flow), 2)
# Create a grid of all pixel coordinates and subtract the flow... | --- +++ @@ -1,3 +1,13 @@+"""
+The Horn-Schunck method estimates the optical flow for every single pixel of
+a sequence of images.
+It works by assuming brightness constancy between two consecutive frames
+and smoothness in the optical flow.
+
+Useful resources:
+Wikipedia: https://en.wikipedia.org/wiki/Horn%E2%80%93Sch... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/computer_vision/horn_schunck.py |
Write docstrings that follow conventions | alphabet = {
"A": ("ABCDEFGHIJKLM", "NOPQRSTUVWXYZ"),
"B": ("ABCDEFGHIJKLM", "NOPQRSTUVWXYZ"),
"C": ("ABCDEFGHIJKLM", "ZNOPQRSTUVWXY"),
"D": ("ABCDEFGHIJKLM", "ZNOPQRSTUVWXY"),
"E": ("ABCDEFGHIJKLM", "YZNOPQRSTUVWX"),
"F": ("ABCDEFGHIJKLM", "YZNOPQRSTUVWX"),
"G": ("ABCDEFGHIJKLM", "XYZNOPQRS... | --- +++ @@ -29,10 +29,20 @@
def generate_table(key: str) -> list[tuple[str, str]]:
+ """
+ >>> generate_table('marvin') # doctest: +NORMALIZE_WHITESPACE
+ [('ABCDEFGHIJKLM', 'UVWXYZNOPQRST'), ('ABCDEFGHIJKLM', 'NOPQRSTUVWXYZ'),
+ ('ABCDEFGHIJKLM', 'STUVWXYZNOPQR'), ('ABCDEFGHIJKLM', 'QRSTUVWXYZNOP'),
... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/porta_cipher.py |
Add docstrings that explain purpose and usage |
import itertools
import string
from collections.abc import Generator, Iterable
def chunker(seq: Iterable[str], size: int) -> Generator[tuple[str, ...]]:
it = iter(seq)
while True:
chunk = tuple(itertools.islice(it, size))
if not chunk:
return
yield chunk
def prepare_inpu... | --- +++ @@ -1,3 +1,23 @@+"""
+https://en.wikipedia.org/wiki/Playfair_cipher#Description
+
+The Playfair cipher was developed by Charles Wheatstone in 1854
+It's use was heavily promotedby Lord Playfair, hence its name
+
+Some features of the Playfair cipher are:
+
+1) It was the first literal diagram substitution ciphe... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/playfair_cipher.py |
Write Python docstrings for this snippet | from __future__ import annotations
import random
import string
class ShuffledShiftCipher:
def __init__(self, passcode: str | None = None) -> None:
self.__passcode = passcode or self.__passcode_creator()
self.__key_list = self.__make_key_list()
self.__shift_key = self.__make_shift_key()
... | --- +++ @@ -5,26 +5,91 @@
class ShuffledShiftCipher:
+ """
+ This algorithm uses the Caesar Cipher algorithm but removes the option to
+ use brute force to decrypt the message.
+
+ The passcode is a random password from the selection buffer of
+ 1. uppercase letters of the English alphabet
+ 2. lo... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/shuffled_shift_cipher.py |
Create docstrings for API functions |
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,
"G... | --- +++ @@ -1,3 +1,22 @@+"""
+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.
+-> Paramet... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/astronomical_length_scale_conversion.py |
Add docstrings to make code maintainable |
from __future__ import annotations
import math
import random
def rsafactor(d: int, e: int, n: int) -> list[int]:
k = d * e - 1
p = 0
q = 0
while p == 0:
g = random.randint(2, n - 1)
t = k
while True:
if t % 2 == 0:
t = t // 2
x = (g... | --- +++ @@ -1,32 +1,61 @@-
-from __future__ import annotations
-
-import math
-import random
-
-
-def rsafactor(d: int, e: int, n: int) -> list[int]:
- k = d * e - 1
- p = 0
- q = 0
- while p == 0:
- g = random.randint(2, n - 1)
- t = k
- while True:
- if t % 2 == 0:
- ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/rsa_factorization.py |
Add docstrings for better understanding | def remove_duplicates(key: str) -> str:
key_no_dups = ""
for ch in key:
if ch == " " or (ch not in key_no_dups and ch.isalpha()):
key_no_dups += ch
return key_no_dups
def create_cipher_map(key: str) -> dict[str, str]:
# Create a list of the letters in the alphabet
alphabet = [... | --- +++ @@ -1,4 +1,14 @@ def remove_duplicates(key: str) -> str:
+ """
+ Removes duplicate alphabetic characters in a keyword (letter is ignored after its
+ first appearance).
+
+ :param key: Keyword to use
+ :return: String with duplicates removed
+
+ >>> remove_duplicates('Hello World!!')
+ 'Helo... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/simple_keyword_cypher.py |
Add docstrings to existing functions |
def decimal_to_binary_iterative(num: int) -> str:
if isinstance(num, float):
raise TypeError("'float' object cannot be interpreted as an integer")
if isinstance(num, str):
raise TypeError("'str' object cannot be interpreted as an integer")
if num == 0:
return "0b0"
negative ... | --- +++ @@ -1,6 +1,31 @@+"""Convert a Decimal Number to a Binary Number."""
def decimal_to_binary_iterative(num: int) -> str:
+ """
+ Convert an Integer Decimal Number to a Binary Number as str.
+ >>> decimal_to_binary_iterative(0)
+ '0b0'
+ >>> decimal_to_binary_iterative(2)
+ '0b10'
+ >>> de... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/conversions/decimal_to_binary.py |
Write proper docstrings for these functions |
def encrypt(input_string: str, key: int) -> str:
temp_grid: list[list[str]] = [[] for _ in range(key)]
lowest = key - 1
if key <= 0:
raise ValueError("Height of grid can't be 0 or negative")
if key == 1 or len(input_string) <= key:
return input_string
for position, character in e... | --- +++ @@ -1,62 +1,102 @@-
-
-def encrypt(input_string: str, key: int) -> str:
- temp_grid: list[list[str]] = [[] for _ in range(key)]
- lowest = key - 1
-
- if key <= 0:
- raise ValueError("Height of grid can't be 0 or negative")
- if key == 1 or len(input_string) <= key:
- return input_stri... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/rail_fence_cipher.py |
Fully document this Python code with docstrings | import random
class Onepad:
@staticmethod
def encrypt(text: str) -> tuple[list[int], list[int]]:
plain = [ord(i) for i in text]
key = []
cipher = []
for i in plain:
k = random.randint(1, 300)
c = (i + k) * k
cipher.append(c)
key.a... | --- +++ @@ -4,6 +4,27 @@ class Onepad:
@staticmethod
def encrypt(text: str) -> tuple[list[int], list[int]]:
+ """
+ Function to encrypt text using pseudo-random numbers
+ >>> Onepad().encrypt("")
+ ([], [])
+ >>> Onepad().encrypt([])
+ ([], [])
+ >>> random.see... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/onepad_cipher.py |
Add standardized docstrings across the file |
def running_key_encrypt(key: str, plaintext: str) -> str:
plaintext = plaintext.replace(" ", "").upper()
key = key.replace(" ", "").upper()
key_length = len(key)
ciphertext = []
ord_a = ord("A")
for i, char in enumerate(plaintext):
p = ord(char) - ord_a
k = ord(key[i % key_len... | --- +++ @@ -1,6 +1,16 @@+"""
+https://en.wikipedia.org/wiki/Running_key_cipher
+"""
def running_key_encrypt(key: str, plaintext: str) -> str:
+ """
+ Encrypts the plaintext using the Running Key Cipher.
+
+ :param key: The running key (long piece of text).
+ :param plaintext: The plaintext to be encryp... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/running_key_cipher.py |
Add docstrings with type hints explained | import math
"""
In cryptography, the TRANSPOSITION cipher is a method of encryption where the
positions of plaintext are shifted a certain number(determined by the key) that
follows a regular system that results in the permuted text, known as the encrypted
text. The type of transposition cipher demonstrated under is t... | --- +++ @@ -23,6 +23,10 @@
def encrypt_message(key: int, message: str) -> str:
+ """
+ >>> encrypt_message(6, 'Harshil Darji')
+ 'Hlia rDsahrij'
+ """
cipher_text = [""] * key
for col in range(key):
pointer = col
@@ -33,6 +37,10 @@
def decrypt_message(key: int, message: str) -> st... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/transposition_cipher.py |
Write clean docstrings for readability | import random
import sys
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def main() -> None:
message = input("Enter message: ")
key = "LFWOAYUISVKMNXPBDCRJTQEGHZ"
resp = input("Encrypt/Decrypt [e/d]: ")
check_valid_key(key)
if resp.lower().startswith("e"):
mode = "encrypt"
translated = e... | --- +++ @@ -32,10 +32,18 @@
def encrypt_message(key: str, message: str) -> str:
+ """
+ >>> encrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji')
+ 'Ilcrism Olcvs'
+ """
return translate_message(key, message, "encrypt")
def decrypt_message(key: str, message: str) -> str:
+ """
+ ... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/simple_substitution_cipher.py |
Improve documentation using docstrings |
import glob
import os
import random
from string import ascii_lowercase, digits
import cv2
import numpy as np
# Parameters
OUTPUT_SIZE = (720, 1280) # Height, Width
SCALE_RANGE = (0.4, 0.6) # if height or width lower than this scale, drop it.
FILTER_TINY_SCALE = 1 / 100
LABEL_DIR = ""
IMG_DIR = ""
OUTPUT_DIR = ""
N... | --- +++ @@ -1,3 +1,4 @@+"""Source: https://github.com/jason9075/opencv-mosaic-data-aug"""
import glob
import os
@@ -18,6 +19,11 @@
def main() -> None:
+ """
+ Get images list and annotations list from input dir.
+ Update new images and annotations.
+ Save images and annotations in output dir.
+ "... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/computer_vision/mosaic_augmentation.py |
Create simple docstrings for beginners | def vernam_encrypt(plaintext: str, key: str) -> str:
ciphertext = ""
for i in range(len(plaintext)):
ct = ord(key[i % len(key)]) - 65 + ord(plaintext[i]) - 65
while ct > 25:
ct = ct - 26
ciphertext += chr(65 + ct)
return ciphertext
def vernam_decrypt(ciphertext: str, ke... | --- +++ @@ -1,4 +1,8 @@ def vernam_encrypt(plaintext: str, key: str) -> str:
+ """
+ >>> vernam_encrypt("HELLO","KEY")
+ 'RIJVS'
+ """
ciphertext = ""
for i in range(len(plaintext)):
ct = ord(key[i % len(key)]) - 65 + ord(plaintext[i]) - 65
@@ -9,6 +13,10 @@
def vernam_decrypt(ciphert... | https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/vernam_cipher.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.