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()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'\".,<>?«»“”‘’]))') raw_links = re.findall(link_pattern, text) links = [ str(raw_link[0]) for raw_link in raw_links ] return links def find_links_in_file(filename: str) -> List[str]: with open(filename, mode='r', encoding='utf-8') as file: readme = file.read() index_section = readme.find('## Index') if index_section == -1: index_section = 0 content = readme[index_section:] links = find_links_in_text(content) return links def check_duplicate_links(links: List[str]) -> Tuple[bool, List]: seen = {} duplicates = [] has_duplicate = False for link in links: link = link.rstrip('/') if link not in seen: seen[link] = 1 else: if seen[link] == 1: duplicates.append(link) if duplicates: has_duplicate = True return (has_duplicate, duplicates) def fake_user_agent() -> str: user_agents = [ 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1467.0 Safari/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko)', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36', ] return random.choice(user_agents) def get_host_from_link(link: str) -> str: host = link.split('://', 1)[1] if '://' in link else link # Remove routes, arguments and anchors if '/' in host: host = host.split('/', 1)[0] elif '?' in host: host = host.split('?', 1)[0] elif '#' in host: host = host.split('#', 1)[0] return host def has_cloudflare_protection(resp: Response) -> bool: code = resp.status_code server = resp.headers.get('Server') or resp.headers.get('server') cloudflare_flags = [ '403 Forbidden', 'cloudflare', 'Cloudflare', 'Security check', 'Please Wait... | Cloudflare', 'We are checking your browser...', 'Please stand by, while we are checking your browser...', 'Checking your browser before accessing', 'This process is automatic.', 'Your browser will redirect to your requested content shortly.', 'Please allow up to 5 seconds', 'DDoS protection by', 'Ray ID:', 'Cloudflare Ray ID:', '_cf_chl', '_cf_chl_opt', '__cf_chl_rt_tk', 'cf-spinner-please-wait', 'cf-spinner-redirecting' ] if code in [403, 503] and server == 'cloudflare': html = resp.text flags_found = [flag in html for flag in cloudflare_flags] any_flag_found = any(flags_found) if any_flag_found: return True return False def check_if_link_is_working(link: str) -> Tuple[bool, str]: has_error = False error_message = '' try: resp = requests.get(link, timeout=25, headers={ 'User-Agent': fake_user_agent(), 'host': get_host_from_link(link) }) code = resp.status_code if code >= 400 and not has_cloudflare_protection(resp): has_error = True error_message = f'ERR:CLT: {code} : {link}' except requests.exceptions.SSLError as error: has_error = True error_message = f'ERR:SSL: {error} : {link}' except requests.exceptions.ConnectionError as error: has_error = True error_message = f'ERR:CNT: {error} : {link}' except (TimeoutError, requests.exceptions.ConnectTimeout): has_error = True error_message = f'ERR:TMO: {link}' except requests.exceptions.TooManyRedirects as error: has_error = True error_message = f'ERR:TMR: {error} : {link}' except (Exception, requests.exceptions.RequestException) as error: has_error = True error_message = f'ERR:UKN: {error} : {link}' return (has_error, error_message) def check_if_list_of_links_are_working(list_of_links: List[str]) -> List[str]: error_messages = [] for link in list_of_links: has_error, error_message = check_if_link_is_working(link) if has_error: error_messages.append(error_message) return error_messages def start_duplicate_links_checker(links: List[str]) -> None: print('Checking for duplicate links...') has_duplicate_link, duplicates_links = check_duplicate_links(links) if has_duplicate_link: print(f'Found duplicate links:') for duplicate_link in duplicates_links: print(duplicate_link) sys.exit(1) else: print('No duplicate links.') def start_links_working_checker(links: List[str]) -> None: print(f'Checking if {len(links)} links are working...') errors = check_if_list_of_links_are_working(links) if errors: num_errors = len(errors) print(f'Apparently {num_errors} links are not working properly. See in:') for error_message in errors: print(error_message) sys.exit(1) def main(filename: str, only_duplicate_links_checker: bool) -> None: links = find_links_in_file(filename) start_duplicate_links_checker(links) if not only_duplicate_links_checker: start_links_working_checker(links) if __name__ == '__main__': num_args = len(sys.argv) only_duplicate_links_checker = False if num_args < 2: print('No .md file passed') sys.exit(1) elif num_args == 3: third_arg = sys.argv[2].lower() if third_arg == '-odlc' or third_arg == '--only_duplicate_links_checker': only_duplicate_links_checker = True else: print(f'Third invalid argument. Usage: python {__file__} [-odlc | --only_duplicate_links_checker]') sys.exit(1) filename = sys.argv[1] main(filename, only_duplicate_links_checker)
--- +++ @@ -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`!()\[\]{};:\'\".,<>?«»“”‘’]))') @@ -23,6 +24,7 @@ def find_links_in_file(filename: str) -> List[str]: + """Find links in a file and return a list of URLs from text file.""" with open(filename, mode='r', encoding='utf-8') as file: readme = file.read() @@ -37,6 +39,10 @@ def check_duplicate_links(links: List[str]) -> Tuple[bool, List]: + """Check for duplicated links. + + Returns a tuple with True or False and duplicate list. + """ seen = {} duplicates = [] @@ -57,6 +63,7 @@ def fake_user_agent() -> str: + """Faking user agent as some hosting services block not-whitelisted UA.""" user_agents = [ 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1467.0 Safari/537.36', @@ -86,6 +93,25 @@ def has_cloudflare_protection(resp: Response) -> bool: + """Checks if there is any cloudflare protection in the response. + + Cloudflare implements multiple network protections on a given link, + this script tries to detect if any of them exist in the response from request. + + Common protections have the following HTTP code as a response: + - 403: When host header is missing or incorrect (and more) + - 503: When DDOS protection exists + + See more about it at: + - https://support.cloudflare.com/hc/en-us/articles/115003014512-4xx-Client-Error + - https://support.cloudflare.com/hc/en-us/articles/115003011431-Troubleshooting-Cloudflare-5XX-errors + - https://www.cloudflare.com/ddos/ + - https://superuser.com/a/888526 + + Discussions in issues and pull requests: + - https://github.com/public-apis/public-apis/pull/2409 + - https://github.com/public-apis/public-apis/issues/2960 + """ code = resp.status_code server = resp.headers.get('Server') or resp.headers.get('server') @@ -124,6 +150,15 @@ def check_if_link_is_working(link: str) -> Tuple[bool, str]: + """Checks if a link is working. + + If an error is identified when the request for the link occurs, + the return will be a tuple with the first value True and the second + value a string containing the error message. + + If no errors are identified, the return will be a tuple with the + first value False and the second an empty string. + """ has_error = False error_message = '' @@ -235,4 +270,4 @@ filename = sys.argv[1] - main(filename, only_duplicate_links_checker)+ main(filename, only_duplicate_links_checker)
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 characters (Basic Latin character) 'rtl_chars_pattern': r"[\u0590-\u08FF]", # Matches Right-to-Left (RTL) characters (Arabic, Hebrew, etc.) 'severity': { 'bidi_mismatch': 'error', # A difference between the displayed and logical order of text 'keyword': 'warning', # An LTR keyword (e.g., "HTML") in an RTL context might need an &rlm; 'symbol': 'warning', # An LTR symbol (e.g., "C#") in an RTL context might need an &lrm; 'pure_ltr': 'notice', # A purely LTR segment in an RTL context might need a trailing &lrm; 'author_meta': 'notice' # Specific rules for LTR authors/metadata in RTL contexts. }, 'ignore_meta': ['PDF', 'EPUB', 'HTML', 'podcast', 'videocast'], 'min_ltr_length': 3, 'rlm_entities': ['&rlm;', '&#x200F;', '&#8207;'], 'lrm_entities': ['&lrm;', '&#x200E;', '&#8206;'] } # If a path is specified and the file exists, attempt to load it if path and os.path.exists(path): try: with open(path, encoding='utf-8') as f: data = yaml.safe_load(f) or {} conf = data.get('rtl_config', {}) default.update(conf) except Exception as e: print(f"::warning file={path}::Could not load config: {e}. Using defaults.") # Output to stdout for GitHub Actions # Return the configuration (updated defaults or just defaults) return default def is_rtl_filename(path): name = os.path.basename(path).lower() return any(name.endswith(suf) for suf in ['-ar.md','_ar.md','-he.md','_he.md','-fa.md','_fa.md','-ur.md','_ur.md']) # Regex to identify a Markdown list item (e.g., "* text", "- text") LIST_ITEM_RE = re.compile(r'^\s*[\*\-\+]\s+(.*)') # Regex to extract title, URL, author, and metadata from a formatted book item # Example: Book Title - Author (Metadata) BOOK_ITEM_RE = re.compile( r"^\s*\[(?P<title>.+?)\]\((?P<url>.+?)\)" # Title and URL (required) r"(?:\s*[-–—]\s*(?P<author>[^\(\n\[]+?))?" # Author (optional), separated by -, –, — r"(?:\s*[\(\[](?P<meta>.*?)[\)\]])?\s*$" # Metadata (optional), enclosed in parentheses () or [] ) # Regex to find the dir="rtl" or dir="ltr" attribute in an HTML tag HTML_DIR_ATTR_RE = re.compile(r"dir\s*=\s*(['\"])(rtl|ltr)\1", re.IGNORECASE) # Regex to find <span> tags with a dir attribute SPAN_DIR_RE = re.compile(r'<span[^>]*dir=["\'](rtl|ltr)["\'][^>]*>', re.IGNORECASE) # Regex to identify inline code (text enclosed in single backticks) INLINE_CODE_RE = re.compile(r'^`.*`$') # Regex to identify the start of a code block (```) # Can be preceded by spaces or a '>' character (for blockquotes) CODE_FENCE_START = re.compile(r'^\s*>?\s*```') # Regex to identify text entirely enclosed in parentheses or square brackets. # Useful for skipping segments like "(PDF)" or "[Free]" during analysis. BRACKET_CONTENT_RE = re.compile(r''' (?:^|\W) # Start of line or non-word character (\[|\() # Open square or round bracket ([^\n\)\]]*?) # Content (\]|\)) # Close square or round bracket (?:\W|$) # End of line or non-word character ''', re.VERBOSE | re.UNICODE) # VERBOSE for comments, UNICODE for correct matching def split_by_span(text, base_ctx): # Split the text based on <span> tags tokens = re.split(r'(<span[^>]*dir=["\'](?:rtl|ltr)["\'][^>]*>|</span>)', text) # Initialize the stack with the base context stack = [base_ctx] # Initialize the segments segments = [] # for each token for tok in tokens: # Skip empty tokens if not tok: continue # Check if the token is an opening <span> tag with a dir attribute m = SPAN_DIR_RE.match(tok) # If so, push the new context onto the stack if m: stack.append(m.group(1).lower()); continue # If the token is a closing </span> tag if tok.lower() == '</span>': # Pop the last context from the stack if len(stack) > 1: stack.pop() continue # Otherwise, if the token is not a span tag, it's a text segment. # So, we need to append the tuple (segment, current context) to segments[] # Where the current context is the top element of the stack. segments.append((tok, stack[-1])) # return the list of tuples return segments def lint_file(path, cfg): # Initialize the list of issues issues = [] # Try to read the file content and handle potential errors try: lines = open(path, encoding='utf-8').read().splitlines() except Exception as e: return [f"::error file={path},line=1::Cannot read file: {e}"] # Return as a list of issues # Extract configuration parameters for easier access and readability keywords_orig = cfg['ltr_keywords'] symbols = cfg['ltr_symbols'] pure_ltr_re = re.compile(cfg['pure_ltr_pattern']) rtl_char_re = re.compile(cfg['rtl_chars_pattern']) sev = cfg['severity'] ignore_meta = set(cfg['ignore_meta']) min_len = cfg['min_ltr_length'] # chr(0x200F) = RLM Unicode character # chr(0x200E) = LRM Unicode character # These control character must be added here in the code and not in the YAML configuration file, # due to the fact that if we included them in the YAML file they would be invisible and, therefore, # the YAML file would be less readable RLM = [chr(0x200F)] + cfg['rlm_entities'] LRM = [chr(0x200E)] + cfg['lrm_entities'] # Determine the directionality context of the file (RTL or LTR) based on the filename file_direction_ctx = 'rtl' if is_rtl_filename(path) else 'ltr' # Stack to manage block-level direction contexts for nested divs. # Initialized with the file's base direction context. block_context_stack = [file_direction_ctx] # Iterate over each line of the file with its line number for idx, line in enumerate(lines, 1): # The active block direction context for the current line is the top of the stack. active_block_direction_ctx = block_context_stack[-1] # Skip lines that start a code block (```) if CODE_FENCE_START.match(line): continue # Find all opening and closing <div> tags on the line to handle cases # where there can be multiple <div> opening and closing on the same line div_tags = re.findall(r"(<div[^>]*dir=['\"](rtl|ltr)['\"][^>]*>|</div>)", line, re.IGNORECASE) # Process each found tag in order to correctly update the context stack for tag_tuple in div_tags: # re.findall with multiple capture groups returns a list of tuples: # tag: The full matched tag (e.g., '<div...>' or '</div>') # direction: The captured direction ('rtl' or 'ltr'), or empty for a closing tag tag, direction = tag_tuple # If it's an opening tag with 'markdown="1"', push the new context if tag.startswith('<div') and 'markdown="1"' in tag: block_context_stack.append(direction.lower()) # If it's a closing tag and we are inside a div, pop the context elif tag == '</div>' and len(block_context_stack) > 1: block_context_stack.pop() # Check if the line is a Markdown list item list_item = LIST_ITEM_RE.match(line) # If the line is not a list item, skip to the next line if not list_item: continue # Extract the text content of the list item and remove leading/trailing whitespace text = list_item.group(1).strip() # Extract item parts (title, author, metadata) if it matches the book format book_item = BOOK_ITEM_RE.match(text) # If the current line is a book item if book_item: # Extract title, author, and metadata from the book item title = book_item.group('title') author = (book_item.group('author') or '').strip() meta = (book_item.group('meta') or '').strip() # If the list item is just a link like the link in the section "### Index" of the .md files (i.e., [Title](url)) is_link_only_item = not author and not meta # Otherwise, if it's not a book item else: # Initialize title, author, and meta with empty strings title, author, meta = text, '', '' # Set is_link_only_item to False is_link_only_item = False # Specific check: RTL author followed by LTR metadata (e.g., اسم المؤلف (PDF)) if active_block_direction_ctx == 'rtl' and \ author and meta and \ rtl_char_re.search(author) and pure_ltr_re.match(meta) and \ len(meta) >= min_len and \ not any(author.strip().endswith(rlm_marker) for rlm_marker in RLM): issues.append( f"::{sev['author_meta'].lower()} file={path},line={idx}::RTL author '{author.strip()}' followed by LTR meta '{meta}' may need '&rlm;' after author." ) # Analyze individual parts of the item (title, author, metadata) for part, raw_text in [('title', title), ('author', author), ('meta', meta)]: # Skip if the part is empty or if it's metadata to be ignored (e.g., "PDF") if not raw_text or (part=='meta' and raw_text in ignore_meta): continue # Split the part into segments based on <span> tags with dir attributes segments = split_by_span(raw_text, active_block_direction_ctx) # Filter keywords to avoid duplicates with symbols (a symbol can contain a keyword) filtered_keywords = [kw for kw in keywords_orig] for sym in symbols: filtered_keywords = [kw for kw in filtered_keywords if kw not in sym] # Iterate over each text segment and its directionality context for segment_text, segment_direction_ctx in segments: # Remove leading/trailing whitespace from the segment text s = segment_text.strip() # In the following block of code, it's checked if the segment is entirely enclosed in parentheses or brackets. # In fact, if the content inside is purely LTR or RTL, its display is usually # well-isolated by the parentheses or brackets and less prone to BIDI issues. # Mixed LTR/RTL content inside brackets should still be checked. # Check if the segment is entirely enclosed in parentheses or brackets. m_bracket = BRACKET_CONTENT_RE.fullmatch(s) if m_bracket: # If it is, extract the content inside the parentheses/brackets. inner_content = m_bracket.group(2) # Determine if the inner content is purely LTR or purely RTL. is_pure_ltr_inner = pure_ltr_re.match(inner_content) is not None # Check for pure RTL: contains RTL chars AND no LTR chars (using [A-Za-z0-9] as a proxy for common LTR chars) is_pure_rtl_inner = rtl_char_re.search(inner_content) is not None and re.search(r"[A-Za-z0-9]", inner_content) is None # Skip the segment ONLY if the content inside is purely LTR or purely RTL. if is_pure_ltr_inner or is_pure_rtl_inner: continue # Skip if it's inline code (i.e., `...`) or already contains directionality markers (e.g., &rlm; or &lrm;) if any([ INLINE_CODE_RE.match(s), any(mk in s for mk in RLM+LRM) ]): continue # Check for BIDI mismatch: if the text contains both RTL and LTR # characters and the calculated visual order differs from the logical order. if rtl_char_re.search(s) and re.search(r"[A-Za-z0-9]", s): disp = get_display(s) if disp != s: issues.append( f"::{sev['bidi_mismatch'].lower()} file={path},line={idx}::BIDI mismatch in {part}: the text '{s}' is displayed as '{disp}'" ) # If the segment context is LTR, there is no need to check LTR keywords and LTR symbols # that might need directionality markers, so we can skip the next checks and move on to the next line of the file if segment_direction_ctx != 'rtl': continue # Skip keyword and symbol checks for titles of link-only items (e.g., in the Index section of markdown files) if not (part == 'title' and is_link_only_item): # Check for LTR symbols: if an LTR symbol is present and lacks an '&lrm;' marker for sym in symbols: if sym in s and not any(m in s for m in LRM): issues.append( f"::{sev['symbol'].lower()} file={path},line={idx}::Symbol '{sym}' in {part} '{s}' may need trailing '&lrm;' marker." ) # Check for LTR keywords: if an LTR keyword is present and lacks an RLM marker for kw in filtered_keywords: if kw in s and not any(m in s for m in RLM): issues.append( f"::{sev['keyword'].lower()} file={path},line={idx}::Keyword '{kw}' in {part} '{s}' may need trailing '&rlm;' marker." ) # Check for "Pure LTR" text: if the segment is entirely LTR, # it's not a title, and has a minimum length, it might need a trailing RLM. if (part != 'title') and pure_ltr_re.match(s) and not rtl_char_re.search(s) and len(s)>=min_len: issues.append( f"::{sev['pure_ltr'].lower()} file={path},line={idx}::Pure LTR text '{s}' in {part} of RTL context may need trailing '&rlm;' marker." ) # Check for unclosed div tags at the end of the file if len(block_context_stack) > 1: issues.append( f"::error file={path},line={len(lines)}::Found unclosed <div dir='...'> tag. " f"The final block context is '{block_context_stack[-1]}', not the file's base '{file_direction_ctx}'." ) # Return the list of found issues return issues def get_changed_lines_for_file(filepath): import subprocess changed_lines = set() try: # Get the diff for the file (unified=0 for no context lines) diff = subprocess.check_output( ['git', 'diff', '--unified=0', 'origin/main...', '--', filepath], encoding='utf-8', errors='ignore' ) for line in diff.splitlines(): if line.startswith('@@'): # Example: @@ -10,0 +11,3 @@ m = re.search(r'\+(\d+)(?:,(\d+))?', line) if m: start = int(m.group(1)) count = int(m.group(2) or '1') for i in range(start, start + count): changed_lines.add(i) except Exception: # Silently ignore errors (e.g., unable to find merge base) pass return changed_lines def main(): # Create an ArgumentParser object to handle command-line arguments parser = argparse.ArgumentParser( description="Lints Markdown files for RTL/LTR issues, with PR annotation support." ) # Argument for files/directories to scan parser.add_argument( 'paths_to_scan', nargs='+', help="List of files or directories to scan for all issues." ) # Optional argument for changed files (for PR annotation filtering) parser.add_argument( '--changed-files', nargs='*', default=None, help="List of changed files to generate PR annotations for." ) # Optional argument for the log file path parser.add_argument( '--log-file', default='rtl-linter-output.log', help="File to write all linter output to." ) # Parse the command-line arguments args = parser.parse_args() # Determine the directory where the script is located to find the config file script_dir = os.path.dirname(os.path.abspath(__file__)) # Load the configuration from 'rtl_linter_config.yml' cfg = load_config(os.path.join(script_dir, 'rtl_linter_config.yml')) # Initialize counters for total files processed and errors/warnings found total = errs = 0 # Count errors/warnings ONLY on changed/added lines for PR annotation exit code annotated_errs = 0 # Normalize changed file paths for consistent comparison changed_files_set = set(os.path.normpath(f) for f in args.changed_files) if args.changed_files else set() # Build a map: {filepath: set(line_numbers)} for changed files changed_lines_map = {} for f in changed_files_set: changed_lines_map[f] = get_changed_lines_for_file(f) # Flag to check if any issues were found any_issues = False # Open the specified log file in write mode with UTF-8 encoding with open(args.log_file, 'w', encoding='utf-8') as log_f: # Iterate over each path provided in 'paths_to_scan' for p_scan_arg in args.paths_to_scan: # Normalize the scan path to ensure consistent handling (e.g., slashes) normalized_scan_path = os.path.normpath(p_scan_arg) # If the path is a directory, recursively scan for .md files if os.path.isdir(normalized_scan_path): # Walk through the directory and its subdirectories to find all Markdown files for root, _, files in os.walk(normalized_scan_path): # For each file in the directory for fn in files: # If the file is a Markdown file, lint it if fn.lower().endswith('.md'): file_path = os.path.normpath(os.path.join(root, fn)) total += 1 issues_found = lint_file(file_path, cfg) # Process each issue found for issue_str in issues_found: log_f.write(issue_str + '\n') any_issues = True # Flag to check if any issues were found # For GitHub Actions PR annotations: print only if the file is changed # and the issue is on a line that was actually modified or added in the PR if file_path in changed_files_set: m = re.search(r'line=(\d+)', issue_str) if m and int(m.group(1)) in changed_lines_map.get(file_path, set()): print(issue_str) # Count errors on changed lines for the exit code logic if issue_str.startswith("::error"): annotated_errs += 1 # Count all errors/warnings for reporting/debugging purposes if issue_str.startswith("::error") or issue_str.startswith("::warning"): errs += 1 # If the path is a Markdown file, lint it directly elif normalized_scan_path.lower().endswith('.md'): total += 1 issues_found = lint_file(normalized_scan_path, cfg) # Process each issue found for issue_str in issues_found: # Always write the issue to the log file for full reporting log_f.write(issue_str + '\n') any_issues = True # Flag to check if any issues were found # For GitHub Actions PR annotations: print only if the file is changed # and the issue is on a line that was actually modified or added in the PR if normalized_scan_path in changed_files_set: # Extract the line number from the issue string (e.g., ...line=123::) m = re.search(r'line=(\d+)', issue_str) if m and int(m.group(1)) in changed_lines_map.get(normalized_scan_path, set()): # For GitHub Actions PR annotations: print the annotation # so that GitHub Actions can display it in the PR summary print(issue_str) # Count errors on changed lines for the exit code logic if issue_str.startswith("::error"): annotated_errs += 1 # Count all errors/warnings for reporting/debugging purposes if issue_str.startswith("::error") or issue_str.startswith("::warning"): errs += 1 # If no issues were found, remove the log file if not any_issues: try: os.remove(args.log_file) except Exception: pass # Print a debug message to stderr summarizing the linting process print(f"::notice ::Processed {total} files, found {errs} issues.") # Exit code: 1 only if there are annotated errors/warnings on changed lines sys.exit(1 if annotated_errs else 0) if __name__ == '__main__': main()
--- +++ @@ -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 script. + +Key Features: +- Line-by-line parsing of Markdown list items. +- Detection of HTML 'dir' attributes to switch text direction context. +- Handling of nested 'dir' contexts within '<span>' tags. +- Detection of LTR keywords and symbols that might require Unicode markers. +- BIDI (Bidirectional Algorithm) visual analysis using the 'python-bidi' library. +- Parsing of metadata for book items (title, author, meta). +- Configurable severity levels for detected issues (error, warning, notice). +- Filters to ignore code blocks, inline code, and text within parentheses. +- Specific check for RTL authors followed by LTR metadata. +""" import sys import os import argparse @@ -8,6 +27,20 @@ def load_config(path): + """ + Loads configuration from the specified YAML file. + + If the file does not exist or an error occurs during loading, + default values will be used. + + Args: + path (str): The path to the YAML configuration file. + + Returns: + dict: A dictionary containing the configuration parameters. + Default values are merged with those loaded from the file, + with the latter taking precedence. + """ # Default configuration values default = { 'ltr_keywords': [], @@ -42,6 +75,15 @@ def is_rtl_filename(path): + ''' + Checks if the given filename indicates an RTL filename. + + Args: + path (str): The path to the file. + + Returns: + bool: True if the filename suggests an RTL language, False otherwise. + ''' name = os.path.basename(path).lower() return any(name.endswith(suf) for suf in ['-ar.md','_ar.md','-he.md','_he.md','-fa.md','_fa.md','-ur.md','_ur.md']) @@ -81,6 +123,37 @@ def split_by_span(text, base_ctx): + """ + Splits text into segments based on nested <span> tags with dir attributes. + + Args: + text (str): The input string to split. + base_ctx (str): The base directionality context ('rtl' or 'ltr'). + + Returns: + list: A list of tuples, where each tuple contains a text segment (str) + and its corresponding directionality context ('rtl' or 'ltr'). + + Example of stack behavior: + Input: "Text <span dir='rtl'>RTL <span dir='ltr'>LTR</span> RTL</span> Text" + base_ctx: 'ltr' + + Initial stack: ['ltr'] + Tokens: ["Text ", "<span dir='rtl'>", "RTL ", "<span dir='ltr'>", "LTR", "</span>", " RTL", "</span>", " Text"] + + Processing: + 1. "Text ": segments.append(("Text ", 'ltr')), stack: ['ltr'] + 2. "<span dir='rtl'>": stack.append('rtl'), stack: ['ltr', 'rtl'] + 3. "RTL ": segments.append(("RTL ", 'rtl')), stack: ['ltr', 'rtl'] + 4. "<span dir='ltr'>": stack.append('ltr'), stack: ['ltr', 'rtl', 'ltr'] + 5. "LTR": segments.append(("LTR", 'ltr')), stack: ['ltr', 'rtl', 'ltr'] + 6. "</span>": stack.pop(), stack: ['ltr', 'rtl'] + 7. " RTL": segments.append((" RTL", 'rtl')), stack: ['ltr', 'rtl'] + 8. "</span>": stack.pop(), stack: ['ltr'] + 9. " Text": segments.append((" Text", 'ltr')), stack: ['ltr'] + + Resulting segments: [("Text ", 'ltr'), ("RTL ", 'rtl'), ("LTR", 'ltr'), (" RTL", 'rtl'), (" Text", 'ltr')] + """ # Split the text based on <span> tags tokens = re.split(r'(<span[^>]*dir=["\'](?:rtl|ltr)["\'][^>]*>|</span>)', text) @@ -121,6 +194,17 @@ def lint_file(path, cfg): + """ + Analyzes a single Markdown file for RTL/LTR issues. + + Args: + path (str): The path to the Markdown file to analyze. + cfg (dict): The configuration dictionary. + + Returns: + list: A list of strings, where each string represents a detected issue, + formatted for GitHub Actions output. + """ # Initialize the list of issues issues = [] @@ -318,6 +402,23 @@ return issues def get_changed_lines_for_file(filepath): + """ + Returns a set of line numbers (1-based) that were changed in the given file in the current PR. + + This function uses 'git diff' to compare the current branch with 'origin/main' and extracts + the line numbers of added or modified lines. It is used to restrict PR annotations to only + those lines that have been changed in the pull request. + + Args: + filepath (str): The path to the file to check for changes. + + Returns: + set: A set of 1-based line numbers that were added or modified in the file. + + Note: + - Requires that the script is run inside a Git repository. + - If the merge base cannot be found, returns an empty set and does not print errors. + """ import subprocess changed_lines = set() try: @@ -342,6 +443,21 @@ def main(): + """ + Main entry point for the RTL/LTR Markdown linter. + + Parses command-line arguments, loads configuration, and scans the specified files or directories + for Markdown files. For each file, it detects RTL/LTR issues and writes all findings to a log file. + For files changed in the current PR, only issues on changed lines are printed to stdout as GitHub + Actions annotations. + + Exit code is 1 if any error or warning is found on changed lines, otherwise 0. + + Command-line arguments: + paths_to_scan: List of files or directories to scan for issues. + --changed-files: List of files changed in the PR (for annotation filtering). + --log-file: Path to the output log file (default: rtl-linter-output.log). + """ # Create an ArgumentParser object to handle command-line arguments parser = argparse.ArgumentParser( description="Lints Markdown files for RTL/LTR issues, with PR annotation support." @@ -486,4 +602,4 @@ sys.exit(1 if annotated_errs else 0) if __name__ == '__main__': - main()+ main()
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 @property @abstractmethod def value(self): pass @value.setter @abstractmethod def value(self, other): pass class BlackJackCard(Card): def __init__(self, value, suit): super(BlackJackCard, self).__init__(value, suit) def is_ace(self): return True if self._value == 1 else False def is_face_card(self): return True if 10 < self._value <= 13 else False @property def value(self): if self.is_ace() == 1: return 1 elif self.is_face_card(): return 10 else: return self._value @value.setter def value(self, new_value): if 1 <= new_value <= 13: self._value = new_value else: raise ValueError('Invalid card value: {}'.format(new_value)) class Hand(object): def __init__(self, cards): self.cards = cards def add_card(self, card): self.cards.append(card) def score(self): total_value = 0 for card in self.cards: total_value += card.value return total_value class BlackJackHand(Hand): BLACKJACK = 21 def __init__(self, cards): super(BlackJackHand, self).__init__(cards) def score(self): min_over = sys.MAXSIZE max_under = -sys.MAXSIZE for score in self.possible_scores(): if self.BLACKJACK < score < min_over: min_over = score elif max_under < score <= self.BLACKJACK: max_under = score return max_under if max_under != -sys.MAXSIZE else min_over def possible_scores(self): pass class Deck(object): def __init__(self, cards): self.cards = cards self.deal_index = 0 def remaining_cards(self): return len(self.cards) - self.deal_index def deal_card(self): try: card = self.cards[self.deal_index] card.is_available = False self.deal_index += 1 except IndexError: return None return card def shuffle(self): pass
--- +++ @@ -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 def possible_scores(self): + """Return a list of possible scores, taking Aces into account.""" pass @@ -112,4 +114,4 @@ return card def shuffle(self): - pass+ pass
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.parse_query(query) results = self.memory_cache.get(query) if results is None: results = self.reverse_index_cluster.process_search(query) self.memory_cache.set(query, results) return results class Node(object): def __init__(self, query, results): self.query = query self.results = results class LinkedList(object): def __init__(self): self.head = None self.tail = None def move_to_front(self, node): ... def append_to_front(self, node): ... def remove_from_tail(self): ... class Cache(object): def __init__(self, MAX_SIZE): self.MAX_SIZE = MAX_SIZE self.size = 0 self.lookup = {} self.linked_list = LinkedList() def get(self, query): node = self.lookup[query] if node is None: return None self.linked_list.move_to_front(node) return node.results def set(self, results, query): node = self.map[query] if node is not None: # Key exists in cache, update the value node.results = results self.linked_list.move_to_front(node) else: # Key does not exist in cache if self.size == self.MAX_SIZE: # Remove the oldest entry from the linked list and lookup self.lookup.pop(self.linked_list.tail.query, None) self.linked_list.remove_from_tail() else: self.size += 1 # Add the new key and value new_node = Node(query, results) self.linked_list.append_to_front(new_node) self.lookup[query] = new_node
--- +++ @@ -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): @@ -51,6 +54,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[query] if node is None: return None @@ -58,6 +65,12 @@ return node.results def set(self, results, query): + """Set the result for the given query key in the cache. + + When updating an entry, updates its position to the front of the LRU list. + If the entry is new and the cache is at capacity, removes the oldest entry + before the new entry is added. + """ node = self.map[query] if node is not None: # Key exists in cache, update the value @@ -74,4 +87,4 @@ # Add the new key and value new_node = Node(query, results) self.linked_list.append_to_front(new_node) - self.lookup[query] = new_node+ self.lookup[query] = new_node
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_plate self.spot_size self.spots_taken = [] def clear_spots(self): for spot in self.spots_taken: spot.remove_vehicle(self) self.spots_taken = [] def take_spot(self, spot): self.spots_taken.append(spot) @abstractmethod def can_fit_in_spot(self, spot): pass class Motorcycle(Vehicle): def __init__(self, license_plate): super(Motorcycle, self).__init__(VehicleSize.MOTORCYCLE, license_plate, spot_size=1) def can_fit_in_spot(self, spot): return True class Car(Vehicle): def __init__(self, license_plate): super(Car, self).__init__(VehicleSize.COMPACT, license_plate, spot_size=1) def can_fit_in_spot(self, spot): return spot.size in (VehicleSize.LARGE, VehicleSize.COMPACT) class Bus(Vehicle): def __init__(self, license_plate): super(Bus, self).__init__(VehicleSize.LARGE, license_plate, spot_size=5) def can_fit_in_spot(self, spot): return spot.size == VehicleSize.LARGE class ParkingLot(object): def __init__(self, num_levels): self.num_levels = num_levels self.levels = [] # List of Levels def park_vehicle(self, vehicle): for level in self.levels: if level.park_vehicle(vehicle): return True return False class Level(object): SPOTS_PER_ROW = 10 def __init__(self, floor, total_spots): self.floor = floor self.num_spots = total_spots self.available_spots = 0 self.spots = [] # List of ParkingSpots def spot_freed(self): self.available_spots += 1 def park_vehicle(self, vehicle): spot = self._find_available_spot(vehicle) if spot is None: return None else: spot.park_vehicle(vehicle) return spot def _find_available_spot(self, vehicle): pass def _park_starting_at_spot(self, spot, vehicle): pass class ParkingSpot(object): def __init__(self, level, row, spot_number, spot_size, vehicle_size): self.level = level self.row = row self.spot_number = spot_number self.spot_size = spot_size self.vehicle_size = vehicle_size self.vehicle = None def is_available(self): return True if self.vehicle is None else False def can_fit_vehicle(self, vehicle): if self.vehicle is not None: return False return vehicle.can_fit_in_spot(self) def park_vehicle(self, vehicle): pass def remove_vehicle(self): pass
--- +++ @@ -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.""" pass @@ -120,4 +122,4 @@ pass def remove_vehicle(self): - pass+ pass
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 def remove_from_tail(self): pass class Cache(object): def __init__(self, MAX_SIZE): self.MAX_SIZE = MAX_SIZE self.size = 0 self.lookup = {} # key: query, value: node self.linked_list = LinkedList() def get(self, query): node = self.lookup.get(query) if node is None: return None self.linked_list.move_to_front(node) return node.results def set(self, results, query): node = self.lookup.get(query) if node is not None: # Key exists in cache, update the value node.results = results self.linked_list.move_to_front(node) else: # Key does not exist in cache if self.size == self.MAX_SIZE: # Remove the oldest entry from the linked list and lookup self.lookup.pop(self.linked_list.tail.query, None) self.linked_list.remove_from_tail() else: self.size += 1 # Add the new key and value new_node = Node(results) self.linked_list.append_to_front(new_node) self.lookup[query] = new_node
--- +++ @@ -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: return None @@ -37,6 +41,12 @@ return node.results def set(self, results, query): + """Set the result for the given query key in the cache. + + When updating an entry, updates its position to the front of the LRU list. + If the entry is new and the cache is at capacity, removes the oldest entry + before the new entry is added. + """ node = self.lookup.get(query) if node is not None: # Key exists in cache, update the value @@ -53,4 +63,4 @@ # Add the new key and value new_node = Node(results) self.linked_list.append_to_front(new_node) - self.lookup[query] = new_node+ self.lookup[query] = new_node
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_page(self): pass def insert_crawled_link(self, url, signature): pass def crawled_similar(self, signature): pass class Page(object): def __init__(self, url, contents, child_urls): self.url = url self.contents = contents self.child_urls = child_urls self.signature = self.create_signature() def create_signature(self): # Create signature based on url and contents pass class Crawler(object): def __init__(self, pages, data_store, reverse_index_queue, doc_index_queue): self.pages = pages self.data_store = data_store self.reverse_index_queue = reverse_index_queue self.doc_index_queue = doc_index_queue def crawl_page(self, page): for url in page.child_urls: self.data_store.add_link_to_crawl(url) self.reverse_index_queue.generate(page) self.doc_index_queue.generate(page) self.data_store.remove_link_to_crawl(page.url) self.data_store.insert_crawled_link(page.url, page.signature) def crawl(self): while True: page = self.data_store.extract_max_priority_page() if page is None: break if self.data_store.crawled_similar(page.signature): self.data_store.reduce_priority_link_to_crawl(page.url) else: self.crawl_page(page) page = self.data_store.extract_max_priority_page()
--- +++ @@ -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): + """Reduce the priority of a link in `links_to_crawl` to avoid cycles.""" pass def extract_max_priority_page(self): + """Return the highest priority link in `links_to_crawl`.""" pass def insert_crawled_link(self, url, signature): + """Add the given link to `crawled_links`.""" pass def crawled_similar(self, signature): + """Determine if we've already crawled a page matching the given signature""" pass @@ -64,4 +70,4 @@ self.data_store.reduce_priority_link_to_crawl(page.url) else: self.crawl_page(page) - page = self.data_store.extract_max_priority_page()+ page = self.data_store.extract_max_priority_page()
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_id), quantity def reducer(self, key, values): yield key, sum(values) def mapper_sort(self, key, value): category, product_id = key quantity = value yield (category, quantity), product_id def reducer_identity(self, key, value): yield key, value def steps(self): return [ self.mr(mapper=self.mapper, reducer=self.reducer), self.mr(mapper=self.mapper_sort, reducer=self.reducer_identity), ] if __name__ == '__main__': SalesRanker.run()
--- +++ @@ -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 pairs of the form: + + (foo, p1), 2 + (bar, p1), 2 + (bar, p1), 1 + (foo, p2), 3 + (bar, p3), 10 + (foo, p4), 1 + """ timestamp, product_id, category, quantity = line.split('\t') if self.within_past_week(timestamp): yield (category, product_id), quantity def reducer(self, key, values): + """Sum values for each key. + + (foo, p1), 2 + (bar, p1), 3 + (foo, p2), 3 + (bar, p3), 10 + (foo, p4), 1 + """ yield key, sum(values) def mapper_sort(self, key, value): + """Construct key to ensure proper sorting. + + Transform key and value to the form: + + (foo, 2), p1 + (bar, 3), p1 + (foo, 3), p2 + (bar, 10), p3 + (foo, 1), p4 + + The shuffle/sort step of MapReduce will then do a + distributed sort on the keys, resulting in: + + (category1, 1), product4 + (category1, 2), product1 + (category1, 3), product2 + (category2, 3), product1 + (category2, 7), product3 + """ category, product_id = key quantity = value yield (category, quantity), product_id @@ -25,6 +64,7 @@ yield key, value def steps(self): + """Run the map and reduce steps.""" return [ self.mr(mapper=self.mapper, reducer=self.reducer), @@ -34,4 +74,4 @@ if __name__ == '__main__': - SalesRanker.run()+ SalesRanker.run()
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(self, key, total): ... def mapper(self, _, line): timestamp, category, amount = line.split('\t') period = self. extract_year_month(timestamp) if period == self.current_year_month(): yield (period, category), amount def reducer(self, key, values): total = sum(values) self.handle_budget_notifications(key, total) yield key, sum(values) def steps(self): return [ self.mr(mapper=self.mapper, reducer=self.reducer) ] if __name__ == '__main__': SpendingByCategory.run()
--- +++ @@ -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, total): + """Call notification API if nearing or exceeded budget.""" ... def mapper(self, _, line): + """Parse each log line, extract and transform relevant lines. + + Emit key value pairs of the form: + + (2016-01, shopping), 25 + (2016-01, shopping), 100 + (2016-01, gas), 50 + """ timestamp, category, amount = line.split('\t') period = self. extract_year_month(timestamp) if period == self.current_year_month(): yield (period, category), amount def reducer(self, key, values): + """Sum values for each key. + + (2016-01, shopping), 125 + (2016-01, gas), 50 + """ total = sum(values) self.handle_budget_notifications(key, total) yield key, sum(values) def steps(self): + """Run the map and reduce steps.""" return [ self.mr(mapper=self.mapper, reducer=self.reducer) @@ -37,4 +54,4 @@ if __name__ == '__main__': - SpendingByCategory.run()+ SpendingByCategory.run()
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, url), 1 def reducer(self, key, values): yield key, sum(values) def steps(self): return [ self.mr(mapper=self.mapper, reducer=self.reducer) ] if __name__ == '__main__': HitCounts.run()
--- +++ @@ -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): + """Parse each log line, extract and transform relevant lines. + + Emit key value pairs of the form: + + (2016-01, url0), 1 + (2016-01, url0), 1 + (2016-01, url1), 1 + """ url = self.extract_url(line) period = self.extract_year_month(line) yield (period, url), 1 def reducer(self, key, values): + """Sum values for each key. + + (2016-01, url0), 2 + (2016-01, url1), 1 + """ yield key, sum(values) def steps(self): + """Run the map and reduce steps.""" return [ self.mr(mapper=self.mapper, reducer=self.reducer) @@ -27,4 +43,4 @@ if __name__ == '__main__': - HitCounts.run()+ HitCounts.run()
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 = Path(__file__).parent.parent / "README.md" GRAPHQL_URL = "https://api.github.com/graphql" BATCH_SIZE = 50 def extract_github_repos(text: str) -> set[str]: repos = set() for url in re.findall(r"https?://github\.com/[^\s)\]]+", text): repo = extract_github_repo(url.split("#")[0].rstrip("/")) if repo: repos.add(repo) return repos def save_cache(cache: dict) -> None: DATA_DIR.mkdir(parents=True, exist_ok=True) CACHE_FILE.write_text( json.dumps(cache, indent=2, ensure_ascii=False) + "\n", encoding="utf-8", ) def build_graphql_query(repos: list[str]) -> str: if not repos: return "" parts = [] for i, repo in enumerate(repos): owner, name = repo.split("/", 1) if '"' in owner or '"' in name: continue parts.append( f'repo_{i}: repository(owner: "{owner}", name: "{name}") ' f"{{ stargazerCount owner {{ login }} defaultBranchRef {{ target {{ ... on Commit {{ committedDate }} }} }} }}" ) if not parts: return "" return "query { " + " ".join(parts) + " }" def parse_graphql_response( data: dict, repos: list[str], ) -> dict[str, dict]: result = {} for i, repo in enumerate(repos): node = data.get(f"repo_{i}") if node is None: continue default_branch = node.get("defaultBranchRef") or {} target = default_branch.get("target") or {} result[repo] = { "stars": node.get("stargazerCount", 0), "owner": node.get("owner", {}).get("login", ""), "last_commit_at": target.get("committedDate", ""), } return result def fetch_batch( repos: list[str], *, client: httpx.Client, ) -> dict[str, dict]: query = build_graphql_query(repos) if not query: return {} resp = client.post(GRAPHQL_URL, json={"query": query}) resp.raise_for_status() result = resp.json() if "errors" in result: for err in result["errors"]: print(f" Warning: {err.get('message', err)}", file=sys.stderr) data = result.get("data", {}) return parse_graphql_response(data, repos) def main() -> None: token = os.environ.get("GITHUB_TOKEN", "") if not token: print("Error: GITHUB_TOKEN environment variable is required.", file=sys.stderr) sys.exit(1) readme_text = README_PATH.read_text(encoding="utf-8") current_repos = extract_github_repos(readme_text) print(f"Found {len(current_repos)} GitHub repos in README.md") cache = load_stars(CACHE_FILE) now = datetime.now(timezone.utc) # Prune entries not in current README pruned = {k: v for k, v in cache.items() if k in current_repos} if len(pruned) < len(cache): print(f"Pruned {len(cache) - len(pruned)} stale cache entries") cache = pruned # Determine which repos need fetching (missing or stale) to_fetch = [] for repo in sorted(current_repos): entry = cache.get(repo) if entry and "fetched_at" in entry: fetched = datetime.fromisoformat(entry["fetched_at"]) age_hours = (now - fetched).total_seconds() / 3600 if age_hours < CACHE_MAX_AGE_HOURS: continue to_fetch.append(repo) print(f"{len(to_fetch)} repos to fetch ({len(current_repos) - len(to_fetch)} cached)") if not to_fetch: save_cache(cache) print("Cache is up to date.") return # Fetch in batches fetched_count = 0 skipped_repos: list[str] = [] with httpx.Client( headers={"Authorization": f"bearer {token}", "Content-Type": "application/json"}, transport=httpx.HTTPTransport(retries=2), timeout=30, ) as client: for i in range(0, len(to_fetch), BATCH_SIZE): batch = to_fetch[i : i + BATCH_SIZE] batch_num = i // BATCH_SIZE + 1 total_batches = (len(to_fetch) + BATCH_SIZE - 1) // BATCH_SIZE print(f"Fetching batch {batch_num}/{total_batches} ({len(batch)} repos)...") try: results = fetch_batch(batch, client=client) except httpx.HTTPStatusError as e: print(f"HTTP error {e.response.status_code}", file=sys.stderr) if e.response.status_code == 401: print("Error: Invalid GITHUB_TOKEN.", file=sys.stderr) sys.exit(1) print("Saving partial cache and exiting.", file=sys.stderr) save_cache(cache) sys.exit(1) now_iso = now.isoformat() for repo in batch: if repo in results: cache[repo] = { "stars": results[repo]["stars"], "owner": results[repo]["owner"], "last_commit_at": results[repo]["last_commit_at"], "fetched_at": now_iso, } fetched_count += 1 else: skipped_repos.append(repo) # Save after each batch in case of interruption save_cache(cache) if skipped_repos: print(f"Skipped {len(skipped_repos)} repos (deleted/private/renamed)") print(f"Done. Fetched {fetched_count} repos, {len(cache)} total cached.") if __name__ == "__main__": main()
--- +++ @@ -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() for url in re.findall(r"https?://github\.com/[^\s)\]]+", text): repo = extract_github_repo(url.split("#")[0].rstrip("/")) @@ -29,6 +31,7 @@ def save_cache(cache: dict) -> None: + """Write the star cache to disk, creating data/ dir if needed.""" DATA_DIR.mkdir(parents=True, exist_ok=True) CACHE_FILE.write_text( json.dumps(cache, indent=2, ensure_ascii=False) + "\n", @@ -37,6 +40,7 @@ def build_graphql_query(repos: list[str]) -> str: + """Build a GraphQL query with aliases for up to 100 repos.""" if not repos: return "" parts = [] @@ -57,6 +61,7 @@ data: dict, repos: list[str], ) -> dict[str, dict]: + """Parse GraphQL response into {owner/repo: {stars, owner}} dict.""" result = {} for i, repo in enumerate(repos): node = data.get(f"repo_{i}") @@ -75,6 +80,7 @@ def fetch_batch( repos: list[str], *, client: httpx.Client, ) -> dict[str, dict]: + """Fetch star data for a batch of repos via GitHub GraphQL API.""" query = build_graphql_query(repos) if not query: return {} @@ -89,6 +95,7 @@ def main() -> None: + """Fetch GitHub stars for all repos in README.md, updating the JSON cache.""" token = os.environ.get("GITHUB_TOKEN", "") if not token: print("Error: GITHUB_TOKEN environment variable is required.", file=sys.stderr) @@ -173,4 +180,4 @@ if __name__ == "__main__": - main()+ main()
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 # inline HTML, properly escaped also_see: list[AlsoSee] class ParsedSection(TypedDict): name: str slug: str description: str # plain text, links resolved to text entries: list[ParsedEntry] entry_count: int preview: str content_html: str # rendered HTML, properly escaped # --- Slugify ---------------------------------------------------------------- _SLUG_NON_ALNUM_RE = re.compile(r"[^a-z0-9\s-]") _SLUG_WHITESPACE_RE = re.compile(r"[\s]+") _SLUG_MULTI_DASH_RE = re.compile(r"-+") def slugify(name: str) -> str: slug = name.lower() slug = _SLUG_NON_ALNUM_RE.sub("", slug) slug = _SLUG_WHITESPACE_RE.sub("-", slug.strip()) slug = _SLUG_MULTI_DASH_RE.sub("-", slug) return slug # --- Inline renderers ------------------------------------------------------- def render_inline_html(children: list[SyntaxTreeNode]) -> str: parts: list[str] = [] for child in children: match child.type: case "text": parts.append(str(escape(child.content))) case "softbreak": parts.append(" ") case "link": href = str(escape(child.attrGet("href") or "")) inner = render_inline_html(child.children) parts.append( f'<a href="{href}" target="_blank" rel="noopener">{inner}</a>' ) case "em": parts.append(f"<em>{render_inline_html(child.children)}</em>") case "strong": parts.append(f"<strong>{render_inline_html(child.children)}</strong>") case "code_inline": parts.append(f"<code>{escape(child.content)}</code>") case "html_inline": parts.append(str(escape(child.content))) return "".join(parts) def render_inline_text(children: list[SyntaxTreeNode]) -> str: parts: list[str] = [] for child in children: match child.type: case "text": parts.append(child.content) case "softbreak": parts.append(" ") case "code_inline": parts.append(child.content) case "em" | "strong" | "link": parts.append(render_inline_text(child.children)) return "".join(parts) # --- AST helpers ------------------------------------------------------------- def _heading_text(node: SyntaxTreeNode) -> str: for child in node.children: if child.type == "inline": return render_inline_text(child.children) return "" def _extract_description(nodes: list[SyntaxTreeNode]) -> str: if not nodes: return "" first = nodes[0] if first.type != "paragraph": return "" for child in first.children: if child.type == "inline" and len(child.children) == 1: em = child.children[0] if em.type == "em": return render_inline_text(em.children) return "" # --- Entry extraction -------------------------------------------------------- _DESC_SEP_RE = re.compile(r"^\s*[-\u2013\u2014]\s*") def _find_child(node: SyntaxTreeNode, child_type: str) -> SyntaxTreeNode | None: for child in node.children: if child.type == child_type: return child return None def _find_inline(node: SyntaxTreeNode) -> SyntaxTreeNode | None: para = _find_child(node, "paragraph") if para is None: return None return _find_child(para, "inline") def _find_first_link(inline: SyntaxTreeNode) -> SyntaxTreeNode | None: for child in inline.children: if child.type == "link": return child return None def _is_leading_link(inline: SyntaxTreeNode, link: SyntaxTreeNode) -> bool: return bool(inline.children) and inline.children[0] is link def _extract_description_html(inline: SyntaxTreeNode, first_link: SyntaxTreeNode) -> str: link_idx = next((i for i, c in enumerate(inline.children) if c is first_link), None) if link_idx is None: return "" desc_children = inline.children[link_idx + 1 :] if not desc_children: return "" html = render_inline_html(desc_children) return _DESC_SEP_RE.sub("", html) def _parse_list_entries(bullet_list: SyntaxTreeNode) -> list[ParsedEntry]: entries: list[ParsedEntry] = [] for list_item in bullet_list.children: if list_item.type != "list_item": continue inline = _find_inline(list_item) if inline is None: continue first_link = _find_first_link(inline) if first_link is None or not _is_leading_link(inline, first_link): # Subcategory label (plain text or text-before-link) — recurse into nested list nested = _find_child(list_item, "bullet_list") if nested: entries.extend(_parse_list_entries(nested)) continue # Entry with a link name = render_inline_text(first_link.children) url = first_link.attrGet("href") or "" desc_html = _extract_description_html(inline, first_link) # Collect also_see from nested bullet_list also_see: list[AlsoSee] = [] nested = _find_child(list_item, "bullet_list") if nested: for sub_item in nested.children: if sub_item.type != "list_item": continue sub_inline = _find_inline(sub_item) if sub_inline: sub_link = _find_first_link(sub_inline) if sub_link: also_see.append(AlsoSee( name=render_inline_text(sub_link.children), url=sub_link.attrGet("href") or "", )) entries.append(ParsedEntry( name=name, url=url, description=desc_html, also_see=also_see, )) return entries def _parse_section_entries(content_nodes: list[SyntaxTreeNode]) -> list[ParsedEntry]: entries: list[ParsedEntry] = [] for node in content_nodes: if node.type == "bullet_list": entries.extend(_parse_list_entries(node)) return entries # --- Content HTML rendering -------------------------------------------------- def _render_bullet_list_html( bullet_list: SyntaxTreeNode, *, is_sub: bool = False, ) -> str: out: list[str] = [] for list_item in bullet_list.children: if list_item.type != "list_item": continue inline = _find_inline(list_item) if inline is None: continue first_link = _find_first_link(inline) if first_link is None or not _is_leading_link(inline, first_link): # Subcategory label (plain text or text-before-link) label = str(escape(render_inline_text(inline.children))) out.append(f'<div class="subcat">{label}</div>') nested = _find_child(list_item, "bullet_list") if nested: out.append(_render_bullet_list_html(nested, is_sub=False)) continue # Entry with a link name = str(escape(render_inline_text(first_link.children))) url = str(escape(first_link.attrGet("href") or "")) if is_sub: out.append(f'<div class="entry-sub"><a href="{url}">{name}</a></div>') else: desc = _extract_description_html(inline, first_link) if desc: out.append( f'<div class="entry"><a href="{url}">{name}</a>' f'<span class="sep">&mdash;</span>{desc}</div>' ) else: out.append(f'<div class="entry"><a href="{url}">{name}</a></div>') # Nested items under an entry with a link are sub-entries nested = _find_child(list_item, "bullet_list") if nested: out.append(_render_bullet_list_html(nested, is_sub=True)) return "\n".join(out) def _render_section_html(content_nodes: list[SyntaxTreeNode]) -> str: parts: list[str] = [] for node in content_nodes: if node.type == "bullet_list": parts.append(_render_bullet_list_html(node)) return "\n".join(parts) # --- Section splitting ------------------------------------------------------- def _group_by_h2( nodes: list[SyntaxTreeNode], ) -> list[ParsedSection]: sections: list[ParsedSection] = [] current_name: str | None = None current_body: list[SyntaxTreeNode] = [] def flush() -> None: nonlocal current_name if current_name is None: return desc = _extract_description(current_body) content_nodes = current_body[1:] if desc else current_body entries = _parse_section_entries(content_nodes) entry_count = len(entries) + sum(len(e["also_see"]) for e in entries) preview = ", ".join(e["name"] for e in entries[:4]) content_html = _render_section_html(content_nodes) sections.append(ParsedSection( name=current_name, slug=slugify(current_name), description=desc, entries=entries, entry_count=entry_count, preview=preview, content_html=content_html, )) current_name = None for node in nodes: if node.type == "heading" and node.tag == "h2": flush() current_name = _heading_text(node) current_body = [] elif current_name is not None: current_body.append(node) flush() return sections def parse_readme(text: str) -> tuple[list[ParsedSection], list[ParsedSection]]: md = MarkdownIt("commonmark") tokens = md.parse(text) root = SyntaxTreeNode(tokens) children = root.children # Find thematic break (---), # Resources, and # Contributing in one pass hr_idx = None resources_idx = None contributing_idx = None for i, node in enumerate(children): if hr_idx is None and node.type == "hr": hr_idx = i elif node.type == "heading" and node.tag == "h1": text_content = _heading_text(node) if text_content == "Resources": resources_idx = i elif text_content == "Contributing": contributing_idx = i if hr_idx is None: return [], [] # Slice into category and resource ranges cat_end = resources_idx or contributing_idx or len(children) cat_nodes = children[hr_idx + 1 : cat_end] res_nodes: list[SyntaxTreeNode] = [] if resources_idx is not None: res_end = contributing_idx or len(children) res_nodes = children[resources_idx + 1 : res_end] categories = _group_by_h2(cat_nodes) resources = _group_by_h2(res_nodes) return categories, resources
--- +++ @@ -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("", slug) slug = _SLUG_WHITESPACE_RE.sub("-", slug.strip()) @@ -50,6 +52,7 @@ def render_inline_html(children: list[SyntaxTreeNode]) -> str: + """Render inline AST nodes to HTML with proper escaping.""" parts: list[str] = [] for child in children: match child.type: @@ -75,6 +78,7 @@ def render_inline_text(children: list[SyntaxTreeNode]) -> str: + """Render inline AST nodes to plain text (links become their text).""" parts: list[str] = [] for child in children: match child.type: @@ -93,6 +97,7 @@ def _heading_text(node: SyntaxTreeNode) -> str: + """Extract plain text from a heading node.""" for child in node.children: if child.type == "inline": return render_inline_text(child.children) @@ -100,6 +105,10 @@ def _extract_description(nodes: list[SyntaxTreeNode]) -> str: + """Extract description from the first paragraph if it's a single <em> block. + + Pattern: _Libraries for foo._ -> "Libraries for foo." + """ if not nodes: return "" first = nodes[0] @@ -119,6 +128,7 @@ def _find_child(node: SyntaxTreeNode, child_type: str) -> SyntaxTreeNode | None: + """Find first direct child of a given type.""" for child in node.children: if child.type == child_type: return child @@ -126,6 +136,7 @@ def _find_inline(node: SyntaxTreeNode) -> SyntaxTreeNode | None: + """Find the inline node in a list_item's paragraph.""" para = _find_child(node, "paragraph") if para is None: return None @@ -133,6 +144,7 @@ def _find_first_link(inline: SyntaxTreeNode) -> SyntaxTreeNode | None: + """Find the first link node among inline children.""" for child in inline.children: if child.type == "link": return child @@ -140,10 +152,16 @@ def _is_leading_link(inline: SyntaxTreeNode, link: SyntaxTreeNode) -> bool: + """Check if the link is the first child of inline (a real entry, not a subcategory label).""" return bool(inline.children) and inline.children[0] is link def _extract_description_html(inline: SyntaxTreeNode, first_link: SyntaxTreeNode) -> str: + """Extract description HTML from inline content after the first link. + + AST: [link("name"), text(" - Description.")] -> "Description." + The separator (- / en-dash / em-dash) is stripped. + """ link_idx = next((i for i, c in enumerate(inline.children) if c is first_link), None) if link_idx is None: return "" @@ -155,6 +173,13 @@ def _parse_list_entries(bullet_list: SyntaxTreeNode) -> list[ParsedEntry]: + """Extract entries from a bullet_list AST node. + + Handles three patterns: + - Text-only list_item -> subcategory label -> recurse into nested list + - Link list_item with nested link-only items -> entry with also_see + - Link list_item without nesting -> simple entry + """ entries: list[ParsedEntry] = [] for list_item in bullet_list.children: @@ -206,6 +231,7 @@ def _parse_section_entries(content_nodes: list[SyntaxTreeNode]) -> list[ParsedEntry]: + """Extract all entries from a section's content nodes.""" entries: list[ParsedEntry] = [] for node in content_nodes: if node.type == "bullet_list": @@ -221,6 +247,7 @@ *, is_sub: bool = False, ) -> str: + """Render a bullet_list node to HTML with entry/entry-sub/subcat classes.""" out: list[str] = [] for list_item in bullet_list.children: @@ -267,6 +294,7 @@ def _render_section_html(content_nodes: list[SyntaxTreeNode]) -> str: + """Render a section's content nodes to HTML.""" parts: list[str] = [] for node in content_nodes: if node.type == "bullet_list": @@ -280,6 +308,7 @@ def _group_by_h2( nodes: list[SyntaxTreeNode], ) -> list[ParsedSection]: + """Group AST nodes into sections by h2 headings.""" sections: list[ParsedSection] = [] current_name: str | None = None current_body: list[SyntaxTreeNode] = [] @@ -319,6 +348,10 @@ def parse_readme(text: str) -> tuple[list[ParsedSection], list[ParsedSection]]: + """Parse README.md text into categories and resources. + + Returns (categories, resources) where each is a list of ParsedSection dicts. + """ md = MarkdownIt("commonmark") tokens = md.parse(text) root = SyntaxTreeNode(tokens) @@ -352,4 +385,4 @@ categories = _group_by_h2(cat_nodes) resources = _group_by_h2(res_nodes) - return categories, resources+ return categories, resources
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 ## heading text). SECTION_GROUPS: list[tuple[str, list[str]]] = [ ( "Web & API", [ "Web Frameworks", "RESTful API", "GraphQL", "WebSocket", "ASGI Servers", "WSGI Servers", "HTTP Clients", "Template Engine", "Web Asset Management", "Web Content Extracting", "Web Crawling", ], ), ( "Data & ML", [ "Data Analysis", "Data Validation", "Data Visualization", "Machine Learning", "Deep Learning", "Computer Vision", "Natural Language Processing", "Recommender Systems", "Science", "Quantum Computing", ], ), ( "DevOps & Infrastructure", [ "DevOps Tools", "Distributed Computing", "Task Queues", "Job Scheduler", "Serverless Frameworks", "Logging", "Processes", "Shell", "Network Virtualization", "RPC Servers", ], ), ( "Database & Storage", [ "Database", "Database Drivers", "ORM", "Caching", "Search", "Serialization", ], ), ( "Development Tools", [ "Testing", "Debugging Tools", "Code Analysis", "Build Tools", "Refactoring", "Documentation", "Editor Plugins and IDEs", "Interactive Interpreter", ], ), ( "CLI & GUI", [ "Command-line Interface Development", "Command-line Tools", "GUI Development", ], ), ( "Content & Media", [ "Audio", "Video", "Image Processing", "HTML Manipulation", "Text Processing", "Specific Formats Processing", "File Manipulation", "Downloader", ], ), ( "System & Runtime", [ "Asynchronous Programming", "Environment Management", "Package Management", "Package Repositories", "Distribution", "Implementations", "Built-in Classes Enhancement", "Functional Programming", "Configuration Files", ], ), ( "Security & Auth", [ "Authentication", "Cryptography", "Penetration Testing", "Permissions", ], ), ( "Specialized", [ "CMS", "Admin Panels", "Email", "Game Development", "Geolocation", "Hardware", "Internationalization", "Date and Time", "URL Manipulation", "Robotics", "Microsoft Windows", "Miscellaneous", "Algorithms and Design Patterns", "Static Site Generator", ], ), ("Resources", []), # Filled dynamically from parsed resources ] def group_categories( categories: list[dict], resources: list[dict], ) -> list[dict]: cat_by_name = {c["name"]: c for c in categories} groups = [] grouped_names: set[str] = set() for group_name, cat_names in SECTION_GROUPS: grouped_names.update(cat_names) if group_name == "Resources": group_cats = list(resources) else: group_cats = [cat_by_name[n] for n in cat_names if n in cat_by_name] if group_cats: groups.append( { "name": group_name, "slug": slugify(group_name), "categories": group_cats, } ) # Any categories not in a group go into "Other" ungrouped = [c for c in categories if c["name"] not in grouped_names] if ungrouped: groups.append( { "name": "Other", "slug": "other", "categories": ungrouped, } ) return groups class Entry(TypedDict): name: str url: str description: str category: str group: str stars: int | None owner: str | None last_commit_at: str | None class StarData(TypedDict): stars: int owner: str last_commit_at: str fetched_at: str GITHUB_REPO_URL_RE = re.compile(r"^https?://github\.com/([^/]+/[^/]+?)(?:\.git)?/?$") def extract_github_repo(url: str) -> str | None: m = GITHUB_REPO_URL_RE.match(url) return m.group(1) if m else None def load_stars(path: Path) -> dict[str, StarData]: if path.exists(): try: return json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError: return {} return {} def sort_entries(entries: list[dict]) -> list[dict]: def sort_key(entry: dict) -> tuple[int, int, str]: stars = entry["stars"] name = entry["name"].lower() if stars is None: return (1, 0, name) return (0, -stars, name) return sorted(entries, key=sort_key) def extract_entries( categories: list[dict], groups: list[dict], ) -> list[dict]: cat_to_group: dict[str, str] = {} for group in groups: for cat in group["categories"]: cat_to_group[cat["name"]] = group["name"] entries: list[dict] = [] for cat in categories: group_name = cat_to_group.get(cat["name"], "Other") for entry in cat["entries"]: entries.append( { "name": entry["name"], "url": entry["url"], "description": entry["description"], "category": cat["name"], "group": group_name, "stars": None, "owner": None, "last_commit_at": None, "also_see": entry["also_see"], } ) return entries def build(repo_root: str) -> None: repo = Path(repo_root) website = repo / "website" readme_text = (repo / "README.md").read_text(encoding="utf-8") subtitle = "" for line in readme_text.split("\n"): stripped = line.strip() if stripped and not stripped.startswith("#"): subtitle = stripped break categories, resources = parse_readme(readme_text) # All fields pre-computed: entry_count, content_html, preview, description total_entries = sum(c["entry_count"] for c in categories) groups = group_categories(categories, resources) entries = extract_entries(categories, groups) stars_data = load_stars(website / "data" / "github_stars.json") for entry in entries: repo_key = extract_github_repo(entry["url"]) if repo_key and repo_key in stars_data: sd = stars_data[repo_key] entry["stars"] = sd["stars"] entry["owner"] = sd["owner"] entry["last_commit_at"] = sd.get("last_commit_at", "") entries = sort_entries(entries) env = Environment( loader=FileSystemLoader(website / "templates"), autoescape=True, ) site_dir = website / "output" if site_dir.exists(): shutil.rmtree(site_dir) site_dir.mkdir(parents=True) tpl_index = env.get_template("index.html") (site_dir / "index.html").write_text( tpl_index.render( categories=categories, resources=resources, groups=groups, subtitle=subtitle, entries=entries, total_entries=total_entries, total_categories=len(categories), ), encoding="utf-8", ) static_src = website / "static" static_dst = site_dir / "static" if static_src.exists(): shutil.copytree(static_src, static_dst, dirs_exist_ok=True) shutil.copy(repo / "README.md", site_dir / "llms.txt") print(f"Built single page with {len(categories)} categories + {len(resources)} resources") print(f"Total entries: {total_entries}") print(f"Output: {site_dir}") if __name__ == "__main__": build(str(Path(__file__).parent.parent))
--- +++ @@ -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 groups.""" cat_by_name = {c["name"]: c for c in categories} groups = [] grouped_names: set[str] = set() @@ -209,11 +211,13 @@ def extract_github_repo(url: str) -> str | None: + """Extract owner/repo from a GitHub repo URL. Returns None for non-GitHub URLs.""" m = GITHUB_REPO_URL_RE.match(url) return m.group(1) if m else None def load_stars(path: Path) -> dict[str, StarData]: + """Load star data from JSON. Returns empty dict if file doesn't exist or is corrupt.""" if path.exists(): try: return json.loads(path.read_text(encoding="utf-8")) @@ -223,6 +227,7 @@ def sort_entries(entries: list[dict]) -> list[dict]: + """Sort entries by stars descending, then name ascending. No-star entries go last.""" def sort_key(entry: dict) -> tuple[int, int, str]: stars = entry["stars"] @@ -238,6 +243,7 @@ categories: list[dict], groups: list[dict], ) -> list[dict]: + """Flatten categories into individual library entries for table display.""" cat_to_group: dict[str, str] = {} for group in groups: for cat in group["categories"]: @@ -264,6 +270,7 @@ def build(repo_root: str) -> None: + """Main build: parse README, render single-page HTML via Jinja2 templates.""" repo = Path(repo_root) website = repo / "website" readme_text = (repo / "README.md").read_text(encoding="utf-8") @@ -330,4 +337,4 @@ if __name__ == "__main__": - build(str(Path(__file__).parent.parent))+ build(str(Path(__file__).parent.parent))
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_history = [0.0] * self.order # y[n-1] ... y[n-k] self.output_history = [0.0] * self.order def set_coefficients(self, a_coeffs: list[float], b_coeffs: list[float]) -> None: if len(a_coeffs) < self.order: a_coeffs = [1.0, *a_coeffs] if len(a_coeffs) != self.order + 1: msg = ( f"Expected a_coeffs to have {self.order + 1} elements " f"for {self.order}-order filter, got {len(a_coeffs)}" ) raise ValueError(msg) if len(b_coeffs) != self.order + 1: msg = ( f"Expected b_coeffs to have {self.order + 1} elements " f"for {self.order}-order filter, got {len(a_coeffs)}" ) raise ValueError(msg) self.a_coeffs = a_coeffs self.b_coeffs = b_coeffs def process(self, sample: float) -> float: result = 0.0 # Start at index 1 and do index 0 at the end. for i in range(1, self.order + 1): result += ( self.b_coeffs[i] * self.input_history[i - 1] - self.a_coeffs[i] * self.output_history[i - 1] ) result = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0] self.input_history[1:] = self.input_history[:-1] self.output_history[1:] = self.output_history[:-1] self.input_history[0] = sample self.output_history[0] = result return result
--- +++ @@ -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 function was made. + + Using the following transfer function + .. math:: H(z)=\frac{b_{0}+b_{1}z^{-1}+b_{2}z^{-2}+...+b_{k}z^{-k}} + {a_{0}+a_{1}z^{-1}+a_{2}z^{-2}+...+a_{k}z^{-k}} + + we can rewrite this to + .. math:: y[n]={\frac{1}{a_{0}}} + \left(\left(b_{0}x[n]+b_{1}x[n-1]+b_{2}x[n-2]+...+b_{k}x[n-k]\right)- + \left(a_{1}y[n-1]+a_{2}y[n-2]+...+a_{k}y[n-k]\right)\right) + """ def __init__(self, order: int) -> None: self.order = order @@ -17,6 +37,21 @@ self.output_history = [0.0] * self.order def set_coefficients(self, a_coeffs: list[float], b_coeffs: list[float]) -> None: + """ + Set the coefficients for the IIR filter. + These should both be of size `order` + 1. + :math:`a_0` may be left out, and it will use 1.0 as default value. + + This method works well with scipy's filter design functions + + >>> # Make a 2nd-order 1000Hz butterworth lowpass filter + >>> import scipy.signal + >>> b_coeffs, a_coeffs = scipy.signal.butter(2, 1000, + ... btype='lowpass', + ... fs=48000) + >>> filt = IIRFilter(2) + >>> filt.set_coefficients(a_coeffs, b_coeffs) + """ if len(a_coeffs) < self.order: a_coeffs = [1.0, *a_coeffs] @@ -38,6 +73,13 @@ self.b_coeffs = b_coeffs def process(self, sample: float) -> float: + """ + Calculate :math:`y[n]` + + >>> filt = IIRFilter(2) + >>> filt.process(0) + 0.0 + """ result = 0.0 # Start at index 1 and do index 0 at the end. @@ -55,4 +97,4 @@ self.input_history[0] = sample self.output_history[0] = result - return result+ return result
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 so, and recurse. backtrack(partial + "(", open_count + 1, close_count, n, result) if close_count < open_count: # If we can add a close parenthesis (it won't make the combination invalid), # do so, and recurse. backtrack(partial + ")", open_count, close_count + 1, n, result) def generate_parenthesis(n: int) -> list[str]: result: list[str] = [] backtrack("", 0, 0, n, result) return result if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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, open_count: int, close_count: int, n: int, result: list[str] ) -> None: + """ + Generate valid combinations of balanced parentheses using recursion. + + :param partial: A string representing the current combination. + :param open_count: An integer representing the count of open parentheses. + :param close_count: An integer representing the count of close parentheses. + :param n: An integer representing the total number of pairs. + :param result: A list to store valid combinations. + :return: None + + This function uses recursion to explore all possible combinations, + ensuring that at each step, the parentheses remain balanced. + + Example: + >>> result = [] + >>> backtrack("", 0, 0, 2, result) + >>> result + ['(())', '()()'] + """ if len(partial) == 2 * n: # When the combination is complete, add it to the result. result.append(partial) @@ -19,6 +46,29 @@ def generate_parenthesis(n: int) -> list[str]: + """ + Generate valid combinations of balanced parentheses for a given n. + + :param n: An integer representing the number of pairs of parentheses. + :return: A list of strings with valid combinations. + + This function uses a recursive approach to generate the combinations. + + Time Complexity: O(2^(2n)) - In the worst case, we have 2^(2n) combinations. + Space Complexity: O(n) - where 'n' is the number of pairs. + + Example 1: + >>> generate_parenthesis(3) + ['((()))', '(()())', '(())()', '()(())', '()()()'] + + Example 2: + >>> generate_parenthesis(1) + ['()'] + + Example 3: + >>> generate_parenthesis(0) + [''] + """ result: list[str] = [] backtrack("", 0, 0, n, result) @@ -28,4 +78,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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_sum, solutions_count i_to_n = current_number**power if current_sum + i_to_n <= needed_sum: # If the sum of the powers is less than needed_sum, then continue adding powers. current_sum += i_to_n current_sum, solutions_count = backtrack( needed_sum, power, current_number + 1, current_sum, solutions_count ) current_sum -= i_to_n if i_to_n < needed_sum: # If the power of i is less than needed_sum, then try with the next power. current_sum, solutions_count = backtrack( needed_sum, power, current_number + 1, current_sum, solutions_count ) return current_sum, solutions_count def solve(needed_sum: int, power: int) -> int: if not (1 <= needed_sum <= 1000 and 2 <= power <= 10): raise ValueError( "Invalid input\n" "needed_sum must be between 1 and 1000, power between 2 and 10." ) return backtrack(needed_sum, power, 1, 0, 0)[1] # Return the solutions_count if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 up to 13. +The only solution is 2^2+3^2. Constraints: 1<=X<=1000, 2<=N<=10. +""" def backtrack( @@ -7,6 +14,22 @@ current_sum: int, solutions_count: int, ) -> tuple[int, int]: + """ + >>> backtrack(13, 2, 1, 0, 0) + (0, 1) + >>> backtrack(10, 2, 1, 0, 0) + (0, 1) + >>> backtrack(10, 3, 1, 0, 0) + (0, 0) + >>> backtrack(20, 2, 1, 0, 0) + (0, 1) + >>> backtrack(15, 10, 1, 0, 0) + (0, 0) + >>> backtrack(16, 2, 1, 0, 0) + (0, 1) + >>> backtrack(20, 1, 1, 0, 0) + (0, 64) + """ if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solutions_count += 1 @@ -29,6 +52,30 @@ def solve(needed_sum: int, power: int) -> int: + """ + >>> solve(13, 2) + 1 + >>> solve(10, 2) + 1 + >>> solve(10, 3) + 0 + >>> solve(20, 2) + 1 + >>> solve(15, 10) + 0 + >>> solve(16, 2) + 1 + >>> solve(20, 1) + Traceback (most recent call last): + ... + ValueError: Invalid input + needed_sum must be between 1 and 1000, power between 2 and 10. + >>> solve(-10, 5) + Traceback (most recent call last): + ... + ValueError: Invalid input + needed_sum must be between 1 and 1000, power between 2 and 10. + """ if not (1 <= needed_sum <= 1000 and 2 <= power <= 10): raise ValueError( "Invalid input\n" @@ -41,4 +88,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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): print(current_subsequence) return create_state_space_tree(sequence, current_subsequence, index + 1) current_subsequence.append(sequence[index]) create_state_space_tree(sequence, current_subsequence, index + 1) current_subsequence.pop() if __name__ == "__main__": seq: list[Any] = [1, 2, 3] generate_all_subsequences(seq) seq.clear() seq.extend(["A", "B", "C"]) generate_all_subsequences(seq)
--- +++ @@ -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_space_tree( sequence: list[Any], current_subsequence: list[Any], index: int ) -> None: + """ + Creates a state space tree to iterate through each branch using DFS. + We know that each state has exactly two children. + It terminates when it reaches the end of the given sequence. + + :param sequence: The input sequence for which subsequences are generated. + :param current_subsequence: The current subsequence being built. + :param index: The current index in the sequence. + + Example: + >>> sequence = [3, 2, 1] + >>> current_subsequence = [] + >>> create_state_space_tree(sequence, current_subsequence, 0) + [] + [1] + [2] + [2, 1] + [3] + [3, 1] + [3, 2] + [3, 2, 1] + + >>> sequence = ["A", "B"] + >>> current_subsequence = [] + >>> create_state_space_tree(sequence, current_subsequence, 0) + [] + ['B'] + ['A'] + ['A', 'B'] + + >>> sequence = [] + >>> current_subsequence = [] + >>> create_state_space_tree(sequence, current_subsequence, 0) + [] + + >>> sequence = [1, 2, 3, 4] + >>> current_subsequence = [] + >>> create_state_space_tree(sequence, current_subsequence, 0) + [] + [4] + [3] + [3, 4] + [2] + [2, 4] + [2, 3] + [2, 3, 4] + [1] + [1, 4] + [1, 3] + [1, 3, 4] + [1, 2] + [1, 2, 4] + [1, 2, 3] + [1, 2, 3, 4] + """ if index == len(sequence): print(current_subsequence) @@ -28,4 +90,4 @@ seq.clear() seq.extend(["A", "B", "C"]) - generate_all_subsequences(seq)+ generate_all_subsequences(seq)
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 i, j in zip(range(row), [column] * row)) and all( board[i][j] != 1 for i, j in zip(range(row - 1, -1, -1), range(column - 1, -1, -1)) ) and all( board[i][j] != 1 for i, j in zip(range(row - 1, -1, -1), range(column + 1, n)) ) ) def solve(board: list[list[int]], row: int) -> bool: if row >= len(board): """ If the row number exceeds N, we have a board with a successful combination and that combination is appended to the solution list and the board is printed. """ solution.append(board) printboard(board) print() return True for i in range(len(board)): """ For every row, it iterates through each column to check if it is feasible to place a queen there. If all the combinations for that particular branch are successful, the board is reinitialized for the next possible combination. """ if is_safe(board, row, i): board[row][i] = 1 solve(board, row + 1) board[row][i] = 0 return False def printboard(board: list[list[int]]) -> None: for i in range(len(board)): for j in range(len(board)): if board[i][j] == 1: print("Q", end=" ") # Queen is present else: print(".", end=" ") # Empty cell print() # Number of queens (e.g., n=8 for an 8x8 board) n = 8 board = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print("The total number of solutions are:", len(solution))
--- +++ @@ -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 annotations @@ -5,6 +14,34 @@ def is_safe(board: list[list[int]], row: int, column: int) -> bool: + """ + This function returns a boolean value True if it is safe to place a queen there + considering the current state of the board. + + Parameters: + board (2D matrix): The chessboard + row, column: Coordinates of the cell on the board + + Returns: + Boolean Value + + >>> is_safe([[0, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 1) + True + >>> is_safe([[0, 1, 0], [0, 0, 0], [0, 0, 0]], 1, 1) + False + >>> is_safe([[1, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 1) + False + >>> is_safe([[0, 0, 1], [0, 0, 0], [0, 0, 0]], 1, 1) + False + >>> is_safe([[1, 0, 0], [0, 0, 0], [0, 0, 0]], 1, 2) + True + >>> is_safe([[1, 0, 0], [0, 0, 0], [0, 0, 0]], 2, 1) + True + >>> is_safe([[0, 0, 0], [1, 0, 0], [0, 0, 0]], 0, 2) + True + >>> is_safe([[0, 0, 0], [1, 0, 0], [0, 0, 0]], 2, 2) + True + """ n = len(board) # Size of the board @@ -24,6 +61,11 @@ def solve(board: list[list[int]], row: int) -> bool: + """ + This function creates a state space tree and calls the safe function until it + receives a False Boolean and terminates that branch and backtracks to the next + possible solution branch. + """ if row >= len(board): """ If the row number exceeds N, we have a board with a successful combination @@ -48,6 +90,9 @@ def printboard(board: list[list[int]]) -> None: + """ + Prints the boards that have a successful combination. + """ for i in range(len(board)): for j in range(len(board)): if board[i][j] == 1: @@ -61,4 +106,4 @@ n = 8 board = [[0 for i in range(n)] for j in range(n)] solve(board, 0) -print("The total number of solutions are:", len(solution))+print("The total number of solutions are:", len(solution))
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 make_lowpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = (1 - _cos) / 2 b1 = 1 - _cos a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b0]) return filt def make_highpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = (1 + _cos) / 2 b1 = -1 - _cos a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b0]) return filt def make_bandpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = _sin / 2 b1 = 0 b2 = -b0 a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_allpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = 1 - alpha b1 = -2 * _cos b2 = 1 + alpha filt = IIRFilter(2) filt.set_coefficients([b2, b1, b0], [b0, b1, b2]) return filt def make_peak( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) b0 = 1 + alpha * big_a b1 = -2 * _cos b2 = 1 - alpha * big_a a0 = 1 + alpha / big_a a1 = -2 * _cos a2 = 1 - alpha / big_a filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_lowshelf( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) pmc = (big_a + 1) - (big_a - 1) * _cos ppmc = (big_a + 1) + (big_a - 1) * _cos mpc = (big_a - 1) - (big_a + 1) * _cos pmpc = (big_a - 1) + (big_a + 1) * _cos aa2 = 2 * sqrt(big_a) * alpha b0 = big_a * (pmc + aa2) b1 = 2 * big_a * mpc b2 = big_a * (pmc - aa2) a0 = ppmc + aa2 a1 = -2 * pmpc a2 = ppmc - aa2 filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_highshelf( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) pmc = (big_a + 1) - (big_a - 1) * _cos ppmc = (big_a + 1) + (big_a - 1) * _cos mpc = (big_a - 1) - (big_a + 1) * _cos pmpc = (big_a - 1) + (big_a + 1) * _cos aa2 = 2 * sqrt(big_a) * alpha b0 = big_a * (ppmc + aa2) b1 = -2 * big_a * pmpc b2 = big_a * (ppmc - aa2) a0 = pmc + aa2 a1 = 2 * mpc a2 = pmc - aa2 filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt
--- +++ @@ -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.9077040443587427, 0.004277569313094809, + 0.008555138626189618, 0.004277569313094809] + """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) @@ -37,6 +45,14 @@ samplerate: int, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: + """ + Creates a high-pass filter + + >>> filter = make_highpass(1000, 48000) + >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE + [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.9957224306869052, + -1.9914448613738105, 0.9957224306869052] + """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) @@ -59,6 +75,14 @@ samplerate: int, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: + """ + Creates a band-pass filter + + >>> filter = make_bandpass(1000, 48000) + >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE + [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.06526309611002579, + 0, -0.06526309611002579] + """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) @@ -82,6 +106,14 @@ samplerate: int, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: + """ + Creates an all-pass filter + + >>> filter = make_allpass(1000, 48000) + >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE + [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.9077040443587427, + -1.9828897227476208, 1.0922959556412573] + """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) @@ -102,6 +134,14 @@ gain_db: float, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: + """ + Creates a peak filter + + >>> filter = make_peak(1000, 48000, 6) + >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE + [1.0653405327119334, -1.9828897227476208, 0.9346594672880666, 1.1303715025601122, + -1.9828897227476208, 0.8696284974398878] + """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) @@ -126,6 +166,14 @@ gain_db: float, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: + """ + Creates a low-shelf filter + + >>> filter = make_lowshelf(1000, 48000, 6) + >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE + [3.0409336710888786, -5.608870992220748, 2.602157875636628, 3.139954022810743, + -5.591841778072785, 2.5201667380627257] + """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) @@ -155,6 +203,14 @@ gain_db: float, q_factor: float = 1 / sqrt(2), ) -> IIRFilter: + """ + Creates a high-shelf filter + + >>> filter = make_highshelf(1000, 48000, 6) + >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE + [2.2229172136088806, -3.9587208137297303, 1.7841414181566304, 4.295432981120543, + -7.922740859457287, 3.6756456963725253] + """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) @@ -175,4 +231,4 @@ filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) - return filt+ return filt
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: list[int], ) -> None: if index == len(sequence): print(current_sequence) return for i in range(len(sequence)): if not index_used[i]: current_sequence.append(sequence[i]) index_used[i] = True create_state_space_tree(sequence, current_sequence, index + 1, index_used) current_sequence.pop() index_used[i] = False """ remove the comment to take an input from the user print("Enter the elements") sequence = list(map(int, input().split())) """ sequence: list[int | str] = [3, 1, 2, 4] generate_all_permutations(sequence) sequence_2: list[int | str] = ["A", "B", "C"] generate_all_permutations(sequence_2)
--- +++ @@ -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: int, index_used: list[int], ) -> None: + """ + Creates a state space tree to iterate through each branch using DFS. + We know that each state has exactly len(sequence) - index children. + It terminates when it reaches the end of the given sequence. + + :param sequence: The input sequence for which permutations are generated. + :param current_sequence: The current permutation being built. + :param index: The current index in the sequence. + :param index_used: list to track which elements are used in permutation. + + Example 1: + >>> sequence = [1, 2, 3] + >>> current_sequence = [] + >>> index_used = [False, False, False] + >>> create_state_space_tree(sequence, current_sequence, 0, index_used) + [1, 2, 3] + [1, 3, 2] + [2, 1, 3] + [2, 3, 1] + [3, 1, 2] + [3, 2, 1] + + Example 2: + >>> sequence = ["A", "B", "C"] + >>> current_sequence = [] + >>> index_used = [False, False, False] + >>> create_state_space_tree(sequence, current_sequence, 0, index_used) + ['A', 'B', 'C'] + ['A', 'C', 'B'] + ['B', 'A', 'C'] + ['B', 'C', 'A'] + ['C', 'A', 'B'] + ['C', 'B', 'A'] + + Example 3: + >>> sequence = [1] + >>> current_sequence = [] + >>> index_used = [False] + >>> create_state_space_tree(sequence, current_sequence, 0, index_used) + [1] + """ if index == len(sequence): print(current_sequence) @@ -37,4 +85,4 @@ generate_all_permutations(sequence) sequence_2: list[int | str] = ["A", "B", "C"] -generate_all_permutations(sequence_2)+generate_all_permutations(sequence_2)
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(len(current_word)): for c in string.ascii_lowercase: # Try changing each letter transformed_word = current_word[:i] + c + current_word[i + 1 :] if transformed_word in word_set: word_set.remove(transformed_word) # Recur with the new word added to the path result = backtrack( transformed_word, [*path, transformed_word], end_word, word_set ) if result: # valid transformation found return result word_set.add(transformed_word) # backtrack return [] # No valid transformation found def word_ladder(begin_word: str, end_word: str, word_set: set[str]) -> list[str]: if end_word not in word_set: # no valid transformation possible return [] # Perform backtracking starting from the begin_word return backtrack(begin_word, [begin_word], end_word, word_set)
--- +++ @@ -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 to the end word. + +Wikipedia: https://en.wikipedia.org/wiki/Word_ladder +""" import string @@ -5,6 +15,34 @@ def backtrack( current_word: str, path: list[str], end_word: str, word_set: set[str] ) -> list[str]: + """ + Helper function to perform backtracking to find the transformation + from the current_word to the end_word. + + Parameters: + current_word (str): The current word in the transformation sequence. + path (list[str]): The list of transformations from begin_word to current_word. + end_word (str): The target word for transformation. + word_set (set[str]): The set of valid words for transformation. + + Returns: + list[str]: The list of transformations from begin_word to end_word. + Returns an empty list if there is no valid + transformation from current_word to end_word. + + Example: + >>> backtrack("hit", ["hit"], "cog", {"hot", "dot", "dog", "lot", "log", "cog"}) + ['hit', 'hot', 'dot', 'lot', 'log', 'cog'] + + >>> backtrack("hit", ["hit"], "cog", {"hot", "dot", "dog", "lot", "log"}) + [] + + >>> backtrack("lead", ["lead"], "gold", {"load", "goad", "gold", "lead", "lord"}) + ['lead', 'lead', 'load', 'goad', 'gold'] + + >>> backtrack("game", ["game"], "code", {"came", "cage", "code", "cade", "gave"}) + ['game', 'came', 'cade', 'code'] + """ # Base case: If the current word is the end word, return the path if current_word == end_word: @@ -28,9 +66,35 @@ def word_ladder(begin_word: str, end_word: str, word_set: set[str]) -> list[str]: + """ + Solve the Word Ladder problem using Backtracking and return + the list of transformations from begin_word to end_word. + + Parameters: + begin_word (str): The word from which the transformation starts. + end_word (str): The target word for transformation. + word_list (list[str]): The list of valid words for transformation. + + Returns: + list[str]: The list of transformations from begin_word to end_word. + Returns an empty list if there is no valid transformation. + + Example: + >>> word_ladder("hit", "cog", ["hot", "dot", "dog", "lot", "log", "cog"]) + ['hit', 'hot', 'dot', 'lot', 'log', 'cog'] + + >>> word_ladder("hit", "cog", ["hot", "dot", "dog", "lot", "log"]) + [] + + >>> word_ladder("lead", "gold", ["load", "goad", "gold", "lead", "lord"]) + ['lead', 'lead', 'load', 'goad', 'gold'] + + >>> word_ladder("game", "code", ["came", "cage", "code", "cade", "gave"]) + ['game', 'came', 'cade', 'code'] + """ if end_word not in word_set: # no valid transformation possible return [] # Perform backtracking starting from the begin_word - return backtrack(begin_word, [begin_word], end_word, word_set)+ return backtrack(begin_word, [begin_word], end_word, word_set)
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 negative") if n < 0: raise ValueError("n must not be negative") result: list[list[int]] = [] create_all_state(1, n, k, [], result) return result def create_all_state( increment: int, total_number: int, level: int, current_list: list[int], total_list: list[list[int]], ) -> None: if level == 0: total_list.append(current_list[:]) return for i in range(increment, total_number - level + 2): current_list.append(i) create_all_state(i + 1, total_number, level - 1, current_list, total_list) current_list.pop() if __name__ == "__main__": from doctest import testmod testmod() print(generate_all_combinations(n=4, k=2)) tests = ((n, k) for n in range(1, 5) for k in range(1, 5)) for n, k in tests: print(n, k, generate_all_combinations(n, k) == combination_lists(n, k)) print("Benchmark:") from timeit import timeit for func in ("combination_lists", "generate_all_combinations"): print(f"{func:>25}(): {timeit(f'{func}(n=4, k = 2)', globals=globals())}")
--- +++ @@ -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 combination_lists(n: int, k: int) -> list[list[int]]: + """ + Generates all possible combinations of k numbers out of 1 ... n using itertools. + + >>> combination_lists(n=4, k=2) + [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] + """ return [list(x) for x in combinations(range(1, n + 1), k)] def generate_all_combinations(n: int, k: int) -> list[list[int]]: + """ + Generates all possible combinations of k numbers out of 1 ... n using backtracking. + + >>> generate_all_combinations(n=4, k=2) + [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] + >>> generate_all_combinations(n=0, k=0) + [[]] + >>> generate_all_combinations(n=10, k=-1) + Traceback (most recent call last): + ... + ValueError: k must not be negative + >>> generate_all_combinations(n=-1, k=10) + Traceback (most recent call last): + ... + ValueError: n must not be negative + >>> generate_all_combinations(n=5, k=4) + [[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]] + >>> generate_all_combinations(n=3, k=3) + [[1, 2, 3]] + >>> generate_all_combinations(n=3, k=1) + [[1], [2], [3]] + >>> generate_all_combinations(n=1, k=0) + [[]] + >>> generate_all_combinations(n=1, k=1) + [[1]] + >>> from itertools import combinations + >>> all(generate_all_combinations(n, k) == combination_lists(n, k) + ... for n in range(1, 6) for k in range(1, 6)) + True + """ if k < 0: raise ValueError("k must not be negative") if n < 0: @@ -26,6 +68,28 @@ current_list: list[int], total_list: list[list[int]], ) -> None: + """ + Helper function to recursively build all combinations. + + >>> create_all_state(1, 4, 2, [], result := []) + >>> result + [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] + >>> create_all_state(1, 3, 3, [], result := []) + >>> result + [[1, 2, 3]] + >>> create_all_state(2, 2, 1, [1], result := []) + >>> result + [[1, 2]] + >>> create_all_state(1, 0, 0, [], result := []) + >>> result + [[]] + >>> create_all_state(1, 4, 0, [1, 2], result := []) + >>> result + [[1, 2]] + >>> create_all_state(5, 4, 2, [1, 2], result := []) + >>> result + [] + """ if level == 0: total_list.append(current_list[:]) return @@ -49,4 +113,4 @@ from timeit import timeit for func in ("combination_lists", "generate_all_combinations"): - print(f"{func:>25}(): {timeit(f'{func}(n=4, k = 2)', globals=globals())}")+ print(f"{func:>25}(): {timeit(f'{func}(n=4, k = 2)', globals=globals())}")
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 not any(vertex == next_ver for vertex in path) def util_hamilton_cycle(graph: list[list[int]], path: list[int], curr_ind: int) -> bool: # Base Case if curr_ind == len(graph): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(len(graph)): if valid_connection(graph, next_ver, curr_ind, path): # Insert current vertex into path as next transition path[curr_ind] = next_ver # Validate created path if util_hamilton_cycle(graph, path, curr_ind + 1): return True # Backtrack path[curr_ind] = -1 return False def hamilton_cycle(graph: list[list[int]], start_index: int = 0) -> list[int]: # Initialize path with -1, indicating that we have not visited them yet path = [-1] * (len(graph) + 1) # initialize start and end of path with starting index path[0] = path[-1] = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(graph, path, 1) else []
--- +++ @@ -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 +""" def valid_connection( graph: list[list[int]], next_ver: int, curr_ind: int, path: list[int] ) -> bool: + """ + Checks whether it is possible to add next into path by validating 2 statements + 1. There should be path between current and next vertex + 2. Next vertex should not be in path + If both validations succeed we return True, saying that it is possible to connect + this vertices, otherwise we return False + + Case 1:Use exact graph as in main function, with initialized values + >>> graph = [[0, 1, 0, 1, 0], + ... [1, 0, 1, 1, 1], + ... [0, 1, 0, 0, 1], + ... [1, 1, 0, 0, 1], + ... [0, 1, 1, 1, 0]] + >>> path = [0, -1, -1, -1, -1, 0] + >>> curr_ind = 1 + >>> next_ver = 1 + >>> valid_connection(graph, next_ver, curr_ind, path) + True + + Case 2: Same graph, but trying to connect to node that is already in path + >>> path = [0, 1, 2, 4, -1, 0] + >>> curr_ind = 4 + >>> next_ver = 1 + >>> valid_connection(graph, next_ver, curr_ind, path) + False + """ # 1. Validate that path exists between current and next vertices if graph[path[curr_ind - 1]][next_ver] == 0: @@ -13,6 +47,47 @@ def util_hamilton_cycle(graph: list[list[int]], path: list[int], curr_ind: int) -> bool: + """ + Pseudo-Code + Base Case: + 1. Check if we visited all of vertices + 1.1 If last visited vertex has path to starting vertex return True either + return False + Recursive Step: + 2. Iterate over each vertex + Check if next vertex is valid for transiting from current vertex + 2.1 Remember next vertex as next transition + 2.2 Do recursive call and check if going to this vertex solves problem + 2.3 If next vertex leads to solution return True + 2.4 Else backtrack, delete remembered vertex + + Case 1: Use exact graph as in main function, with initialized values + >>> graph = [[0, 1, 0, 1, 0], + ... [1, 0, 1, 1, 1], + ... [0, 1, 0, 0, 1], + ... [1, 1, 0, 0, 1], + ... [0, 1, 1, 1, 0]] + >>> path = [0, -1, -1, -1, -1, 0] + >>> curr_ind = 1 + >>> util_hamilton_cycle(graph, path, curr_ind) + True + >>> path + [0, 1, 2, 4, 3, 0] + + Case 2: Use exact graph as in previous case, but in the properties taken from + middle of calculation + >>> graph = [[0, 1, 0, 1, 0], + ... [1, 0, 1, 1, 1], + ... [0, 1, 0, 0, 1], + ... [1, 1, 0, 0, 1], + ... [0, 1, 1, 1, 0]] + >>> path = [0, 1, 2, -1, -1, 0] + >>> curr_ind = 3 + >>> util_hamilton_cycle(graph, path, curr_ind) + True + >>> path + [0, 1, 2, 4, 3, 0] + """ # Base Case if curr_ind == len(graph): @@ -33,10 +108,69 @@ def hamilton_cycle(graph: list[list[int]], start_index: int = 0) -> list[int]: + r""" + Wrapper function to call subroutine called util_hamilton_cycle, + which will either return array of vertices indicating hamiltonian cycle + or an empty list indicating that hamiltonian cycle was not found. + Case 1: + Following graph consists of 5 edges. + If we look closely, we can see that there are multiple Hamiltonian cycles. + For example one result is when we iterate like: + (0)->(1)->(2)->(4)->(3)->(0) + + (0)---(1)---(2) + | / \ | + | / \ | + | / \ | + |/ \| + (3)---------(4) + >>> graph = [[0, 1, 0, 1, 0], + ... [1, 0, 1, 1, 1], + ... [0, 1, 0, 0, 1], + ... [1, 1, 0, 0, 1], + ... [0, 1, 1, 1, 0]] + >>> hamilton_cycle(graph) + [0, 1, 2, 4, 3, 0] + + Case 2: + Same Graph as it was in Case 1, changed starting index from default to 3 + + (0)---(1)---(2) + | / \ | + | / \ | + | / \ | + |/ \| + (3)---------(4) + >>> graph = [[0, 1, 0, 1, 0], + ... [1, 0, 1, 1, 1], + ... [0, 1, 0, 0, 1], + ... [1, 1, 0, 0, 1], + ... [0, 1, 1, 1, 0]] + >>> hamilton_cycle(graph, 3) + [3, 0, 1, 2, 4, 3] + + Case 3: + Following Graph is exactly what it was before, but edge 3-4 is removed. + Result is that there is no Hamiltonian Cycle anymore. + + (0)---(1)---(2) + | / \ | + | / \ | + | / \ | + |/ \| + (3) (4) + >>> graph = [[0, 1, 0, 1, 0], + ... [1, 0, 1, 1, 1], + ... [0, 1, 0, 0, 1], + ... [1, 1, 0, 0, 0], + ... [0, 1, 1, 0, 0]] + >>> hamilton_cycle(graph,4) + [] + """ # Initialize path with -1, indicating that we have not visited them yet path = [-1] * (len(graph) + 1) # initialize start and end of path with starting index path[0] = path[-1] = start_index # evaluate and if we find answer return path either return empty array - return path if util_hamilton_cycle(graph, path, 1) else []+ return path if util_hamilton_cycle(graph, path, 1) else []
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 case: If the current depth equals the height of the tree, # return the score of the current node. if depth == height: return scores[node_index] # If it's the maximizer's turn, choose the maximum score # between the two possible moves. if is_max: return max( minimax(depth + 1, node_index * 2, False, scores, height), minimax(depth + 1, node_index * 2 + 1, False, scores, height), ) # If it's the minimizer's turn, choose the minimum score # between the two possible moves. return min( minimax(depth + 1, node_index * 2, True, scores, height), minimax(depth + 1, node_index * 2 + 1, True, scores, height), ) def main() -> None: # Sample scores and height calculation scores = [90, 23, 6, 33, 21, 65, 123, 34423] height = math.log(len(scores), 2) # Calculate and print the optimal value using the minimax algorithm print("Optimal value : ", end="") print(minimax(0, 0, True, scores, height)) if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -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 Game tree +""" from __future__ import annotations @@ -7,6 +16,41 @@ def minimax( depth: int, node_index: int, is_max: bool, scores: list[int], height: float ) -> int: + """ + This function implements the minimax algorithm, which helps achieve the optimal + score for a player in a two-player game by checking all possible moves. + If the player is the maximizer, then the score is maximized. + If the player is the minimizer, then the score is minimized. + + Parameters: + - depth: Current depth in the game tree. + - node_index: Index of the current node in the scores list. + - is_max: A boolean indicating whether the current move + is for the maximizer (True) or minimizer (False). + - scores: A list containing the scores of the leaves of the game tree. + - height: The maximum height of the game tree. + + Returns: + - An integer representing the optimal score for the current player. + + >>> import math + >>> scores = [90, 23, 6, 33, 21, 65, 123, 34423] + >>> height = math.log(len(scores), 2) + >>> minimax(0, 0, True, scores, height) + 65 + >>> minimax(-1, 0, True, scores, height) + Traceback (most recent call last): + ... + ValueError: Depth cannot be less than 0 + >>> minimax(0, 0, True, [], 2) + Traceback (most recent call last): + ... + ValueError: Scores cannot be empty + >>> scores = [3, 5, 2, 9, 12, 5, 23, 23] + >>> height = math.log(len(scores), 2) + >>> minimax(0, 0, True, scores, height) + 12 + """ if depth < 0: raise ValueError("Depth cannot be less than 0") @@ -48,4 +92,4 @@ import doctest doctest.testmod() - main()+ main()
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 = len(possible_board) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append([". " * i + "Q " + ". " * (n - 1 - i) for i in possible_board]) return # We iterate each column in the row to find all possible results in each row for col in range(n): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col], [*diagonal_right_collisions, row - col], [*diagonal_left_collisions, row + col], boards, n, ) def n_queens_solution(n: int) -> None: boards: list[list[str]] = [] depth_first_search([], [], [], boards, n) # Print all the boards for board in boards: for column in board: print(column) print("") print(len(boards), "solutions were found.") if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
--- +++ @@ -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 problem we will use simple math. First we know the queen can move in all +the possible ways, we can simplify it in this: vertical, horizontal, diagonal left and + diagonal right. + +We can visualize it like this: + +left diagonal = \ +right diagonal = / + +On a chessboard vertical movement could be the rows and horizontal movement could be +the columns. + +In programming we can use an array, and in this array each index could be the rows and +each value in the array could be the column. For example: + + . Q . . We have this chessboard with one queen in each column and each queen + . . . Q can't attack to each other. + Q . . . The array for this example would look like this: [1, 3, 0, 2] + . . Q . + +So if we use an array and we verify that each value in the array is different to each +other we know that at least the queens can't attack each other in horizontal and +vertical. + +At this point we have it halfway completed and we will treat the chessboard as a +Cartesian plane. Hereinafter we are going to remember basic math, so in the school we +learned this formula: + + Slope of a line: + + y2 - y1 + m = ---------- + x2 - x1 + +This formula allow us to get the slope. For the angles 45º (right diagonal) and 135º +(left diagonal) this formula gives us m = 1, and m = -1 respectively. + +See:: +https://www.enotes.com/homework-help/write-equation-line-that-hits-origin-45-degree-1474860 + +Then we have this other formula: + +Slope intercept: + +y = mx + b + +b is where the line crosses the Y axis (to get more information see: +https://www.mathsisfun.com/y_intercept.html), if we change the formula to solve for b +we would have: + +y - mx = b + +And since we already have the m values for the angles 45º and 135º, this formula would +look like this: + +45º: y - (1)x = b +45º: y - x = b + +135º: y - (-1)x = b +135º: y + x = b + +y = row +x = column + +Applying these two formulas we can check if a queen in some position is being attacked +for another one or vice versa. + +""" from __future__ import annotations @@ -9,6 +86,14 @@ boards: list[list[str]], n: int, ) -> None: + """ + >>> boards = [] + >>> depth_first_search([], [], [], boards, 4) + >>> for board in boards: + ... print(board) + ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] + ['. . Q . ', 'Q . . . ', '. . . Q ', '. Q . . '] + """ # Get next row in the current board (possible_board) to fill it with a queen row = len(possible_board) @@ -70,4 +155,4 @@ import doctest doctest.testmod() - n_queens_solution(4)+ n_queens_solution(4)
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 <= size - 1 and 0 <= source_column <= size - 1) or ( not (0 <= destination_row <= size - 1 and 0 <= destination_column <= size - 1) ): raise ValueError("Invalid source or destination coordinates") # We need to create solution object to save path. solutions = [[1 for _ in range(size)] for _ in range(size)] solved = run_maze( maze, source_row, source_column, destination_row, destination_column, solutions ) if solved: return solutions else: raise ValueError("No solution exists!") def run_maze( maze: list[list[int]], i: int, j: int, destination_row: int, destination_column: int, solutions: list[list[int]], ) -> bool: size = len(maze) # Final check point. if i == destination_row and j == destination_column and maze[i][j] == 0: solutions[i][j] = 0 return True lower_flag = (not i < 0) and (not j < 0) # Check lower bounds upper_flag = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. block_flag = (solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited solutions[i][j] = 0 # check for directions if ( run_maze(maze, i + 1, j, destination_row, destination_column, solutions) or run_maze( maze, i, j + 1, destination_row, destination_column, solutions ) or run_maze( maze, i - 1, j, destination_row, destination_column, solutions ) or run_maze( maze, i, j - 1, destination_row, destination_column, solutions ) ): return True solutions[i][j] = 1 return False return False if __name__ == "__main__": import doctest doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
--- +++ @@ -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. + - source_column: The column index of the starting point. + - destination_row: The row index of the destination point. + - destination_column: The column index of the destination point. + Returns: + - solution: A 2D matrix representing the solution path if it exists. + Raises: + - ValueError: If no solution exists or if the source or + destination coordinates are invalid. + Description: + This method navigates through a maze represented as an n by n matrix, + starting from a specified source cell and + aiming to reach a destination cell. + The maze consists of walls (1s) and open paths (0s). + By providing custom row and column values, the source and destination + cells can be adjusted. + >>> maze = [[0, 1, 0, 1, 1], + ... [0, 0, 0, 0, 0], + ... [1, 0, 1, 0, 1], + ... [0, 0, 1, 0, 0], + ... [1, 0, 0, 1, 0]] + >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE + [[0, 1, 1, 1, 1], + [0, 0, 0, 0, 1], + [1, 1, 1, 0, 1], + [1, 1, 1, 0, 0], + [1, 1, 1, 1, 0]] + + Note: + In the output maze, the zeros (0s) represent one of the possible + paths from the source to the destination. + + >>> maze = [[0, 1, 0, 1, 1], + ... [0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 1], + ... [0, 0, 0, 0, 0], + ... [0, 0, 0, 0, 0]] + >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE + [[0, 1, 1, 1, 1], + [0, 1, 1, 1, 1], + [0, 1, 1, 1, 1], + [0, 1, 1, 1, 1], + [0, 0, 0, 0, 0]] + + >>> maze = [[0, 0, 0], + ... [0, 1, 0], + ... [1, 0, 0]] + >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE + [[0, 0, 0], + [1, 1, 0], + [1, 1, 0]] + + >>> maze = [[1, 0, 0], + ... [0, 1, 0], + ... [1, 0, 0]] + >>> solve_maze(maze,0,1,len(maze)-1,len(maze)-1) # doctest: +NORMALIZE_WHITESPACE + [[1, 0, 0], + [1, 1, 0], + [1, 1, 0]] + + >>> maze = [[1, 1, 0, 0, 1, 0, 0, 1], + ... [1, 0, 1, 0, 0, 1, 1, 1], + ... [0, 1, 0, 1, 0, 0, 1, 0], + ... [1, 1, 1, 0, 0, 1, 0, 1], + ... [0, 1, 0, 0, 1, 0, 1, 1], + ... [0, 0, 0, 1, 1, 1, 0, 1], + ... [0, 1, 0, 1, 0, 1, 1, 1], + ... [1, 1, 0, 0, 0, 0, 0, 1]] + >>> solve_maze(maze,0,2,len(maze)-1,2) # doctest: +NORMALIZE_WHITESPACE + [[1, 1, 0, 0, 1, 1, 1, 1], + [1, 1, 1, 0, 0, 1, 1, 1], + [1, 1, 1, 1, 0, 1, 1, 1], + [1, 1, 1, 0, 0, 1, 1, 1], + [1, 1, 0, 0, 1, 1, 1, 1], + [1, 1, 0, 1, 1, 1, 1, 1], + [1, 1, 0, 1, 1, 1, 1, 1], + [1, 1, 0, 1, 1, 1, 1, 1]] + >>> maze = [[1, 0, 0], + ... [0, 1, 1], + ... [1, 0, 1]] + >>> solve_maze(maze,0,1,len(maze)-1,len(maze)-1) + Traceback (most recent call last): + ... + ValueError: No solution exists! + + >>> maze = [[0, 0], + ... [1, 1]] + >>> solve_maze(maze,0,0,len(maze)-1,len(maze)-1) + Traceback (most recent call last): + ... + ValueError: No solution exists! + + >>> maze = [[0, 1], + ... [1, 0]] + >>> solve_maze(maze,2,0,len(maze)-1,len(maze)-1) + Traceback (most recent call last): + ... + ValueError: Invalid source or destination coordinates + + >>> maze = [[1, 0, 0], + ... [0, 1, 0], + ... [1, 0, 0]] + >>> solve_maze(maze,0,1,len(maze),len(maze)-1) + Traceback (most recent call last): + ... + ValueError: Invalid source or destination coordinates + """ size = len(maze) # Check if source and destination coordinates are Invalid. if not (0 <= source_row <= size - 1 and 0 <= source_column <= size - 1) or ( @@ -33,6 +144,17 @@ destination_column: int, solutions: list[list[int]], ) -> bool: + """ + This method is recursive starting from (i, j) and going in one of four directions: + up, down, left, right. + If a path is found to destination it returns True otherwise it returns False. + Parameters + maze: A two dimensional matrix of zeros and ones. + i, j : coordinates of matrix + solutions: A two dimensional matrix of solutions. + Returns: + Boolean if path is found True, Otherwise False. + """ size = len(maze) # Final check point. if i == destination_row and j == destination_column and maze[i][j] == 0: @@ -72,4 +194,4 @@ if __name__ == "__main__": import doctest - doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)+ doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
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[row][column] != word[word_index]: return False if word_index == len(word) - 1: return True traverts_directions = [(0, 1), (0, -1), (-1, 0), (1, 0)] len_board = len(board) len_board_column = len(board[0]) for direction in traverts_directions: next_i = row + direction[0] next_j = column + direction[1] if not (0 <= next_i < len_board and 0 <= next_j < len_board_column): continue key = get_point_key(len_board, len_board_column, next_i, next_j) if key in visited_points_set: continue visited_points_set.add(key) if exits_word(board, word, next_i, next_j, word_index + 1, visited_points_set): return True visited_points_set.remove(key) return False def word_exists(board: list[list[str]], word: str) -> bool: # Validate board board_error_message = ( "The board should be a non empty matrix of single chars strings." ) len_board = len(board) if not isinstance(board, list) or len(board) == 0: raise ValueError(board_error_message) for row in board: if not isinstance(row, list) or len(row) == 0: raise ValueError(board_error_message) for item in row: if not isinstance(item, str) or len(item) != 1: raise ValueError(board_error_message) # Validate word if not isinstance(word, str) or len(word) == 0: raise ValueError( "The word parameter should be a string of length greater than 0." ) len_board_column = len(board[0]) for i in range(len_board): for j in range(len_board_column): if exits_word( board, word, i, j, 0, {get_point_key(len_board, len_board_column, i, j)} ): return True return False if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 vertically neighboring. +The same letter cell may not be used more than once. + +Example: + +Matrix: +--------- +|A|B|C|E| +|S|F|C|S| +|A|D|E|E| +--------- + +Word: +"ABCCED" + +Result: +True + +Implementation notes: Use backtracking approach. +At each point, check all neighbors to try to find the next letter of the word. + +leetcode: https://leetcode.com/problems/word-search/ + +""" def get_point_key(len_board: int, len_board_column: int, row: int, column: int) -> int: + """ + Returns the hash key of matrix indexes. + + >>> get_point_key(10, 20, 1, 0) + 200 + """ return len_board * len_board_column * row + column @@ -13,6 +52,13 @@ word_index: int, visited_points_set: set[int], ) -> bool: + """ + Return True if it's possible to search the word suffix + starting from the word_index. + + >>> exits_word([["A"]], "B", 0, 0, 0, set()) + False + """ if board[row][column] != word[word_index]: return False @@ -43,6 +89,38 @@ def word_exists(board: list[list[str]], word: str) -> bool: + """ + >>> word_exists([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCCED") + True + >>> word_exists([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "SEE") + True + >>> word_exists([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCB") + False + >>> word_exists([["A"]], "A") + True + >>> word_exists([["B", "A", "A"], ["A", "A", "A"], ["A", "B", "A"]], "ABB") + False + >>> word_exists([["A"]], 123) + Traceback (most recent call last): + ... + ValueError: The word parameter should be a string of length greater than 0. + >>> word_exists([["A"]], "") + Traceback (most recent call last): + ... + ValueError: The word parameter should be a string of length greater than 0. + >>> word_exists([[]], "AB") + Traceback (most recent call last): + ... + ValueError: The board should be a non empty matrix of single chars strings. + >>> word_exists([], "AB") + Traceback (most recent call last): + ... + ValueError: The board should be a non empty matrix of single chars strings. + >>> word_exists([["A"], [21]], "AB") + Traceback (most recent call last): + ... + ValueError: The board should be a non empty matrix of single chars strings. + """ # Validate board board_error_message = ( @@ -81,4 +159,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] permissible_positions = [] for inner_position in positions: y_test, x_test = inner_position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(inner_position) return permissible_positions def is_complete(board: list[list[int]]) -> bool: return not any(elem == 0 for row in board for elem in row) def open_knight_tour_helper( board: list[list[int]], pos: tuple[int, int], curr: int ) -> bool: if is_complete(board): return True for position in get_valid_pos(pos, len(board)): y, x = position if board[y][x] == 0: board[y][x] = curr + 1 if open_knight_tour_helper(board, position, curr + 1): return True board[y][x] = 0 return False def open_knight_tour(n: int) -> list[list[int]]: board = [[0 for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): board[i][j] = 1 if open_knight_tour_helper(board, (i, j), 1): return board board[i][j] = 0 msg = f"Open Knight Tour cannot be performed on a board of size {n}" raise ValueError(msg) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 = [ @@ -27,6 +33,15 @@ def is_complete(board: list[list[int]]) -> bool: + """ + Check if the board (matrix) has been completely filled with non-zero values. + + >>> is_complete([[1]]) + True + + >>> is_complete([[1, 2], [3, 0]]) + False + """ return not any(elem == 0 for row in board for elem in row) @@ -34,6 +49,9 @@ def open_knight_tour_helper( board: list[list[int]], pos: tuple[int, int], curr: int ) -> bool: + """ + Helper function to solve knight tour problem. + """ if is_complete(board): return True @@ -51,6 +69,18 @@ def open_knight_tour(n: int) -> list[list[int]]: + """ + Find the solution for the knight tour problem for a board of size n. Raises + ValueError if the tour cannot be performed for the given size. + + >>> open_knight_tour(1) + [[1]] + + >>> open_knight_tour(2) + Traceback (most recent call last): + ... + ValueError: Open Knight Tour cannot be performed on a board of size 2 + """ board = [[0 for i in range(n)] for j in range(n)] @@ -68,4 +98,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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): if input_string[start:end] in word_dict and backtrack( input_string, word_dict, end ): return True return False def word_break(input_string: str, word_dict: set[str]) -> bool: return backtrack(input_string, word_dict, 0)
--- +++ @@ -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 backtrack(input_string: str, word_dict: set[str], start: int) -> bool: + """ + Helper function that uses backtracking to determine if a valid + word segmentation is possible starting from index 'start'. + + Parameters: + input_string (str): The input string to be segmented. + word_dict (set[str]): A set of valid dictionary words. + start (int): The starting index of the substring to be checked. + + Returns: + bool: True if a valid segmentation is possible, otherwise False. + + Example: + >>> backtrack("leetcode", {"leet", "code"}, 0) + True + + >>> backtrack("applepenapple", {"apple", "pen"}, 0) + True + + >>> backtrack("catsandog", {"cats", "dog", "sand", "and", "cat"}, 0) + False + """ # Base case: if the starting index has reached the end of the string if start == len(input_string): @@ -17,5 +46,29 @@ def word_break(input_string: str, word_dict: set[str]) -> bool: + """ + Determines if the input string can be segmented into a sequence of + valid dictionary words using backtracking. - return backtrack(input_string, word_dict, 0)+ Parameters: + input_string (str): The input string to segment. + word_dict (set[str]): The set of valid words. + + Returns: + bool: True if the string can be segmented into valid words, otherwise False. + + Example: + >>> word_break("leetcode", {"leet", "code"}) + True + + >>> word_break("applepenapple", {"apple", "pen"}) + True + + >>> word_break("catsandog", {"cats", "dog", "sand", "and", "cat"}) + False + + >>> word_break("applepenapple", {}) + False + """ + + return backtrack(input_string, word_dict, 0)
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, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution no_solution: Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 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, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def is_safe(grid: Matrix, row: int, column: int, n: int) -> bool: for i in range(9): if n in {grid[row][i], grid[i][column]}: return False for i in range(3): for j in range(3): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def find_empty_location(grid: Matrix) -> tuple[int, int] | None: for i in range(9): for j in range(9): if grid[i][j] == 0: return i, j return None def sudoku(grid: Matrix) -> Matrix | None: if location := find_empty_location(grid): row, column = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1, 10): if is_safe(grid, row, column, digit): grid[row][column] = digit if sudoku(grid) is not None: return grid grid[row][column] = 0 return None def print_solution(grid: Matrix) -> None: for row in grid: for cell in row: print(cell, end=" ") print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("\nExample grid:\n" + "=" * 20) print_solution(example_grid) print("\nExample grid solution:") solution = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("Cannot find a solution.")
--- +++ @@ -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 see if a cell is safe or not and recursively call the +function on the next column to see if it returns True. if yes, we +have solved the puzzle. else, we backtrack and place another number +in that cell and repeat this process. +""" from __future__ import annotations @@ -31,6 +42,12 @@ def is_safe(grid: Matrix, row: int, column: int, n: int) -> bool: + """ + This function checks the grid to see if each row, + column, and the 3x3 subgrids contain the digit 'n'. + It returns False if it is not 'safe' (a duplicate digit + is found) else returns True if it is 'safe' + """ for i in range(9): if n in {grid[row][i], grid[i][column]}: return False @@ -44,6 +61,10 @@ def find_empty_location(grid: Matrix) -> tuple[int, int] | None: + """ + This function finds an empty location so that we can assign a number + for that particular row and column. + """ for i in range(9): for j in range(9): if grid[i][j] == 0: @@ -52,6 +73,24 @@ def sudoku(grid: Matrix) -> Matrix | None: + """ + Takes a partially filled-in grid and attempts to assign values to + all unassigned locations in such a way to meet the requirements + for Sudoku solution (non-duplication across rows, columns, and boxes) + + >>> sudoku(initial_grid) # doctest: +NORMALIZE_WHITESPACE + [[3, 1, 6, 5, 7, 8, 4, 9, 2], + [5, 2, 9, 1, 3, 4, 7, 6, 8], + [4, 8, 7, 6, 2, 9, 5, 3, 1], + [2, 6, 3, 4, 1, 5, 9, 8, 7], + [9, 7, 4, 8, 6, 3, 1, 2, 5], + [8, 5, 1, 7, 9, 2, 6, 4, 3], + [1, 3, 8, 9, 4, 7, 2, 5, 6], + [6, 9, 2, 3, 5, 1, 8, 7, 4], + [7, 4, 5, 2, 8, 6, 3, 1, 9]] + >>> sudoku(no_solution) is None + True + """ if location := find_empty_location(grid): row, column = location else: @@ -71,6 +110,10 @@ def print_solution(grid: Matrix) -> None: + """ + A function to print the solution in the form + of a 9x9 grid + """ for row in grid: for cell in row: print(cell, end=" ") @@ -87,4 +130,4 @@ if solution is not None: print_solution(solution) else: - print("Cannot find a solution.")+ print("Cannot find a solution.")
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[list[int]], max_colors: int, colored_vertices: list[int], index: int ) -> bool: # Base Case if index == len(graph): return True # Recursive Step for i in range(max_colors): if valid_coloring(graph[index], colored_vertices, i): # Color current vertex colored_vertices[index] = i # Validate coloring if util_color(graph, max_colors, colored_vertices, index + 1): return True # Backtrack colored_vertices[index] = -1 return False def color(graph: list[list[int]], max_colors: int) -> list[int]: colored_vertices = [-1] * len(graph) if util_color(graph, max_colors, colored_vertices, 0): return colored_vertices return []
--- +++ @@ -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_vertices: list[int], color: int ) -> bool: + """ + For each neighbour check if the coloring constraint is satisfied + If any of the neighbours fail the constraint return False + If all neighbours validate the constraint return True + + >>> neighbours = [0,1,0,1,0] + >>> colored_vertices = [0, 2, 1, 2, 0] + + >>> color = 1 + >>> valid_coloring(neighbours, colored_vertices, color) + True + + >>> color = 2 + >>> valid_coloring(neighbours, colored_vertices, color) + False + """ # Does any neighbour not satisfy the constraints return not any( neighbour == 1 and colored_vertices[i] == color @@ -13,6 +36,37 @@ def util_color( graph: list[list[int]], max_colors: int, colored_vertices: list[int], index: int ) -> bool: + """ + Pseudo-Code + + Base Case: + 1. Check if coloring is complete + 1.1 If complete return True (meaning that we successfully colored the graph) + + Recursive Step: + 2. Iterates over each color: + Check if the current coloring is valid: + 2.1. Color given vertex + 2.2. Do recursive call, check if this coloring leads to a solution + 2.4. if current coloring leads to a solution return + 2.5. Uncolor given vertex + + >>> graph = [[0, 1, 0, 0, 0], + ... [1, 0, 1, 0, 1], + ... [0, 1, 0, 1, 0], + ... [0, 1, 1, 0, 0], + ... [0, 1, 0, 0, 0]] + >>> max_colors = 3 + >>> colored_vertices = [0, 1, 0, 0, 0] + >>> index = 3 + + >>> util_color(graph, max_colors, colored_vertices, index) + True + + >>> max_colors = 2 + >>> util_color(graph, max_colors, colored_vertices, index) + False + """ # Base Case if index == len(graph): @@ -32,9 +86,36 @@ def color(graph: list[list[int]], max_colors: int) -> list[int]: + """ + Wrapper function to call subroutine called util_color + which will either return True or False. + If True is returned colored_vertices list is filled with correct colorings + + >>> graph = [[0, 1, 0, 0, 0], + ... [1, 0, 1, 0, 1], + ... [0, 1, 0, 1, 0], + ... [0, 1, 1, 0, 0], + ... [0, 1, 0, 0, 0]] + + >>> max_colors = 3 + >>> color(graph, max_colors) + [0, 1, 0, 2, 0] + + >>> max_colors = 2 + >>> color(graph, max_colors) + [] + >>> color([], 2) # empty graph + [] + >>> color([[0]], 1) # single node, 1 color + [0] + >>> color([[0, 1], [1, 0]], 1) # 2 nodes, 1 color (impossible) + [] + >>> color([[0, 1], [1, 0]], 2) # 2 nodes, 2 colors (possible) + [0, 1] + """ colored_vertices = [-1] * len(graph) if util_color(graph, max_colors, colored_vertices, 0): return colored_vertices - return []+ return []
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[index]) backtrack(candidates, path, answer, target - candidates[index], index) path.pop(len(path) - 1) def combination_sum(candidates: list, target: int) -> list: if not candidates: raise ValueError("Candidates list should not be empty") if any(x < 0 for x in candidates): raise ValueError("All elements in candidates must be non-negative") path = [] # type: list[int] answer = [] # type: list[int] backtrack(candidates, path, answer, target, 0) return answer def main() -> None: print(combination_sum([-8, 2.3, 0], 1)) if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -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 <= candidates[i] <= 40 +All elements of candidates are distinct. +1 <= target <= 40 +""" def backtrack( candidates: list, path: list, answer: list, target: int, previous_index: int ) -> None: + """ + A recursive function that searches for possible combinations. Backtracks in case + of a bigger current combination value than the target value. + + Parameters + ---------- + previous_index: Last index from the previous search + target: The value we need to obtain by summing our integers in the path list. + answer: A list of possible combinations + path: Current combination + candidates: A list of integers we can use. + """ if target == 0: answer.append(path.copy()) else: @@ -14,6 +39,20 @@ def combination_sum(candidates: list, target: int) -> list: + """ + >>> combination_sum([2, 3, 5], 8) + [[2, 2, 2, 2], [2, 3, 3], [3, 5]] + >>> combination_sum([2, 3, 6, 7], 7) + [[2, 2, 3], [7]] + >>> combination_sum([-8, 2.3, 0], 1) + Traceback (most recent call last): + ... + ValueError: All elements in candidates must be non-negative + >>> combination_sum([], 1) + Traceback (most recent call last): + ... + ValueError: Candidates list should not be empty + """ if not candidates: raise ValueError("Candidates list should not be empty") @@ -34,4 +73,4 @@ import doctest doctest.testmod() - main()+ main()
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 col + i >= len(puzzle[0]) or puzzle[row][col + i] != "": return False return True def place_word( puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool ) -> None: for i, char in enumerate(word): if vertical: puzzle[row + i][col] = char else: puzzle[row][col + i] = char def remove_word( puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool ) -> None: for i in range(len(word)): if vertical: puzzle[row + i][col] = "" else: puzzle[row][col + i] = "" def solve_crossword(puzzle: list[list[str]], words: list[str]) -> bool: for row in range(len(puzzle)): for col in range(len(puzzle[0])): if puzzle[row][col] == "": for word in words: for vertical in [True, False]: if is_valid(puzzle, word, row, col, vertical): place_word(puzzle, word, row, col, vertical) words.remove(word) if solve_crossword(puzzle, words): return True words.append(word) remove_word(puzzle, word, row, col, vertical) return False return True if __name__ == "__main__": PUZZLE = [[""] * 3 for _ in range(3)] WORDS = ["cat", "dog", "car"] if solve_crossword(PUZZLE, WORDS): print("Solution found:") for row in PUZZLE: print(" ".join(row)) else: print("No solution found:")
--- +++ @@ -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 = [ + ... ['', '', '', ''], + ... ['', '', '', ''], + ... ['', '', '', ''], + ... ['', '', '', ''] + ... ] + >>> is_valid(puzzle, 'word', 0, 0, True) + True + >>> puzzle = [ + ... ['', '', '', ''], + ... ['', '', '', ''], + ... ['', '', '', ''], + ... ['', '', '', ''] + ... ] + >>> is_valid(puzzle, 'word', 0, 0, False) + True + """ for i in range(len(word)): if vertical: if row + i >= len(puzzle) or puzzle[row + i][col] != "": @@ -16,6 +36,19 @@ def place_word( puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool ) -> None: + """ + Place a word at the given position. + + >>> puzzle = [ + ... ['', '', '', ''], + ... ['', '', '', ''], + ... ['', '', '', ''], + ... ['', '', '', ''] + ... ] + >>> place_word(puzzle, 'word', 0, 0, True) + >>> puzzle + [['w', '', '', ''], ['o', '', '', ''], ['r', '', '', ''], ['d', '', '', '']] + """ for i, char in enumerate(word): if vertical: puzzle[row + i][col] = char @@ -26,6 +59,19 @@ def remove_word( puzzle: list[list[str]], word: str, row: int, col: int, vertical: bool ) -> None: + """ + Remove a word from the given position. + + >>> puzzle = [ + ... ['w', '', '', ''], + ... ['o', '', '', ''], + ... ['r', '', '', ''], + ... ['d', '', '', ''] + ... ] + >>> remove_word(puzzle, 'word', 0, 0, True) + >>> puzzle + [['', '', '', ''], ['', '', '', ''], ['', '', '', ''], ['', '', '', '']] + """ for i in range(len(word)): if vertical: puzzle[row + i][col] = "" @@ -34,6 +80,29 @@ def solve_crossword(puzzle: list[list[str]], words: list[str]) -> bool: + """ + Solve the crossword puzzle using backtracking. + + >>> puzzle = [ + ... ['', '', '', ''], + ... ['', '', '', ''], + ... ['', '', '', ''], + ... ['', '', '', ''] + ... ] + + >>> words = ['word', 'four', 'more', 'last'] + >>> solve_crossword(puzzle, words) + True + >>> puzzle = [ + ... ['', '', '', ''], + ... ['', '', '', ''], + ... ['', '', '', ''], + ... ['', '', '', ''] + ... ] + >>> words = ['word', 'four', 'more', 'paragraphs'] + >>> solve_crossword(puzzle, words) + False + """ for row in range(len(puzzle)): for col in range(len(puzzle[0])): if puzzle[row][col] == "": @@ -59,4 +128,4 @@ for row in PUZZLE: print(" ".join(row)) else: - print("No solution found:")+ print("No solution found:")
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, samplerate: int ) -> tuple[int | float, int | float]: lowest = min([-20, np.min(fft_results[1 : samplerate // 2 - 1])]) highest = max([20, np.max(fft_results[1 : samplerate // 2 - 1])]) return lowest, highest def show_frequency_response(filter_type: FilterType, samplerate: int) -> None: size = 512 inputs = [1] + [0] * (size - 1) outputs = [filter_type.process(item) for item in inputs] filler = [0] * (samplerate - size) # zero-padding outputs += filler fft_out = np.abs(np.fft.fft(outputs)) fft_db = 20 * np.log10(fft_out) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24, samplerate / 2 - 1) plt.xlabel("Frequency (Hz)") plt.xscale("log") # Display within reasonable bounds bounds = get_bounds(fft_db, samplerate) plt.ylim(max([-80, bounds[0]]), min([80, bounds[1]])) plt.ylabel("Gain (dB)") plt.plot(fft_db) plt.show() def show_phase_response(filter_type: FilterType, samplerate: int) -> None: size = 512 inputs = [1] + [0] * (size - 1) outputs = [filter_type.process(item) for item in inputs] filler = [0] * (samplerate - size) # zero-padding outputs += filler fft_out = np.angle(np.fft.fft(outputs)) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24, samplerate / 2 - 1) plt.xlabel("Frequency (Hz)") plt.xscale("log") plt.ylim(-2 * pi, 2 * pi) plt.ylabel("Phase shift (Radians)") plt.plot(np.unwrap(fft_out, -2 * pi)) plt.show()
--- +++ @@ -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 | float, int | float]: + """ + Get bounds for printing fft results + + >>> import numpy + >>> array = numpy.linspace(-20.0, 20.0, 1000) + >>> get_bounds(array, 1000) + (-20, 20) + """ lowest = min([-20, np.min(fft_results[1 : samplerate // 2 - 1])]) highest = max([20, np.max(fft_results[1 : samplerate // 2 - 1])]) return lowest, highest def show_frequency_response(filter_type: FilterType, samplerate: int) -> None: + """ + Show frequency response of a filter + + >>> from audio_filters.iir_filter import IIRFilter + >>> filt = IIRFilter(4) + >>> show_frequency_response(filt, 48000) + """ size = 512 inputs = [1] + [0] * (size - 1) @@ -47,6 +68,13 @@ def show_phase_response(filter_type: FilterType, samplerate: int) -> None: + """ + Show phase response of a filter + + >>> from audio_filters.iir_filter import IIRFilter + >>> filt = IIRFilter(4) + >>> show_phase_response(filt, 48000) + """ size = 512 inputs = [1] + [0] * (size - 1) @@ -64,4 +92,4 @@ plt.ylim(-2 * pi, 2 * pi) plt.ylabel("Phase shift (Radians)") plt.plot(np.unwrap(fft_out, -2 * pi)) - plt.show()+ plt.show()
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 create_state_space_tree( nums: list[int], max_sum: int, num_index: int, path: list[int], result: list[list[int]], remaining_nums_sum: int, ) -> None: if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum: return if sum(path) == max_sum: result.append(path) return for index in range(num_index, len(nums)): create_state_space_tree( nums, max_sum, index + 1, [*path, nums[index]], result, remaining_nums_sum - nums[index], ) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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. +""" def generate_sum_of_subsets_solutions(nums: list[int], max_sum: int) -> list[list[int]]: + """ + The main function. For list of numbers 'nums' find the subsets with sum + equal to 'max_sum' + + >>> generate_sum_of_subsets_solutions(nums=[3, 34, 4, 12, 5, 2], max_sum=9) + [[3, 4, 2], [4, 5]] + >>> generate_sum_of_subsets_solutions(nums=[3, 34, 4, 12, 5, 2], max_sum=3) + [[3]] + >>> generate_sum_of_subsets_solutions(nums=[3, 34, 4, 12, 5, 2], max_sum=1) + [] + """ result: list[list[int]] = [] path: list[int] = [] @@ -18,6 +37,27 @@ result: list[list[int]], remaining_nums_sum: int, ) -> None: + """ + Creates a state space tree to iterate through each branch using DFS. + It terminates the branching of a node when any of the two conditions + given below satisfy. + This algorithm follows depth-fist-search and backtracks when the node is not + branchable. + + >>> path = [] + >>> result = [] + >>> create_state_space_tree( + ... nums=[1], + ... max_sum=1, + ... num_index=0, + ... path=path, + ... result=result, + ... remaining_nums_sum=1) + >>> path + [] + >>> result + [[1]] + """ if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum: return @@ -38,4 +78,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 in range(len(sequence)): sequence[i] = int(sequence[i], 2) return sequence def gray_code_sequence_string(bit_count: int) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] seq_len = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits smaller_sequence = gray_code_sequence_string(bit_count - 1) sequence = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2): generated_no = "0" + smaller_sequence[i] sequence.append(generated_no) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2)): generated_no = "1" + smaller_sequence[i] sequence.append(generated_no) return sequence if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 integer appears at most one times in the sequence + d)The binary representation of every pair of integers differ + by exactly one bit + e) The binary representation of first and last bit also + differ by exactly one bit + + >>> gray_code(2) + [0, 1, 3, 2] + + >>> gray_code(1) + [0, 1] + + >>> gray_code(3) + [0, 1, 3, 2, 6, 7, 5, 4] + + >>> gray_code(-1) + Traceback (most recent call last): + ... + ValueError: The given input must be positive + + >>> gray_code(10.6) + Traceback (most recent call last): + ... + TypeError: unsupported operand type(s) for <<: 'int' and 'float' + """ # bit count represents no. of bits in the gray code if bit_count < 0: @@ -15,6 +48,16 @@ def gray_code_sequence_string(bit_count: int) -> list: + """ + Will output the n-bit grey sequence as a + string of bits + + >>> gray_code_sequence_string(2) + ['00', '01', '11', '10'] + + >>> gray_code_sequence_string(1) + ['0', '1'] + """ # The approach is a recursive one # Base case achieved when either n = 0 or n=1 @@ -48,4 +91,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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): return False char = pattern[pattern_index] if char in pattern_map: mapped_str = pattern_map[char] if input_string.startswith(mapped_str, str_index): return backtrack(pattern_index + 1, str_index + len(mapped_str)) else: return False for end in range(str_index + 1, len(input_string) + 1): substr = input_string[str_index:end] if substr in str_map: continue pattern_map[char] = substr str_map[substr] = char if backtrack(pattern_index + 1, end): return True del pattern_map[char] del str_map[substr] return False pattern_map: dict[str, str] = {} str_map: dict[str, str] = {} return backtrack(0, 0) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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, False otherwise. + + >>> match_word_pattern("aba", "GraphTreesGraph") + True + + >>> match_word_pattern("xyx", "PythonRubyPython") + True + + >>> match_word_pattern("GG", "PythonJavaPython") + False + """ def backtrack(pattern_index: int, str_index: int) -> bool: + """ + >>> backtrack(0, 0) + True + + >>> backtrack(0, 1) + True + + >>> backtrack(0, 4) + False + """ if pattern_index == len(pattern) and str_index == len(input_string): return True if pattern_index == len(pattern) or str_index == len(input_string): @@ -32,4 +58,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 | + ------------------------------ + | 0 | 0 | 0 | + | 0 | 1 | 1 | + | 1 | 0 | 1 | + | 1 | 1 | 0 | + ------------------------------ + +Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ +""" def xor_gate(input_1: int, input_2: int) -> int: + """ + calculate xor of the input values + + >>> xor_gate(0, 0) + 0 + >>> xor_gate(0, 1) + 1 + >>> xor_gate(1, 0) + 1 + >>> xor_gate(1, 1) + 0 + """ return (input_1, input_2).count(0) % 2 if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 | + ------------------------------ + | 0 | 0 | 0 | + | 0 | 1 | 0 | + | 1 | 0 | 0 | + | 1 | 1 | 1 | + ------------------------------ + +Refer - https://www.geeksforgeeks.org/logic-gates/ +""" def and_gate(input_1: int, input_2: int) -> int: + """ + Calculate AND of the input values + + >>> and_gate(0, 0) + 0 + >>> and_gate(0, 1) + 0 + >>> and_gate(1, 0) + 0 + >>> and_gate(1, 1) + 1 + """ return int(input_1 and input_2) def n_input_and_gate(inputs: list[int]) -> int: + """ + Calculate AND of a list of input values + + >>> n_input_and_gate([1, 0, 1, 1, 0]) + 0 + >>> n_input_and_gate([1, 1, 1, 1, 1]) + 1 + """ return int(all(inputs)) if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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_result = "".join(B32_CHARSET[int(chunk, 2)] for chunk in b32_chunks) return bytes(b32_result.ljust(8 * ((len(b32_result) // 8) + 1), "="), "utf-8") def base32_decode(data: bytes) -> bytes: binary_chunks = "".join( bin(B32_CHARSET.index(_d))[2:].zfill(5) for _d in data.decode("utf-8").strip("=") ) binary_data = list(map("".join, zip(*[iter(binary_chunks)] * 8))) return bytes("".join([chr(int(_d, 2)) for _d in binary_data]), "utf-8") if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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") + b'GEZDGNBVGY======' + >>> base32_encode(b"some long complex string") + b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=' + """ 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)) @@ -11,6 +24,14 @@ def base32_decode(data: bytes) -> bytes: + """ + >>> base32_decode(b'JBSWY3DPEBLW64TMMQQQ====') + b'Hello World!' + >>> base32_decode(b'GEZDGNBVGY======') + b'123456' + >>> base32_decode(b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=') + b'some long complex string' + """ binary_chunks = "".join( bin(B32_CHARSET.index(_d))[2:].zfill(5) for _d in data.decode("utf-8").strip("=") @@ -22,4 +43,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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]) if len(input_list) == 2: return first_implication new_list = [first_implication, *input_list[2:]] return recursive_imply_list(new_list) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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: + ------------------------------ + | Input 1 | Input 2 | Output | + ------------------------------ + | 0 | 0 | 1 | + | 0 | 1 | 1 | + | 1 | 0 | 0 | + | 1 | 1 | 1 | + ------------------------------ + +Refer - https://en.wikipedia.org/wiki/IMPLY_gate +""" def imply_gate(input_1: int, input_2: int) -> int: + """ + Calculate IMPLY of the input values + + >>> imply_gate(0, 0) + 1 + >>> imply_gate(0, 1) + 1 + >>> imply_gate(1, 0) + 0 + >>> imply_gate(1, 1) + 1 + """ return int(input_1 == 0 or input_2 == 1) def recursive_imply_list(input_list: list[int]) -> int: + """ + Recursively calculates the implication of a list. + Strictly the implication is applied consecutively left to right: + ( (a -> b) -> c ) -> d ... + + >>> recursive_imply_list([]) + Traceback (most recent call last): + ... + ValueError: Input list must contain at least two elements + >>> recursive_imply_list([0]) + Traceback (most recent call last): + ... + ValueError: Input list must contain at least two elements + >>> recursive_imply_list([1]) + Traceback (most recent call last): + ... + ValueError: Input list must contain at least two elements + >>> recursive_imply_list([0, 0]) + 1 + >>> recursive_imply_list([0, 1]) + 1 + >>> recursive_imply_list([1, 0]) + 0 + >>> recursive_imply_list([1, 1]) + 1 + >>> recursive_imply_list([0, 0, 0]) + 0 + >>> recursive_imply_list([0, 0, 1]) + 1 + >>> recursive_imply_list([0, 1, 0]) + 0 + >>> recursive_imply_list([0, 1, 1]) + 1 + >>> recursive_imply_list([1, 0, 0]) + 1 + >>> recursive_imply_list([1, 0, 1]) + 1 + >>> recursive_imply_list([1, 1, 0]) + 0 + >>> recursive_imply_list([1, 1, 1]) + 1 + """ 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]) @@ -17,4 +88,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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]: count += 1 list1[i] = "_" if count > 1: return False else: return "".join(list1) def check(binary: list[str]) -> list[str]: pi = [] while True: check1 = ["$"] * len(binary) temp = [] for i in range(len(binary)): for j in range(i + 1, len(binary)): k = compare_string(binary[i], binary[j]) if k is False: check1[i] = "*" check1[j] = "*" temp.append("X") for i in range(len(binary)): if check1[i] == "$": pi.append(binary[i]) if len(temp) == 0: return pi binary = list(set(temp)) def decimal_to_binary(no_of_variable: int, minterms: Sequence[float]) -> list[str]: temp = [] for minterm in minterms: string = "" for _ in range(no_of_variable): string = str(minterm % 2) + string minterm //= 2 temp.append(string) return temp def is_for_table(string1: str, string2: str, count: int) -> bool: list1 = list(string1) list2 = list(string2) count_n = sum(item1 != item2 for item1, item2 in zip(list1, list2)) return count_n == count def selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]: temp = [] select = [0] * len(chart) for i in range(len(chart[0])): count = sum(row[i] == 1 for row in chart) if count == 1: rem = max(j for j, row in enumerate(chart) if row[i] == 1) select[rem] = 1 for i, item in enumerate(select): if item != 1: continue for j in range(len(chart[0])): if chart[i][j] != 1: continue for row in chart: row[j] = 0 temp.append(prime_implicants[i]) while True: counts = [chart[i].count(1) for i in range(len(chart))] max_n = max(counts) rem = counts.index(max_n) if max_n == 0: return temp temp.append(prime_implicants[rem]) for j in range(len(chart[0])): if chart[rem][j] != 1: continue for i in range(len(chart)): chart[i][j] = 0 def prime_implicant_chart( prime_implicants: list[str], binary: list[str] ) -> list[list[int]]: chart = [[0 for x in range(len(binary))] for x in range(len(prime_implicants))] for i in range(len(prime_implicants)): count = prime_implicants[i].count("_") for j in range(len(binary)): if is_for_table(prime_implicants[i], binary[j], count): chart[i][j] = 1 return chart def main() -> None: no_of_variable = int(input("Enter the no. of variables\n")) minterms = [ float(x) for x in input( "Enter the decimal representation of Minterms 'Spaces Separated'\n" ).split() ] binary = decimal_to_binary(no_of_variable, minterms) prime_implicants = check(binary) print("Prime Implicants are:") print(prime_implicants) chart = prime_implicant_chart(prime_implicants, binary) essential_prime_implicants = selection(chart, prime_implicants) print("Essential Prime Implicants are:") print(essential_prime_implicants) if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -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 check(binary: list[str]) -> list[str]: + """ + >>> check(['0.00.01.5']) + ['0.00.01.5'] + """ pi = [] while True: check1 = ["$"] * len(binary) @@ -39,6 +50,10 @@ def decimal_to_binary(no_of_variable: int, minterms: Sequence[float]) -> list[str]: + """ + >>> decimal_to_binary(3,[1.5]) + ['0.00.01.5'] + """ temp = [] for minterm in minterms: string = "" @@ -50,6 +65,13 @@ def is_for_table(string1: str, string2: str, count: int) -> bool: + """ + >>> is_for_table('__1','011',2) + True + + >>> is_for_table('01_','001',1) + False + """ list1 = list(string1) list2 = list(string2) count_n = sum(item1 != item2 for item1, item2 in zip(list1, list2)) @@ -57,6 +79,13 @@ def selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]: + """ + >>> selection([[1]],['0.00.01.5']) + ['0.00.01.5'] + + >>> selection([[1]],['0.00.01.5']) + ['0.00.01.5'] + """ temp = [] select = [0] * len(chart) for i in range(len(chart[0])): @@ -93,6 +122,10 @@ def prime_implicant_chart( prime_implicants: list[str], binary: list[str] ) -> list[list[int]]: + """ + >>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5']) + [[1]] + """ chart = [[0 for x in range(len(binary))] for x in range(len(prime_implicants))] for i in range(len(prime_implicants)): count = prime_implicants[i].count("_") @@ -127,4 +160,4 @@ import doctest doctest.testmod() - main()+ main()
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 initial_speed = max(initial_speed, 0) while i < number_of_cells: highway[0][i] = ( randint(0, max_speed) if random_speed else initial_speed ) # Place the cars i += ( randint(1, max_speed * 2) if random_frequency else frequency ) # Arbitrary number, may need tuning return highway def get_distance(highway_now: list, car_index: int) -> int: distance = 0 cells = highway_now[car_index + 1 :] for cell in range(len(cells)): # May need a better name for this if cells[cell] != -1: # If the cell is not empty then return distance # we have the distance we wanted distance += 1 # Here if the car is near the end of the highway return distance + get_distance(highway_now, -1) def update(highway_now: list, probability: float, max_speed: int) -> list: number_of_cells = len(highway_now) # Beforce calculations, the highway is empty next_highway = [-1] * number_of_cells for car_index in range(number_of_cells): if highway_now[car_index] != -1: # Add 1 to the current speed of the car and cap the speed next_highway[car_index] = min(highway_now[car_index] + 1, max_speed) # Number of empty cell before the next car dn = get_distance(highway_now, car_index) - 1 # We can't have the car causing an accident next_highway[car_index] = min(next_highway[car_index], dn) if random() < probability: # Randomly, a driver will slow down next_highway[car_index] = max(next_highway[car_index] - 1, 0) return next_highway def simulate( highway: list, number_of_update: int, probability: float, max_speed: int ) -> list: number_of_cells = len(highway[0]) for i in range(number_of_update): next_speeds_calculated = update(highway[i], probability, max_speed) real_next_speeds = [-1] * number_of_cells for car_index in range(number_of_cells): speed = next_speeds_calculated[car_index] if speed != -1: # Change the position based on the speed (with % to create the loop) index = (car_index + speed) % number_of_cells # Commit the change of position real_next_speeds[index] = speed highway.append(real_next_speeds) return highway if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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). + +Some information about speed: + -1 means that the cell on the highway is empty + 0 to 5 are the speed of the cars with 0 being the lowest and 5 the highest + +highway: list[int] Where every position and speed of every car will be stored +probability The probability that a driver will slow down +initial_speed The speed of the cars a the start +frequency How many cells there are between two cars at the start +max_speed The maximum speed a car can go to +number_of_cells How many cell are there in the highway +number_of_update How many times will the position be updated + +More information here: https://en.wikipedia.org/wiki/Nagel%E2%80%93Schreckenberg_model + +Examples for doctest: +>>> simulate(construct_highway(6, 3, 0), 2, 0, 2) +[[0, -1, -1, 0, -1, -1], [-1, 1, -1, -1, 1, -1], [-1, -1, 1, -1, -1, 1]] +>>> simulate(construct_highway(5, 2, -2), 3, 0, 2) +[[0, -1, 0, -1, 0], [0, -1, 0, -1, -1], [0, -1, -1, 1, -1], [-1, 1, -1, 0, -1]] +""" from random import randint, random @@ -10,6 +36,13 @@ random_speed: bool = False, max_speed: int = 5, ) -> list: + """ + Build the highway following the parameters given + >>> construct_highway(10, 2, 6) + [[6, -1, 6, -1, 6, -1, 6, -1, 6, -1]] + >>> construct_highway(10, 10, 2) + [[2, -1, -1, -1, -1, -1, -1, -1, -1, -1]] + """ highway = [[-1] * number_of_cells] # Create a highway without any car i = 0 @@ -25,6 +58,15 @@ def get_distance(highway_now: list, car_index: int) -> int: + """ + Get the distance between a car (at index car_index) and the next car + >>> get_distance([6, -1, 6, -1, 6], 2) + 1 + >>> get_distance([2, -1, -1, -1, 3, 1, 0, 1, 3, 2], 0) + 3 + >>> get_distance([-1, -1, -1, -1, 2, -1, -1, -1, 3], -1) + 4 + """ distance = 0 cells = highway_now[car_index + 1 :] @@ -37,6 +79,13 @@ def update(highway_now: list, probability: float, max_speed: int) -> list: + """ + Update the speed of the cars + >>> update([-1, -1, -1, -1, -1, 2, -1, -1, -1, -1, 3], 0.0, 5) + [-1, -1, -1, -1, -1, 3, -1, -1, -1, -1, 4] + >>> update([-1, -1, 2, -1, -1, -1, -1, 3], 0.0, 5) + [-1, -1, 3, -1, -1, -1, -1, 1] + """ number_of_cells = len(highway_now) # Beforce calculations, the highway is empty @@ -59,6 +108,13 @@ def simulate( highway: list, number_of_update: int, probability: float, max_speed: int ) -> list: + """ + The main function, it will simulate the evolution of the highway + >>> simulate([[-1, 2, -1, -1, -1, 3]], 2, 0.0, 3) + [[-1, 2, -1, -1, -1, 3], [-1, -1, -1, 2, -1, 0], [1, -1, -1, 0, -1, -1]] + >>> simulate([[-1, 2, -1, 3]], 4, 0.0, 3) + [[-1, 2, -1, 3], [-1, 0, -1, 0], [-1, 0, -1, 0], [-1, 0, -1, 0], [-1, 0, -1, 0]] + """ number_of_cells = len(highway[0]) @@ -81,4 +137,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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!") bitwise_sum = number ^ other_number carry = number & other_number if carry == 0: return bitwise_sum return bitwise_addition_recursive(bitwise_sum, carry << 1) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 + >>> bitwise_addition_recursive(8, 9) + 17 + >>> bitwise_addition_recursive(0, 4) + 4 + >>> bitwise_addition_recursive(4.5, 9) + Traceback (most recent call last): + ... + TypeError: Both arguments MUST be integers! + >>> bitwise_addition_recursive('4', 9) + Traceback (most recent call last): + ... + TypeError: Both arguments MUST be integers! + >>> bitwise_addition_recursive('4.5', 9) + Traceback (most recent call last): + ... + TypeError: Both arguments MUST be integers! + >>> bitwise_addition_recursive(-1, 9) + Traceback (most recent call last): + ... + ValueError: Both arguments MUST be non-negative! + >>> bitwise_addition_recursive(1, -9) + Traceback (most recent call last): + ... + ValueError: Both arguments MUST be non-negative! + """ if not isinstance(number, int) or not isinstance(other_number, int): raise TypeError("Both arguments MUST be integers!") @@ -20,4 +52,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 doctest.testmod()
--- +++ @@ -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. + +For example: +number: 15 +res: 1 0b1 + 2 0b10 + 4 0b100 + 8 0b1000 + 16 0b10000 (Exit) +""" def largest_pow_of_two_le_num(number: int) -> int: + """ + Return the largest power of two less than or equal to a number. + + >>> largest_pow_of_two_le_num(0) + 0 + >>> largest_pow_of_two_le_num(1) + 1 + >>> largest_pow_of_two_le_num(-1) + 0 + >>> largest_pow_of_two_le_num(3) + 2 + >>> largest_pow_of_two_le_num(15) + 8 + >>> largest_pow_of_two_le_num(99) + 64 + >>> largest_pow_of_two_le_num(178) + 128 + >>> largest_pow_of_two_le_num(999999) + 524288 + >>> largest_pow_of_two_le_num(99.9) + Traceback (most recent call last): + ... + TypeError: Input value must be a 'int' type + """ if isinstance(number, float): raise TypeError("Input value must be a 'int' type") if number <= 0: @@ -14,4 +57,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 main() -> None: kmap = [[0, 1], [1, 1]] # Manually generate the product of [0, 1] and [0, 1] for row in kmap: print(row) print("Simplified Expression:") print(simplify_kmap(kmap)) if __name__ == "__main__": main() print(f"{simplify_kmap(kmap=[[0, 1], [1, 1]]) = }")
--- +++ @@ -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], [1, 1]]) + "A'B + AB' + AB" + >>> simplify_kmap(kmap=[[0, 0], [0, 0]]) + '' + >>> simplify_kmap(kmap=[[0, 1], [1, -1]]) + "A'B + AB' + AB" + >>> simplify_kmap(kmap=[[0, 1], [1, 2]]) + "A'B + AB' + AB" + >>> simplify_kmap(kmap=[[0, 1], [1, 1.1]]) + "A'B + AB' + AB" + >>> simplify_kmap(kmap=[[0, 1], [1, 'a']]) + "A'B + AB' + AB" + """ simplified_f = [] for a, row in enumerate(kmap): for b, item in enumerate(row): @@ -11,6 +30,15 @@ def main() -> None: + """ + Main function to create and simplify a K-Map. + + >>> main() + [0, 1] + [1, 1] + Simplified Expression: + A'B + AB' + AB + """ kmap = [[0, 1], [1, 1]] # Manually generate the product of [0, 1] and [0, 1] @@ -24,4 +52,4 @@ if __name__ == "__main__": main() - print(f"{simplify_kmap(kmap=[[0, 1], [1, 1]]) = }")+ print(f"{simplify_kmap(kmap=[[0, 1], [1, 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 return c % 2 == 1 else: return False if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 intersections = 0 +If the number is a power of 4 then it should be a power of 2 +and the set bit should be at an odd position. +""" def power_of_4(number: int) -> bool: + """ + Return True if this number is power of 4 or False otherwise. + + >>> power_of_4(0) + Traceback (most recent call last): + ... + ValueError: number must be positive + >>> power_of_4(1) + True + >>> power_of_4(2) + False + >>> power_of_4(4) + True + >>> power_of_4(6) + False + >>> power_of_4(8) + False + >>> power_of_4(17) + False + >>> power_of_4(64) + True + >>> power_of_4(-1) + Traceback (most recent call last): + ... + ValueError: number must be positive + >>> power_of_4(1.2) + Traceback (most recent call last): + ... + TypeError: number must be an integer + + """ if not isinstance(number, int): raise TypeError("number must be an integer") if number <= 0: @@ -18,4 +64,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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, position: int) -> bool: return ((number >> position) & 1) == 1 def get_bit(number: int, position: int) -> int: return int((number & (1 << position)) != 0) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 and bit on given + position - one. + + >>> set_bit(0b1101, 1) # 0b1111 + 15 + >>> set_bit(0b0, 5) # 0b100000 + 32 + >>> set_bit(0b1111, 1) # 0b1111 + 15 + """ return number | (1 << position) def clear_bit(number: int, position: int) -> int: + """ + Set the bit at position to 0. + + Details: perform bitwise and for given number and X. + Where X is a number with all the bits - ones and bit on given + position - zero. + + >>> clear_bit(0b10010, 1) # 0b10000 + 16 + >>> clear_bit(0b0, 5) # 0b0 + 0 + """ return number & ~(1 << position) def flip_bit(number: int, position: int) -> int: + """ + Flip the bit at position. + + Details: perform bitwise xor for given number and X. + Where X is a number with all the bits - zeroes and bit on given + position - one. + + >>> flip_bit(0b101, 1) # 0b111 + 7 + >>> flip_bit(0b101, 0) # 0b100 + 4 + """ return number ^ (1 << position) def is_bit_set(number: int, position: int) -> bool: + """ + Is the bit at position set? + + Details: Shift the bit at position to be the first (smallest) bit. + Then check if the first bit is set by anding the shifted number with 1. + + >>> is_bit_set(0b1010, 0) + False + >>> is_bit_set(0b1010, 1) + True + >>> is_bit_set(0b1010, 2) + False + >>> is_bit_set(0b1010, 3) + True + >>> is_bit_set(0b0, 17) + False + """ return ((number >> position) & 1) == 1 def get_bit(number: int, position: int) -> int: + """ + Get the bit at the given position + + Details: perform bitwise and for the given number and X, + Where X is a number with all the bits - zeroes and bit on given position - one. + If the result is not equal to 0, then the bit on the given position is 1, else 0. + + >>> get_bit(0b1010, 0) + 0 + >>> get_bit(0b1010, 1) + 1 + >>> get_bit(0b1010, 2) + 0 + >>> get_bit(0b1010, 3) + 1 + """ return int((number & (1 << position)) != 0) if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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(number % 2) number >>= 1 return bit_string def reverse_bit(number: int) -> int: if not isinstance(number, int): raise TypeError("Input value must be an 'int' type") if number < 0: raise ValueError("The value of input must be non-negative") result = 0 # iterator over [0 to 31], since we are dealing with a 32 bit integer for _ in range(32): # left shift the bits by unity result <<= 1 # get the end bit end_bit = number & 1 # right shift the bits by unity number >>= 1 # add that bit to our answer result |= end_bit return result if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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_string(2873) + '10011100110100000000000000000000' + >>> get_reverse_bit_string(2550136832) + '00000000000000000000000000011001' + >>> get_reverse_bit_string("this is not a number") + Traceback (most recent call last): + ... + TypeError: operation can not be conducted on an object of type str + """ if not isinstance(number, int): msg = ( "operation can not be conducted on an object of type " @@ -13,6 +29,38 @@ def reverse_bit(number: int) -> int: + """ + Take in a 32 bit integer, reverse its bits, return a 32 bit integer result + + >>> reverse_bit(25) + 2550136832 + >>> reverse_bit(37) + 2751463424 + >>> reverse_bit(21) + 2818572288 + >>> reverse_bit(58) + 1543503872 + >>> reverse_bit(0) + 0 + >>> reverse_bit(256) + 8388608 + >>> reverse_bit(2550136832) + 25 + >>> reverse_bit(-1) + Traceback (most recent call last): + ... + ValueError: The value of input must be non-negative + + >>> reverse_bit(1.1) + Traceback (most recent call last): + ... + TypeError: Input value must be an 'int' type + + >>> reverse_bit("0") + Traceback (most recent call last): + ... + TypeError: Input value must be an 'int' type + """ if not isinstance(number, int): raise TypeError("Input value must be an 'int' type") if number < 0: @@ -35,4 +83,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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: + ------------------------------ + | Input 1 | Input 2 | Output | + ------------------------------ + | 0 | 0 | 0 | + | 0 | 1 | 0 | + | 1 | 0 | 1 | + | 1 | 1 | 0 | + ------------------------------ + +Refer - https://en.wikipedia.org/wiki/NIMPLY_gate +""" def nimply_gate(input_1: int, input_2: int) -> int: + """ + Calculate NIMPLY of the input values + + >>> nimply_gate(0, 0) + 0 + >>> nimply_gate(0, 1) + 0 + >>> nimply_gate(1, 0) + 1 + >>> nimply_gate(1, 1) + 0 + """ return int(input_1 == 1 and input_2 == 0) if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 (True) otherwise. +Following is the truth table of an AND Gate: + ------------------------------ + | Input 1 | Input 2 | Output | + ------------------------------ + | 0 | 0 | 0 | + | 0 | 1 | 1 | + | 1 | 0 | 1 | + | 1 | 1 | 1 | + ------------------------------ +Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ +""" + + +def or_gate(input_1: int, input_2: int) -> int: + """ + Calculate OR of the input values + >>> or_gate(0, 0) + 0 + >>> or_gate(0, 1) + 1 + >>> or_gate(1, 0) + 1 + >>> or_gate(1, 1) + 1 + """ + return int((input_1, input_2).count(1) != 0) + + +if __name__ == "__main__": + import doctest + + doctest.testmod()
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": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", " ": "", } # Define possible trigrams of Morse code MORSE_COMBINATIONS = [ "...", "..-", "..x", ".-.", ".--", ".-x", ".x.", ".x-", ".xx", "-..", "-.-", "-.x", "--.", "---", "--x", "-x.", "-x-", "-xx", "x..", "x.-", "x.x", "x-.", "x--", "x-x", "xx.", "xx-", "xxx", ] # Create a reverse dictionary for Morse code REVERSE_DICT = {value: key for key, value in MORSE_CODE_DICT.items()} def encode_to_morse(plaintext: str) -> str: return "x".join([MORSE_CODE_DICT.get(letter.upper(), "") for letter in plaintext]) def encrypt_fractionated_morse(plaintext: str, key: str) -> str: morse_code = encode_to_morse(plaintext) key = key.upper() + string.ascii_uppercase key = "".join(sorted(set(key), key=key.find)) # Ensure morse_code length is a multiple of 3 padding_length = 3 - (len(morse_code) % 3) morse_code += "x" * padding_length fractionated_morse_dict = {v: k for k, v in zip(key, MORSE_COMBINATIONS)} fractionated_morse_dict["xxx"] = "" encrypted_text = "".join( [ fractionated_morse_dict[morse_code[i : i + 3]] for i in range(0, len(morse_code), 3) ] ) return encrypted_text def decrypt_fractionated_morse(ciphertext: str, key: str) -> str: key = key.upper() + string.ascii_uppercase key = "".join(sorted(set(key), key=key.find)) inverse_fractionated_morse_dict = dict(zip(key, MORSE_COMBINATIONS)) morse_code = "".join( [inverse_fractionated_morse_dict.get(letter, "") for letter in ciphertext] ) decrypted_text = "".join( [REVERSE_DICT[code] for code in morse_code.split("x")] ).strip() return decrypted_text if __name__ == "__main__": """ Example usage of Fractionated Morse Cipher. """ plaintext = "defend the east" print("Plain Text:", plaintext) key = "ROUNDTABLE" ciphertext = encrypt_fractionated_morse(plaintext, key) print("Encrypted:", ciphertext) decrypted_text = decrypt_fractionated_morse(ciphertext, key) print("Decrypted:", decrypted_text)
--- +++ @@ -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 secure than substitution ciphers. + +http://practicalcryptography.com/ciphers/fractionated-morse-cipher/ +""" import string @@ -67,10 +77,36 @@ def encode_to_morse(plaintext: str) -> str: + """Encode a plaintext message into Morse code. + + Args: + plaintext: The plaintext message to encode. + + Returns: + The Morse code representation of the plaintext message. + + Example: + >>> encode_to_morse("defend the east") + '-..x.x..-.x.x-.x-..xx-x....x.xx.x.-x...x-' + """ return "x".join([MORSE_CODE_DICT.get(letter.upper(), "") for letter in plaintext]) def encrypt_fractionated_morse(plaintext: str, key: str) -> str: + """Encrypt a plaintext message using Fractionated Morse Cipher. + + Args: + plaintext: The plaintext message to encrypt. + key: The encryption key. + + Returns: + The encrypted ciphertext. + + Example: + >>> encrypt_fractionated_morse("defend the east","Roundtable") + 'ESOAVVLJRSSTRX' + + """ morse_code = encode_to_morse(plaintext) key = key.upper() + string.ascii_uppercase key = "".join(sorted(set(key), key=key.find)) @@ -91,6 +127,19 @@ def decrypt_fractionated_morse(ciphertext: str, key: str) -> str: + """Decrypt a ciphertext message encrypted with Fractionated Morse Cipher. + + Args: + ciphertext: The ciphertext message to decrypt. + key: The decryption key. + + Returns: + The decrypted plaintext message. + + Example: + >>> decrypt_fractionated_morse("ESOAVVLJRSSTRX","Roundtable") + 'DEFEND THE EAST' + """ key = key.upper() + string.ascii_uppercase key = "".join(sorted(set(key), key=key.find)) @@ -116,4 +165,4 @@ print("Encrypted:", ciphertext) decrypted_text = decrypt_fractionated_morse(ciphertext, key) - print("Decrypted:", decrypted_text)+ print("Decrypted:", decrypted_text)
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 TypeError(msg) binary_stream = "".join(bin(byte)[2:].zfill(8) for byte in data) padding_needed = len(binary_stream) % 6 != 0 if padding_needed: # The padding that will be added later padding = b"=" * ((6 - len(binary_stream) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(binary_stream) % 6) else: padding = b"" # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6], 2)] for index in range(0, len(binary_stream), 6) ).encode() + padding ) def base64_decode(encoded_data: str) -> bytes: # Make sure encoded_data is either a string or a bytes-like object if not isinstance(encoded_data, bytes) and not isinstance(encoded_data, str): msg = ( "argument should be a bytes-like object or ASCII string, " f"not '{encoded_data.__class__.__name__}'" ) raise TypeError(msg) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(encoded_data, bytes): try: encoded_data = encoded_data.decode("utf-8") except UnicodeDecodeError: raise ValueError("base64 encoded data should only contain ASCII characters") padding = encoded_data.count("=") # Check if the encoded string contains non base64 characters if padding: assert all(char in B64_CHARSET for char in encoded_data[:-padding]), ( "Invalid base64 character(s) found." ) else: assert all(char in B64_CHARSET for char in encoded_data), ( "Invalid base64 character(s) found." ) # Check the padding assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one encoded_data = encoded_data[:-padding] binary_stream = "".join( bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data )[: -padding * 2] else: binary_stream = "".join( bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data ) data = [ int(binary_stream[index : index + 8], 2) for index in range(0, len(binary_stream), 8) ] return bytes(data) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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. The number of appended binary digits would later determine + how many "=" signs should be added, the padding. + For every 2 binary digits added, a "=" sign is added in the output. + We can add any binary digits to make it a multiple of 6, for instance, consider the + following example: + "AA" -> 0010100100101001 -> 001010 010010 1001 + As can be seen above, 2 more binary digits should be added, so there's 4 + possibilities here: 00, 01, 10 or 11. + That being said, Base64 encoding can be used in Steganography to hide data in these + appended digits. + + >>> from base64 import b64encode + >>> a = b"This pull request is part of Hacktoberfest20!" + >>> b = b"https://tools.ietf.org/html/rfc4648" + >>> c = b"A" + >>> base64_encode(a) == b64encode(a) + True + >>> base64_encode(b) == b64encode(b) + True + >>> base64_encode(c) == b64encode(c) + True + >>> base64_encode("abc") + Traceback (most recent call last): + ... + TypeError: a bytes-like object is required, not 'str' + """ # 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__}'" @@ -32,6 +62,29 @@ def base64_decode(encoded_data: str) -> bytes: + """Decodes data according to RFC4648. + + This does the reverse operation of base64_encode. + We first transform the encoded data back to a binary stream, take off the + previously appended binary digits according to the padding, at this point we + would have a binary stream whose length is multiple of 8, the last step is + to convert every 8 bits to a byte. + + >>> from base64 import b64decode + >>> a = "VGhpcyBwdWxsIHJlcXVlc3QgaXMgcGFydCBvZiBIYWNrdG9iZXJmZXN0MjAh" + >>> b = "aHR0cHM6Ly90b29scy5pZXRmLm9yZy9odG1sL3JmYzQ2NDg=" + >>> c = "QQ==" + >>> base64_decode(a) == b64decode(a) + True + >>> base64_decode(b) == b64decode(b) + True + >>> base64_decode(c) == b64decode(c) + True + >>> base64_decode("abc") + Traceback (most recent call last): + ... + AssertionError: Incorrect padding + """ # Make sure encoded_data is either a string or a bytes-like object if not isinstance(encoded_data, bytes) and not isinstance(encoded_data, str): msg = ( @@ -86,4 +139,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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: raise ValueError( "Warning: upper bound of deterministic test is exceeded. " "Pass allow_probable=True to allow probabilistic test. " "A return value of True indicates a probable prime." ) # array bounds provided by analysis bounds = [ 2_047, 1_373_653, 25_326_001, 3_215_031_751, 2_152_302_898_747, 3_474_749_660_383, 341_550_071_728_321, 1, 3_825_123_056_546_413_051, 1, 1, 318_665_857_834_031_151_167_461, 3_317_044_064_679_887_385_961_981, ] primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] for idx, _p in enumerate(bounds, 1): if n < _p: # then we have our last prime to check plist = primes[:idx] break d, s = n - 1, 0 # break up n -1 into a power of 2 (s) and # remaining odd component # essentially, solve for d * 2 ** s == n - 1 while d % 2 == 0: d //= 2 s += 1 for prime in plist: pr = False for r in range(s): m = pow(prime, d * 2**r, n) # see article for analysis explanation for m if (r == 0 and m == 1) or ((m + 1) % n == 0): pr = True # this loop will not determine compositeness break if pr: continue # if pr is False, then the above loop never evaluated to true, # and the n MUST be composite return False return True def test_miller_rabin() -> None: assert not miller_rabin(561) assert miller_rabin(563) # 2047 assert not miller_rabin(838_201) assert miller_rabin(838_207) # 1_373_653 assert not miller_rabin(17_316_001) assert miller_rabin(17_316_017) # 25_326_001 assert not miller_rabin(3_078_386_641) assert miller_rabin(3_078_386_653) # 3_215_031_751 assert not miller_rabin(1_713_045_574_801) assert miller_rabin(1_713_045_574_819) # 2_152_302_898_747 assert not miller_rabin(2_779_799_728_307) assert miller_rabin(2_779_799_728_327) # 3_474_749_660_383 assert not miller_rabin(113_850_023_909_441) assert miller_rabin(113_850_023_909_527) # 341_550_071_728_321 assert not miller_rabin(1_275_041_018_848_804_351) assert miller_rabin(1_275_041_018_848_804_391) # 3_825_123_056_546_413_051 assert not miller_rabin(79_666_464_458_507_787_791_867) assert miller_rabin(79_666_464_458_507_787_791_951) # 318_665_857_834_031_151_167_461 assert not miller_rabin(552_840_677_446_647_897_660_333) assert miller_rabin(552_840_677_446_647_897_660_359) # 3_317_044_064_679_887_385_961_981 # upper limit for probabilistic test if __name__ == "__main__": test_miller_rabin()
--- +++ @@ -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 number + is prime. If the passed number is above the upper limit, and + allow_probable is True, then a return value of True indicates that n is + probably prime. This test does not allow False negatives- a return value + of False is ALWAYS composite. + + Parameters + ---------- + n : int + The integer to be tested. Since we usually care if a number is prime, + n < 2 returns False instead of raising a ValueError. + allow_probable: bool, default False + Whether or not to test n above the upper bound of the deterministic test. + + Raises + ------ + ValueError + + Reference + --------- + https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test + """ if n == 2: return True if not n % 2 or n < 2: @@ -61,6 +88,9 @@ def test_miller_rabin() -> None: + """Testing a nontrivial (ends in 1, 3, 7, 9) composite + and a prime in each range. + """ assert not miller_rabin(561) assert miller_rabin(563) # 2047 @@ -104,4 +134,4 @@ if __name__ == "__main__": - test_miller_rabin()+ test_miller_rabin()
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 be positive integers") binary_number = str(bin(number)) binary_number += "0" * shift_amount return binary_number def logical_right_shift(number: int, shift_amount: int) -> str: if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers") binary_number = str(bin(number))[2:] if shift_amount >= len(binary_number): return "0b0" shifted_binary_number = binary_number[: len(binary_number) - shift_amount] return "0b" + shifted_binary_number def arithmetic_right_shift(number: int, shift_amount: int) -> str: if number >= 0: # Get binary representation of positive number binary_number = "0" + str(bin(number)).strip("-")[2:] else: # Get binary (2's complement) representation of negative number binary_number_length = len(bin(number)[3:]) # Find 2's complement of number binary_number = bin(abs(number) - (1 << binary_number_length))[3:] binary_number = ( "1" + "0" * (binary_number_length - len(binary_number)) + binary_number ) if shift_amount >= len(binary_number): return "0b" + binary_number[0] * len(binary_number) return ( "0b" + binary_number[0] * shift_amount + binary_number[: len(binary_number) - shift_amount] ) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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_shift(0, 1) + '0b00' + >>> logical_left_shift(1, 1) + '0b10' + >>> logical_left_shift(1, 5) + '0b100000' + >>> logical_left_shift(17, 2) + '0b1000100' + >>> logical_left_shift(1983, 4) + '0b111101111110000' + >>> logical_left_shift(1, -1) + Traceback (most recent call last): + ... + ValueError: both inputs must be positive integers + """ if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers") @@ -13,6 +34,27 @@ def logical_right_shift(number: int, shift_amount: int) -> str: + """ + Take in positive 2 integers. + 'number' is the integer to be logically right shifted 'shift_amount' times. + i.e. (number >>> shift_amount) + Return the shifted binary representation. + + >>> logical_right_shift(0, 1) + '0b0' + >>> logical_right_shift(1, 1) + '0b0' + >>> logical_right_shift(1, 5) + '0b0' + >>> logical_right_shift(17, 2) + '0b100' + >>> logical_right_shift(1983, 4) + '0b1111011' + >>> logical_right_shift(1, -1) + Traceback (most recent call last): + ... + ValueError: both inputs must be positive integers + """ if number < 0 or shift_amount < 0: raise ValueError("both inputs must be positive integers") @@ -24,6 +66,25 @@ def arithmetic_right_shift(number: int, shift_amount: int) -> str: + """ + Take in 2 integers. + 'number' is the integer to be arithmetically right shifted 'shift_amount' times. + i.e. (number >> shift_amount) + Return the shifted binary representation. + + >>> arithmetic_right_shift(0, 1) + '0b00' + >>> arithmetic_right_shift(1, 1) + '0b00' + >>> arithmetic_right_shift(-1, 1) + '0b11' + >>> arithmetic_right_shift(17, 2) + '0b000100' + >>> arithmetic_right_shift(-17, 2) + '0b111011' + >>> arithmetic_right_shift(-1983, 4) + '0b111110000100' + """ if number >= 0: # Get binary representation of positive number binary_number = "0" + str(bin(number)).strip("-")[2:] else: # Get binary (2's complement) representation of negative number @@ -45,4 +106,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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) otherwise. It's similar to adding +a NOT gate along with an AND gate. +Following is the truth table of a NAND Gate: + ------------------------------ + | Input 1 | Input 2 | Output | + ------------------------------ + | 0 | 0 | 1 | + | 0 | 1 | 1 | + | 1 | 0 | 1 | + | 1 | 1 | 0 | + ------------------------------ +Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ +""" + + +def nand_gate(input_1: int, input_2: int) -> int: + """ + Calculate NAND of the input values + >>> nand_gate(0, 0) + 1 + >>> nand_gate(0, 1) + 1 + >>> nand_gate(1, 0) + 1 + >>> nand_gate(1, 1) + 0 + """ + return int(not (input_1 and input_2)) + + +if __name__ == "__main__": + import doctest + + doctest.testmod()
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, b) # extended_gcd(a,b) function implemented below r = c / d return (r * x, r * y) def diophantine_all_soln(a: int, b: int, c: int, n: int = 2) -> None: (x0, y0) = diophantine(a, b, c) # Initial value d = greatest_common_divisor(a, b) p = a // d q = b // d for i in range(n): x = x0 + i * q y = y0 - i * p print(x, y) def extended_gcd(a: int, b: int) -> tuple[int, int, int]: assert a >= 0 assert b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 assert b % d == 0 assert d == a * x + b * y return (d, x, y) if __name__ == "__main__": from doctest import testmod testmod(name="diophantine", verbose=True) testmod(name="diophantine_all_soln", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="greatest_common_divisor", verbose=True)
--- +++ @@ -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. + + GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) + + >>> diophantine(10,6,14) + (-7.0, 14.0) + + >>> diophantine(391,299,-69) + (9.0, -12.0) + + But above equation has one more solution i.e., x = -4, y = 5. + That's why we need diophantine all solution function. + + """ assert ( c % greatest_common_divisor(a, b) == 0 @@ -14,6 +31,35 @@ def diophantine_all_soln(a: int, b: int, c: int, n: int = 2) -> None: + """ + Lemma : if n|ab and gcd(a,n) = 1, then n|b. + + Finding All solutions of Diophantine Equations: + + Theorem : Let gcd(a,b) = d, a = d*p, b = d*q. If (x0,y0) is a solution of + Diophantine Equation a*x + b*y = c. a*x0 + b*y0 = c, then all the + solutions have the form a(x0 + t*q) + b(y0 - t*p) = c, + where t is an arbitrary integer. + + n is the number of solution you want, n = 2 by default + + >>> diophantine_all_soln(10, 6, 14) + -7.0 14.0 + -4.0 9.0 + + >>> diophantine_all_soln(10, 6, 14, 4) + -7.0 14.0 + -4.0 9.0 + -1.0 4.0 + 2.0 -1.0 + + >>> diophantine_all_soln(391, 299, -69, n = 4) + 9.0 -12.0 + 22.0 -29.0 + 35.0 -46.0 + 48.0 -63.0 + + """ (x0, y0) = diophantine(a, b, c) # Initial value d = greatest_common_divisor(a, b) p = a // d @@ -26,6 +72,17 @@ def extended_gcd(a: int, b: int) -> tuple[int, int, int]: + """ + Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers + x and y, then d = gcd(a,b) + + >>> extended_gcd(10, 6) + (2, -1, 2) + + >>> extended_gcd(7, 5) + (1, -2, 3) + + """ assert a >= 0 assert b >= 0 @@ -49,4 +106,4 @@ testmod(name="diophantine", verbose=True) testmod(name="diophantine_all_soln", verbose=True) testmod(name="extended_gcd", verbose=True) - testmod(name="greatest_common_divisor", verbose=True)+ testmod(name="greatest_common_divisor", verbose=True)
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( ( "Truth Table of NOR Gate:", make_table_row(("Input 1", "Input 2", "Output")), *[make_table_row((i, j, func(i, j))) for i in (0, 1) for j in (0, 1)], ) ) if __name__ == "__main__": import doctest doctest.testmod() print(truth_table(nor_gate))
--- +++ @@ -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 | + | 0 | 1 | 0 | + | 1 | 0 | 0 | + | 1 | 1 | 0 | + + Code provided by Akshaj Vishwanathan +https://www.geeksforgeeks.org/logic-gates-in-python +""" from collections.abc import Callable def nor_gate(input_1: int, input_2: int) -> int: + """ + >>> nor_gate(0, 0) + 1 + >>> nor_gate(0, 1) + 0 + >>> nor_gate(1, 0) + 0 + >>> nor_gate(1, 1) + 0 + >>> nor_gate(0.0, 0.0) + 1 + >>> nor_gate(0, -7) + 0 + """ return int(input_1 == input_2 == 0) def truth_table(func: Callable) -> str: + """ + >>> print(truth_table(nor_gate)) + Truth Table of NOR Gate: + | Input 1 | Input 2 | Output | + | 0 | 0 | 1 | + | 0 | 1 | 0 | + | 1 | 0 | 0 | + | 1 | 1 | 0 | + """ def make_table_row(items: list | tuple) -> str: + """ + >>> make_table_row(("One", "Two", "Three")) + '| One | Two | Three |' + """ return f"| {' | '.join(f'{item:^8}' for item in items)} |" return "\n".join( @@ -24,4 +65,4 @@ import doctest doctest.testmod() - print(truth_table(nor_gate))+ print(truth_table(nor_gate))
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) -> bool: + """ + Return True if numbers have opposite signs False otherwise. + + >>> different_signs(1, -1) + True + >>> different_signs(1, 1) + False + >>> different_signs(1000000000000000000000000000, -1000000000000000000000000000) + True + >>> different_signs(-1000000000000000000000000000, 1000000000000000000000000000) + True + >>> different_signs(50, 278) + False + >>> different_signs(0, 2) + False + >>> different_signs(2, 0) + False + """ return num1 ^ num2 < 0 if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 for i in range(size)] for j in range(size)] return canvas def seed(canvas: list[list[bool]]) -> None: for i, row in enumerate(canvas): for j, _ in enumerate(row): canvas[i][j] = bool(random.getrandbits(1)) def run(canvas: list[list[bool]]) -> list[list[bool]]: current_canvas = np.array(canvas) next_gen_canvas = np.array(create_canvas(current_canvas.shape[0])) for r, row in enumerate(current_canvas): for c, pt in enumerate(row): next_gen_canvas[r][c] = __judge_point( pt, current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) return next_gen_canvas.tolist() def __judge_point(pt: bool, neighbours: list[list[bool]]) -> bool: dead = 0 alive = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. state = pt if pt: if alive < 2: state = False elif alive in {2, 3}: state = True elif alive > 3: state = False elif alive == 3: state = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) canvas_size = int(sys.argv[1]) # main working structure of this module. c = create_canvas(canvas_size) seed(c) fig, ax = plt.subplots() fig.show() cmap = ListedColormap(["w", "k"]) try: while True: c = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
--- +++ @@ -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 neighbours + dies, as if caused by under-population. + 2. + Any live cell with two or three live neighbours lives + on to the next generation. + 3. + Any live cell with more than three live neighbours + dies, as if by over-population. + 4. + Any dead cell with exactly three live neighbours be- + comes a live cell, as if by reproduction. +""" import random import sys @@ -24,6 +53,17 @@ def run(canvas: list[list[bool]]) -> list[list[bool]]: + """ + This function runs the rules of game through all points, and changes their + status accordingly.(in the same canvas) + @Args: + -- + canvas : canvas of population to run the rules on. + + @returns: + -- + canvas of population after one step + """ current_canvas = np.array(canvas) next_gen_canvas = np.array(create_canvas(current_canvas.shape[0])) for r, row in enumerate(current_canvas): @@ -86,4 +126,4 @@ ax.cla() except KeyboardInterrupt: # do nothing. - pass+ pass
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 before reproducing PREDATOR_INITIAL_COUNT = 50 # The initial number of predator entities # The initial energy value of predator entities PREDATOR_INITIAL_ENERGY_VALUE = 15 # The energy value provided when consuming prey PREDATOR_FOOD_VALUE = 5 PREDATOR_REPRODUCTION_TIME = 20 # The chronons before reproducing MAX_ENTITIES = 500 # The max number of organisms on the board # The number of entities to delete from the unbalanced side DELETE_UNBALANCED_ENTITIES = 50 class Entity: def __init__(self, prey: bool, coords: tuple[int, int]) -> None: self.prey = prey # The (row, col) pos of the entity self.coords = coords self.remaining_reproduction_time = ( PREY_REPRODUCTION_TIME if prey else PREDATOR_REPRODUCTION_TIME ) self.energy_value = None if prey is True else PREDATOR_INITIAL_ENERGY_VALUE self.alive = True def reset_reproduction_time(self) -> None: self.remaining_reproduction_time = ( PREY_REPRODUCTION_TIME if self.prey is True else PREDATOR_REPRODUCTION_TIME ) def __repr__(self) -> str: repr_ = ( f"Entity(prey={self.prey}, coords={self.coords}, " f"remaining_reproduction_time={self.remaining_reproduction_time}" ) if self.energy_value is not None: repr_ += f", energy_value={self.energy_value}" return f"{repr_})" class WaTor: time_passed: Callable[["WaTor", int], None] | None def __init__(self, width: int, height: int) -> None: self.width = width self.height = height self.time_passed = None self.planet: list[list[Entity | None]] = [[None] * width for _ in range(height)] # Populate planet with predators and prey randomly for _ in range(PREY_INITIAL_COUNT): self.add_entity(prey=True) for _ in range(PREDATOR_INITIAL_COUNT): self.add_entity(prey=False) self.set_planet(self.planet) def set_planet(self, planet: list[list[Entity | None]]) -> None: self.planet = planet self.width = len(planet[0]) self.height = len(planet) def add_entity(self, prey: bool) -> None: while True: row, col = randint(0, self.height - 1), randint(0, self.width - 1) if self.planet[row][col] is None: self.planet[row][col] = Entity(prey=prey, coords=(row, col)) return def get_entities(self) -> list[Entity]: return [entity for column in self.planet for entity in column if entity] def balance_predators_and_prey(self) -> None: entities = self.get_entities() shuffle(entities) if len(entities) >= MAX_ENTITIES - MAX_ENTITIES / 10: prey = [entity for entity in entities if entity.prey] predators = [entity for entity in entities if not entity.prey] prey_count, predator_count = len(prey), len(predators) entities_to_purge = ( prey[:DELETE_UNBALANCED_ENTITIES] if prey_count > predator_count else predators[:DELETE_UNBALANCED_ENTITIES] ) for entity in entities_to_purge: self.planet[entity.coords[0]][entity.coords[1]] = None def get_surrounding_prey(self, entity: Entity) -> list[Entity]: row, col = entity.coords adjacent: list[tuple[int, int]] = [ (row - 1, col), # North (row + 1, col), # South (row, col - 1), # West (row, col + 1), # East ] return [ ent for r, c in adjacent if 0 <= r < self.height and 0 <= c < self.width and (ent := self.planet[r][c]) is not None and ent.prey ] def move_and_reproduce( self, entity: Entity, direction_orders: list[Literal["N", "E", "S", "W"]] ) -> None: row, col = coords = entity.coords adjacent_squares: dict[Literal["N", "E", "S", "W"], tuple[int, int]] = { "N": (row - 1, col), # North "S": (row + 1, col), # South "W": (row, col - 1), # West "E": (row, col + 1), # East } # Weight adjacent locations adjacent: list[tuple[int, int]] = [] for order in direction_orders: adjacent.append(adjacent_squares[order]) for r, c in adjacent: if ( 0 <= r < self.height and 0 <= c < self.width and self.planet[r][c] is None ): # Move entity to empty adjacent square self.planet[r][c] = entity self.planet[row][col] = None entity.coords = (r, c) break # (2.) See if it possible to reproduce in previous square if coords != entity.coords and entity.remaining_reproduction_time <= 0: # Check if the entities on the planet is less than the max limit if len(self.get_entities()) < MAX_ENTITIES: # Reproduce in previous square self.planet[row][col] = Entity(prey=entity.prey, coords=coords) entity.reset_reproduction_time() else: entity.remaining_reproduction_time -= 1 def perform_prey_actions( self, entity: Entity, direction_orders: list[Literal["N", "E", "S", "W"]] ) -> None: self.move_and_reproduce(entity, direction_orders) def perform_predator_actions( self, entity: Entity, occupied_by_prey_coords: tuple[int, int] | None, direction_orders: list[Literal["N", "E", "S", "W"]], ) -> None: assert entity.energy_value is not None # [type checking] # (3.) If the entity has 0 energy, it will die if entity.energy_value == 0: self.planet[entity.coords[0]][entity.coords[1]] = None return # (1.) Move to entity if possible if occupied_by_prey_coords is not None: # Kill the prey prey = self.planet[occupied_by_prey_coords[0]][occupied_by_prey_coords[1]] assert prey is not None prey.alive = False # Move onto prey self.planet[occupied_by_prey_coords[0]][occupied_by_prey_coords[1]] = entity self.planet[entity.coords[0]][entity.coords[1]] = None entity.coords = occupied_by_prey_coords # (4.) Eats the prey and earns energy entity.energy_value += PREDATOR_FOOD_VALUE else: # (5.) If it has survived the certain number of chronons it will also # reproduce in this function self.move_and_reproduce(entity, direction_orders) # (2.) Each chronon, the predator is deprived of a unit of energy entity.energy_value -= 1 def run(self, *, iteration_count: int) -> None: for iter_num in range(iteration_count): # Generate list of all entities in order to randomly # pop an entity at a time to simulate true randomness # This removes the systematic approach of iterating # through each entity width by height all_entities = self.get_entities() for __ in range(len(all_entities)): entity = all_entities.pop(randint(0, len(all_entities) - 1)) if entity.alive is False: continue directions: list[Literal["N", "E", "S", "W"]] = ["N", "E", "S", "W"] shuffle(directions) # Randomly shuffle directions if entity.prey: self.perform_prey_actions(entity, directions) else: # Create list of surrounding prey surrounding_prey = self.get_surrounding_prey(entity) surrounding_prey_coords = None if surrounding_prey: # Again, randomly shuffle directions shuffle(surrounding_prey) surrounding_prey_coords = surrounding_prey[0].coords self.perform_predator_actions( entity, surrounding_prey_coords, directions ) # Balance out the predators and prey self.balance_predators_and_prey() if self.time_passed is not None: # Call time_passed function for Wa-Tor planet # visualisation in a terminal or a graph. self.time_passed(self, iter_num) def visualise(wt: WaTor, iter_number: int, *, colour: bool = True) -> None: if colour: __import__("os").system("") print("\x1b[0;0H\x1b[2J\x1b[?25l") reprint = "\x1b[0;0H" if colour else "" ansi_colour_end = "\x1b[0m " if colour else " " planet = wt.planet output = "" # Iterate over every entity in the planet for row in planet: for entity in row: if entity is None: output += " . " else: if colour is True: output += ( "\x1b[38;2;96;241;151m" if entity.prey else "\x1b[38;2;255;255;15m" ) output += f" {'#' if entity.prey else 'x'}{ansi_colour_end}" output += "\n" entities = wt.get_entities() prey_count = sum(entity.prey for entity in entities) print( f"{output}\n Iteration: {iter_number} | Prey count: {prey_count} | " f"Predator count: {len(entities) - prey_count} | {reprint}" ) # Block the thread to be able to visualise seeing the algorithm sleep(0.05) if __name__ == "__main__": import doctest doctest.testmod() wt = WaTor(WIDTH, HEIGHT) wt.time_passed = visualise wt.run(iteration_count=100_000)
--- +++ @@ -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. + +The constants are a working set that allows the Wa-Tor planet +to result in one of the three possible results. +""" from collections.abc import Callable from random import randint, shuffle @@ -23,6 +36,17 @@ class Entity: + """ + Represents an entity (either prey or predator). + + >>> e = Entity(True, coords=(0, 0)) + >>> e.prey + True + >>> e.coords + (0, 0) + >>> e.alive + True + """ def __init__(self, prey: bool, coords: tuple[int, int]) -> None: self.prey = prey @@ -36,11 +60,28 @@ self.alive = True def reset_reproduction_time(self) -> None: + """ + >>> e = Entity(True, coords=(0, 0)) + >>> e.reset_reproduction_time() + >>> e.remaining_reproduction_time == PREY_REPRODUCTION_TIME + True + >>> e = Entity(False, coords=(0, 0)) + >>> e.reset_reproduction_time() + >>> e.remaining_reproduction_time == PREDATOR_REPRODUCTION_TIME + True + """ self.remaining_reproduction_time = ( PREY_REPRODUCTION_TIME if self.prey is True else PREDATOR_REPRODUCTION_TIME ) def __repr__(self) -> str: + """ + >>> Entity(prey=True, coords=(1, 1)) + Entity(prey=True, coords=(1, 1), remaining_reproduction_time=5) + >>> Entity(prey=False, coords=(2, 1)) # doctest: +NORMALIZE_WHITESPACE + Entity(prey=False, coords=(2, 1), + remaining_reproduction_time=20, energy_value=15) + """ repr_ = ( f"Entity(prey={self.prey}, coords={self.coords}, " f"remaining_reproduction_time={self.remaining_reproduction_time}" @@ -51,6 +92,26 @@ class WaTor: + """ + Represents the main Wa-Tor algorithm. + + :attr time_passed: A function that is called every time + time passes (a chronon) in order to visually display + the new Wa-Tor planet. The `time_passed` function can block + using ``time.sleep`` to slow the algorithm progression. + + >>> wt = WaTor(10, 15) + >>> wt.width + 10 + >>> wt.height + 15 + >>> len(wt.planet) + 15 + >>> len(wt.planet[0]) + 10 + >>> len(wt.get_entities()) == PREDATOR_INITIAL_COUNT + PREY_INITIAL_COUNT + True + """ time_passed: Callable[["WaTor", int], None] | None @@ -69,11 +130,40 @@ self.set_planet(self.planet) def set_planet(self, planet: list[list[Entity | None]]) -> None: + """ + Ease of access for testing + + >>> wt = WaTor(WIDTH, HEIGHT) + >>> planet = [ + ... [None, None, None], + ... [None, Entity(True, coords=(1, 1)), None] + ... ] + >>> wt.set_planet(planet) + >>> wt.planet == planet + True + >>> wt.width + 3 + >>> wt.height + 2 + """ self.planet = planet self.width = len(planet[0]) self.height = len(planet) def add_entity(self, prey: bool) -> None: + """ + Adds an entity, making sure the entity does + not override another entity + + >>> wt = WaTor(WIDTH, HEIGHT) + >>> wt.set_planet([[None, None], [None, None]]) + >>> wt.add_entity(True) + >>> len(wt.get_entities()) + 1 + >>> wt.add_entity(False) + >>> len(wt.get_entities()) + 2 + """ while True: row, col = randint(0, self.height - 1), randint(0, self.width - 1) if self.planet[row][col] is None: @@ -81,9 +171,30 @@ return def get_entities(self) -> list[Entity]: + """ + Returns a list of all the entities within the planet. + + >>> wt = WaTor(WIDTH, HEIGHT) + >>> len(wt.get_entities()) == PREDATOR_INITIAL_COUNT + PREY_INITIAL_COUNT + True + """ return [entity for column in self.planet for entity in column if entity] def balance_predators_and_prey(self) -> None: + """ + Balances predators and preys so that prey + can not dominate the predators, blocking up + space for them to reproduce. + + >>> wt = WaTor(WIDTH, HEIGHT) + >>> for i in range(2000): + ... row, col = i // HEIGHT, i % WIDTH + ... wt.planet[row][col] = Entity(True, coords=(row, col)) + >>> entities = len(wt.get_entities()) + >>> wt.balance_predators_and_prey() + >>> len(wt.get_entities()) == entities + False + """ entities = self.get_entities() shuffle(entities) @@ -102,6 +213,30 @@ self.planet[entity.coords[0]][entity.coords[1]] = None def get_surrounding_prey(self, entity: Entity) -> list[Entity]: + """ + Returns all the prey entities around (N, S, E, W) a predator entity. + + Subtly different to the `move_and_reproduce`. + + >>> wt = WaTor(WIDTH, HEIGHT) + >>> wt.set_planet([ + ... [None, Entity(True, (0, 1)), None], + ... [None, Entity(False, (1, 1)), None], + ... [None, Entity(True, (2, 1)), None]]) + >>> wt.get_surrounding_prey( + ... Entity(False, (1, 1))) # doctest: +NORMALIZE_WHITESPACE + [Entity(prey=True, coords=(0, 1), remaining_reproduction_time=5), + Entity(prey=True, coords=(2, 1), remaining_reproduction_time=5)] + >>> wt.set_planet([[Entity(False, (0, 0))]]) + >>> wt.get_surrounding_prey(Entity(False, (0, 0))) + [] + >>> wt.set_planet([ + ... [Entity(True, (0, 0)), Entity(False, (1, 0)), Entity(False, (2, 0))], + ... [None, Entity(False, (1, 1)), Entity(True, (2, 1))], + ... [None, None, None]]) + >>> wt.get_surrounding_prey(Entity(False, (1, 0))) + [Entity(prey=True, coords=(0, 0), remaining_reproduction_time=5)] + """ row, col = entity.coords adjacent: list[tuple[int, int]] = [ (row - 1, col), # North @@ -122,6 +257,58 @@ def move_and_reproduce( self, entity: Entity, direction_orders: list[Literal["N", "E", "S", "W"]] ) -> None: + """ + Attempts to move to an unoccupied neighbouring square + in either of the four directions (North, South, East, West). + If the move was successful and the `remaining_reproduction_time` is + equal to 0, then a new prey or predator can also be created + in the previous square. + + :param direction_orders: Ordered list (like priority queue) depicting + order to attempt to move. Removes any systematic + approach of checking neighbouring squares. + + >>> planet = [ + ... [None, None, None], + ... [None, Entity(True, coords=(1, 1)), None], + ... [None, None, None] + ... ] + >>> wt = WaTor(WIDTH, HEIGHT) + >>> wt.set_planet(planet) + >>> wt.move_and_reproduce(Entity(True, coords=(1, 1)), direction_orders=["N"]) + >>> wt.planet # doctest: +NORMALIZE_WHITESPACE + [[None, Entity(prey=True, coords=(0, 1), remaining_reproduction_time=4), None], + [None, None, None], + [None, None, None]] + >>> wt.planet[0][0] = Entity(True, coords=(0, 0)) + >>> wt.move_and_reproduce(Entity(True, coords=(0, 1)), + ... direction_orders=["N", "W", "E", "S"]) + >>> wt.planet # doctest: +NORMALIZE_WHITESPACE + [[Entity(prey=True, coords=(0, 0), remaining_reproduction_time=5), None, + Entity(prey=True, coords=(0, 2), remaining_reproduction_time=4)], + [None, None, None], + [None, None, None]] + >>> wt.planet[0][1] = wt.planet[0][2] + >>> wt.planet[0][2] = None + >>> wt.move_and_reproduce(Entity(True, coords=(0, 1)), + ... direction_orders=["N", "W", "S", "E"]) + >>> wt.planet # doctest: +NORMALIZE_WHITESPACE + [[Entity(prey=True, coords=(0, 0), remaining_reproduction_time=5), None, None], + [None, Entity(prey=True, coords=(1, 1), remaining_reproduction_time=4), None], + [None, None, None]] + + >>> wt = WaTor(WIDTH, HEIGHT) + >>> reproducable_entity = Entity(False, coords=(0, 1)) + >>> reproducable_entity.remaining_reproduction_time = 0 + >>> wt.planet = [[None, reproducable_entity]] + >>> wt.move_and_reproduce(reproducable_entity, + ... direction_orders=["N", "W", "S", "E"]) + >>> wt.planet # doctest: +NORMALIZE_WHITESPACE + [[Entity(prey=False, coords=(0, 0), + remaining_reproduction_time=20, energy_value=15), + Entity(prey=False, coords=(0, 1), remaining_reproduction_time=20, + energy_value=15)]] + """ row, col = coords = entity.coords adjacent_squares: dict[Literal["N", "E", "S", "W"], tuple[int, int]] = { @@ -160,6 +347,27 @@ def perform_prey_actions( self, entity: Entity, direction_orders: list[Literal["N", "E", "S", "W"]] ) -> None: + """ + Performs the actions for a prey entity + + For prey the rules are: + 1. At each chronon, a prey moves randomly to one of the adjacent unoccupied + squares. If there are no free squares, no movement takes place. + 2. Once a prey has survived a certain number of chronons it may reproduce. + This is done as it moves to a neighbouring square, + leaving behind a new prey in its old position. + Its reproduction time is also reset to zero. + + >>> wt = WaTor(WIDTH, HEIGHT) + >>> reproducable_entity = Entity(True, coords=(0, 1)) + >>> reproducable_entity.remaining_reproduction_time = 0 + >>> wt.planet = [[None, reproducable_entity]] + >>> wt.perform_prey_actions(reproducable_entity, + ... direction_orders=["N", "W", "S", "E"]) + >>> wt.planet # doctest: +NORMALIZE_WHITESPACE + [[Entity(prey=True, coords=(0, 0), remaining_reproduction_time=5), + Entity(prey=True, coords=(0, 1), remaining_reproduction_time=5)]] + """ self.move_and_reproduce(entity, direction_orders) def perform_predator_actions( @@ -168,6 +376,29 @@ occupied_by_prey_coords: tuple[int, int] | None, direction_orders: list[Literal["N", "E", "S", "W"]], ) -> None: + """ + Performs the actions for a predator entity + + :param occupied_by_prey_coords: Move to this location if there is prey there + + For predators the rules are: + 1. At each chronon, a predator moves randomly to an adjacent square occupied + by a prey. If there is none, the predator moves to a random adjacent + unoccupied square. If there are no free squares, no movement takes place. + 2. At each chronon, each predator is deprived of a unit of energy. + 3. Upon reaching zero energy, a predator dies. + 4. If a predator moves to a square occupied by a prey, + it eats the prey and earns a certain amount of energy. + 5. Once a predator has survived a certain number of chronons + it may reproduce in exactly the same way as the prey. + + >>> wt = WaTor(WIDTH, HEIGHT) + >>> wt.set_planet([[Entity(True, coords=(0, 0)), Entity(False, coords=(0, 1))]]) + >>> wt.perform_predator_actions(Entity(False, coords=(0, 1)), (0, 0), []) + >>> wt.planet # doctest: +NORMALIZE_WHITESPACE + [[Entity(prey=False, coords=(0, 0), + remaining_reproduction_time=20, energy_value=19), None]] + """ assert entity.energy_value is not None # [type checking] # (3.) If the entity has 0 energy, it will die @@ -198,6 +429,15 @@ entity.energy_value -= 1 def run(self, *, iteration_count: int) -> None: + """ + Emulate time passing by looping `iteration_count` times + + >>> wt = WaTor(WIDTH, HEIGHT) + >>> wt.run(iteration_count=PREDATOR_INITIAL_ENERGY_VALUE - 1) + >>> len(list(filter(lambda entity: entity.prey is False, + ... wt.get_entities()))) >= PREDATOR_INITIAL_COUNT + True + """ for iter_num in range(iteration_count): # Generate list of all entities in order to randomly # pop an entity at a time to simulate true randomness @@ -239,6 +479,28 @@ def visualise(wt: WaTor, iter_number: int, *, colour: bool = True) -> None: + """ + Visually displays the Wa-Tor planet using + an ascii code in terminal to clear and re-print + the Wa-Tor planet at intervals. + + Uses ascii colour codes to colourfully display the predators and prey: + * (0x60f197) Prey = ``#`` + * (0xfffff) Predator = ``x`` + + >>> wt = WaTor(30, 30) + >>> wt.set_planet([ + ... [Entity(True, coords=(0, 0)), Entity(False, coords=(0, 1)), None], + ... [Entity(False, coords=(1, 0)), None, Entity(False, coords=(1, 2))], + ... [None, Entity(True, coords=(2, 1)), None] + ... ]) + >>> visualise(wt, 0, colour=False) # doctest: +NORMALIZE_WHITESPACE + # x . + x . x + . # . + <BLANKLINE> + Iteration: 0 | Prey count: 2 | Predator count: 3 | + """ if colour: __import__("os").system("") print("\x1b[0;0H\x1b[2J\x1b[?25l") @@ -283,4 +545,4 @@ wt = WaTor(WIDTH, HEIGHT) wt.time_passed = visualise - wt.run(iteration_count=100_000)+ wt.run(iteration_count=100_000)
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"{ruleset:08}"[:8]] def new_generation(cells: list[list[int]], rule: list[int], time: int) -> list[int]: population = len(cells[0]) # 31 next_generation = [] for i in range(population): # Get the neighbors of each cell # Handle neighbours outside bounds by using 0 as their value left_neighbor = 0 if i == 0 else cells[time][i - 1] right_neighbor = 0 if i == population - 1 else cells[time][i + 1] # Define a new cell and add it to the new generation situation = 7 - int(f"{left_neighbor}{cells[time][i]}{right_neighbor}", 2) next_generation.append(rule[situation]) return next_generation def generate_image(cells: list[list[int]]) -> Image.Image: # Create the output image img = Image.new("RGB", (len(cells[0]), len(cells))) pixels = img.load() # Generates image for w in range(img.width): for h in range(img.height): color = 255 - int(255 * cells[h][w]) pixels[w, h] = (color, color, color) return img if __name__ == "__main__": rule_num = bin(int(input("Rule:\n").strip()))[2:] rule = format_ruleset(int(rule_num)) for time in range(16): CELLS.append(new_generation(CELLS, rule, time)) img = generate_image(CELLS) # Uncomment to save the image # img.save(f"rule_{rule_num}.png") img.show()
--- +++ @@ -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]: + """ + >>> format_ruleset(11100) + [0, 0, 0, 1, 1, 1, 0, 0] + >>> format_ruleset(0) + [0, 0, 0, 0, 0, 0, 0, 0] + >>> format_ruleset(11111111) + [1, 1, 1, 1, 1, 1, 1, 1] + """ return [int(c) for c in f"{ruleset:08}"[:8]] @@ -29,6 +42,16 @@ def generate_image(cells: list[list[int]]) -> Image.Image: + """ + Convert the cells into a greyscale PIL.Image.Image and return it to the caller. + >>> from random import random + >>> cells = [[random() for w in range(31)] for h in range(16)] + >>> img = generate_image(cells) + >>> isinstance(img, Image.Image) + True + >>> img.width, img.height + (31, 16) + """ # Create the output image img = Image.new("RGB", (len(cells[0]), len(cells))) pixels = img.load() @@ -48,4 +71,4 @@ img = generate_image(CELLS) # Uncomment to save the image # img.save(f"rule_{rule_num}.png") - img.show()+ img.show()
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) modulus = np.vectorize(lambda x: x % 36) to_int = np.vectorize(round) def __init__(self, encrypt_key: np.ndarray) -> None: self.encrypt_key = self.modulus(encrypt_key) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key self.break_key = encrypt_key.shape[0] def replace_letters(self, letter: str) -> int: return self.key_string.index(letter) def replace_digits(self, num: int) -> str: return self.key_string[int(num)] def check_determinant(self) -> None: det = round(np.linalg.det(self.encrypt_key)) if det < 0: det = det % len(self.key_string) req_l = len(self.key_string) if greatest_common_divisor(det, len(self.key_string)) != 1: msg = ( f"determinant modular {req_l} of encryption key({det}) " f"is not co prime w.r.t {req_l}.\nTry another key." ) raise ValueError(msg) def process_text(self, text: str) -> str: chars = [char for char in text.upper() if char in self.key_string] last = chars[-1] while len(chars) % self.break_key != 0: chars.append(last) return "".join(chars) def encrypt(self, text: str) -> str: text = self.process_text(text.upper()) encrypted = "" for i in range(0, len(text) - self.break_key + 1, self.break_key): batch = text[i : i + self.break_key] vec = [self.replace_letters(char) for char in batch] batch_vec = np.array([vec]).T batch_encrypted = self.modulus(self.encrypt_key.dot(batch_vec)).T.tolist()[ 0 ] encrypted_batch = "".join( self.replace_digits(num) for num in batch_encrypted ) encrypted += encrypted_batch return encrypted def make_decrypt_key(self) -> np.ndarray: det = round(np.linalg.det(self.encrypt_key)) if det < 0: det = det % len(self.key_string) det_inv = None for i in range(len(self.key_string)): if (det * i) % len(self.key_string) == 1: det_inv = i break inv_key = ( det_inv * np.linalg.det(self.encrypt_key) * np.linalg.inv(self.encrypt_key) ) return self.to_int(self.modulus(inv_key)) def decrypt(self, text: str) -> str: decrypt_key = self.make_decrypt_key() text = self.process_text(text.upper()) decrypted = "" for i in range(0, len(text) - self.break_key + 1, self.break_key): batch = text[i : i + self.break_key] vec = [self.replace_letters(char) for char in batch] batch_vec = np.array([vec]).T batch_decrypted = self.modulus(decrypt_key.dot(batch_vec)).T.tolist()[0] decrypted_batch = "".join( self.replace_digits(num) for num in batch_decrypted ) decrypted += decrypted_batch return decrypted def main() -> None: n = int(input("Enter the order of the encryption key: ")) hill_matrix = [] print("Enter each row of the encryption key with space separated integers") for _ in range(n): row = [int(x) for x in input().split()] hill_matrix.append(row) hc = HillCipher(np.array(hill_matrix)) print("Would you like to encrypt or decrypt some text? (1 or 2)") option = input("\n1. Encrypt\n2. Decrypt\n") if option == "1": text_e = input("What text would you like to encrypt?: ") print("Your encrypted text is:") print(hc.encrypt(text_e)) elif option == "2": text_d = input("What text would you like to decrypt?: ") print("Your decrypted text is:") print(hc.decrypt(text_d)) if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -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 divided into batches of length N and converted to numerical vectors +by a simple mapping starting with A=0 and so on. + +The key is then multiplied with the newly created batch vector to obtain the +encoded vector. After each multiplication modular 36 calculations are performed +on the vectors so as to bring the numbers between 0 and 36 and then mapped with +their corresponding alphanumerics. + +While decrypting, the decrypting key is found which is the inverse of the +encrypting key modular 36. The same process is repeated for decrypting to get +the original message back. + +Constraints: +The determinant of the encryption key matrix must be relatively prime w.r.t 36. + +Note: +This implementation only considers alphanumerics in the text. If the length of +the text to be encrypted is not a multiple of the break key(the length of one +batch of letters), the last character of the text is added to the text until the +length of the text reaches a multiple of the break_key. So the text after +decrypting might be a little different than the original text. + +References: +https://apprendre-en-ligne.net/crypto/hill/Hillciph.pdf +https://www.youtube.com/watch?v=kfmNeskzs2o +https://www.youtube.com/watch?v=4RhLNDqcjpA + +""" import string @@ -17,17 +54,40 @@ to_int = np.vectorize(round) def __init__(self, encrypt_key: np.ndarray) -> None: + """ + encrypt_key is an NxN numpy array + """ self.encrypt_key = self.modulus(encrypt_key) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key self.break_key = encrypt_key.shape[0] def replace_letters(self, letter: str) -> int: + """ + >>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]])) + >>> hill_cipher.replace_letters('T') + 19 + >>> hill_cipher.replace_letters('0') + 26 + """ return self.key_string.index(letter) def replace_digits(self, num: int) -> str: + """ + >>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]])) + >>> hill_cipher.replace_digits(19) + 'T' + >>> hill_cipher.replace_digits(26) + '0' + >>> hill_cipher.replace_digits(26.1) + '0' + """ return self.key_string[int(num)] def check_determinant(self) -> None: + """ + >>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]])) + >>> hill_cipher.check_determinant() + """ det = round(np.linalg.det(self.encrypt_key)) if det < 0: @@ -42,6 +102,13 @@ raise ValueError(msg) def process_text(self, text: str) -> str: + """ + >>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]])) + >>> hill_cipher.process_text('Testing Hill Cipher') + 'TESTINGHILLCIPHERR' + >>> hill_cipher.process_text('hello') + 'HELLOO' + """ chars = [char for char in text.upper() if char in self.key_string] last = chars[-1] @@ -51,6 +118,13 @@ return "".join(chars) def encrypt(self, text: str) -> str: + """ + >>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]])) + >>> hill_cipher.encrypt('testing hill cipher') + 'WHXYJOLM9C6XT085LL' + >>> hill_cipher.encrypt('hello') + '85FF00' + """ text = self.process_text(text.upper()) encrypted = "" @@ -69,6 +143,12 @@ return encrypted def make_decrypt_key(self) -> np.ndarray: + """ + >>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]])) + >>> hill_cipher.make_decrypt_key() + array([[ 6, 25], + [ 5, 26]]) + """ det = round(np.linalg.det(self.encrypt_key)) if det < 0: @@ -86,6 +166,13 @@ return self.to_int(self.modulus(inv_key)) def decrypt(self, text: str) -> str: + """ + >>> hill_cipher = HillCipher(np.array([[2, 5], [1, 6]])) + >>> hill_cipher.decrypt('WHXYJOLM9C6XT085LL') + 'TESTINGHILLCIPHERR' + >>> hill_cipher.decrypt('85FF00') + 'HELLOO' + """ decrypt_key = self.make_decrypt_key() text = self.process_text(text.upper()) decrypted = "" @@ -131,4 +218,4 @@ doctest.testmod() - main()+ main()
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(8) for d in data.decode("utf-8")) null_values = (32 * ((len(binary_data) // 32) + 1) - len(binary_data)) // 8 binary_data = binary_data.ljust(32 * ((len(binary_data) // 32) + 1), "0") b85_chunks = [int(_s, 2) for _s in map("".join, zip(*[iter(binary_data)] * 32))] result = "".join(_base10_to_85(chunk)[::-1] for chunk in b85_chunks) return bytes(result[:-null_values] if null_values % 4 != 0 else result, "utf-8") def ascii85_decode(data: bytes) -> bytes: null_values = 5 * ((len(data) // 5) + 1) - len(data) binary_data = data.decode("utf-8") + "u" * null_values b85_chunks = map("".join, zip(*[iter(binary_data)] * 5)) b85_segments = [[ord(_s) - 33 for _s in chunk] for chunk in b85_chunks] results = [bin(_base85_to_10(chunk))[2::].zfill(32) for chunk in b85_segments] char_chunks = [ [chr(int(_s, 2)) for _s in map("".join, zip(*[iter(r)] * 8))] for r in results ] result = "".join("".join(char) for char in char_chunks) offset = int(null_values % 5 == 0) return bytes(result[: offset - null_values], "utf-8") if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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#' + >>> ascii85_encode(b"base 85") + b'@UX=h+?24' + """ binary_data = "".join(bin(ord(d))[2:].zfill(8) for d in data.decode("utf-8")) null_values = (32 * ((len(binary_data) // 32) + 1) - len(binary_data)) // 8 binary_data = binary_data.ljust(32 * ((len(binary_data) // 32) + 1), "0") @@ -18,6 +31,14 @@ def ascii85_decode(data: bytes) -> bytes: + """ + >>> ascii85_decode(b"") + b'' + >>> ascii85_decode(b"0etOA2#") + b'12345' + >>> ascii85_decode(b"@UX=h+?24") + b'base 85' + """ null_values = 5 * ((len(data) // 5) + 1) - len(data) binary_data = data.decode("utf-8") + "u" * null_values b85_chunks = map("".join, zip(*[iter(binary_data)] * 5)) @@ -34,4 +55,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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. +Following is the truth table of a XOR Gate: + ------------------------------ + | Input | Output | + ------------------------------ + | 0 | 1 | + | 1 | 0 | + ------------------------------ +Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ +""" + + +def not_gate(input_1: int) -> int: + """ + Calculate NOT of the input values + >>> not_gate(0) + 1 + >>> not_gate(1) + 0 + """ + + return 1 if input_1 == 0 else 0 + + +if __name__ == "__main__": + import doctest + + doctest.testmod()
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 output def atbash(sequence: str) -> str: letters = string.ascii_letters letters_reversed = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(c)] if c in letters else c for c in sequence ) def benchmark() -> None: from timeit import timeit print("Running performance benchmarks...") setup = "from string import printable ; from __main__ import atbash, atbash_slow" print(f"> atbash_slow(): {timeit('atbash_slow(printable)', setup=setup)} seconds") print(f"> atbash(): {timeit('atbash(printable)', setup=setup)} seconds") if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"{example} encrypted in atbash: {atbash(example)}") benchmark()
--- +++ @@ -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,6 +24,13 @@ def atbash(sequence: str) -> str: + """ + >>> atbash("ABCDEFG") + 'ZYXWVUT' + + >>> atbash("aW;;123BX") + 'zD;;123YC' + """ letters = string.ascii_letters letters_reversed = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( @@ -24,6 +39,7 @@ def benchmark() -> None: + """Let's benchmark our functions side-by-side...""" from timeit import timeit print("Running performance benchmarks...") @@ -35,4 +51,4 @@ if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"{example} encrypted in atbash: {atbash(example)}") - benchmark()+ benchmark()
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..100..00 +n - 1 = 0..011..11 + +n & (n - 1) - no intersections = 0 +""" def is_power_of_two(number: int) -> bool: + """ + Return True if this number is power of 2 or False otherwise. + + >>> is_power_of_two(0) + True + >>> is_power_of_two(1) + True + >>> is_power_of_two(2) + True + >>> is_power_of_two(4) + True + >>> is_power_of_two(6) + False + >>> is_power_of_two(8) + True + >>> is_power_of_two(17) + False + >>> is_power_of_two(-1) + Traceback (most recent call last): + ... + ValueError: number must not be negative + >>> is_power_of_two(1.2) + Traceback (most recent call last): + ... + TypeError: unsupported operand type(s) for &: 'float' and 'float' + + # Test all powers of 2 from 0 to 10,000 + >>> all(is_power_of_two(int(2 ** i)) for i in range(10000)) + True + """ if number < 0: raise ValueError("number must not be negative") return number & (number - 1) == 0 @@ -9,4 +54,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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", "r": "BAAAA", "s": "BAAAB", "t": "BAABA", "u": "BAABB", "v": "BBBAB", "w": "BABAA", "x": "BABAB", "y": "BABBA", "z": "BABBB", " ": " ", } decode_dict = {value: key for key, value in encode_dict.items()} def encode(word: str) -> str: encoded = "" for letter in word.lower(): if letter.isalpha() or letter == " ": encoded += encode_dict[letter] else: raise Exception("encode() accepts only letters of the alphabet and spaces") return encoded def decode(coded: str) -> str: if set(coded) - {"A", "B", " "} != set(): raise Exception("decode() accepts only 'A', 'B' and spaces") decoded = "" for word in coded.split(): while len(word) != 0: decoded += decode_dict[word[:5]] word = word[5:] decoded += " " return decoded.strip() if __name__ == "__main__": from doctest import testmod testmod()
--- +++ @@ -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") + 'AABBBAABAAABABAABABAABBAB' + >>> encode("hello world") + 'AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB' + >>> encode("hello world!") + Traceback (most recent call last): + ... + Exception: encode() accepts only letters of the alphabet and spaces + """ encoded = "" for letter in word.lower(): if letter.isalpha() or letter == " ": @@ -44,6 +60,18 @@ def decode(coded: str) -> str: + """ + Decodes from Baconian cipher + + >>> decode("AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB") + 'hello world' + >>> decode("AABBBAABAAABABAABABAABBAB") + 'hello' + >>> decode("AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB!") + Traceback (most recent call last): + ... + Exception: decode() accepts only 'A', 'B' and spaces + """ if set(coded) - {"A", "B", " "} != set(): raise Exception("decode() accepts only 'A', 'B' and spaces") decoded = "" @@ -58,4 +86,4 @@ if __name__ == "__main__": from doctest import testmod - testmod()+ testmod()
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 in list(data)]) def base16_decode(data: str) -> bytes: # Check data validity, following RFC3548 # https://www.ietf.org/rfc/rfc3548.txt if (len(data) % 2) != 0: raise ValueError( """Base16 encoded data is invalid: Data does not have an even number of hex digits.""" ) # Check the character set - the standard base16 alphabet # is uppercase according to RFC3548 section 6 if not set(data) <= set("0123456789ABCDEF"): raise ValueError( """Base16 encoded data is invalid: Data is not uppercase hex or it contains invalid characters.""" ) # For every two hexadecimal digits (= a byte), turn it into an integer. # Then, string the result together into bytes, and return it. return bytes(int(data[i] + data[i + 1], 16) for i in range(0, len(data), 2)) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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 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. @@ -6,6 +16,31 @@ def base16_decode(data: str) -> bytes: + """ + Decodes the given base16 encoded data into bytes. + + >>> base16_decode('48656C6C6F20576F726C6421') + b'Hello World!' + >>> base16_decode('48454C4C4F20574F524C4421') + b'HELLO WORLD!' + >>> base16_decode('') + b'' + >>> base16_decode('486') + Traceback (most recent call last): + ... + ValueError: Base16 encoded data is invalid: + Data does not have an even number of hex digits. + >>> base16_decode('48656c6c6f20576f726c6421') + Traceback (most recent call last): + ... + ValueError: Base16 encoded data is invalid: + Data is not uppercase hex or it contains invalid characters. + >>> base16_decode('This is not base64 encoded data.') + Traceback (most recent call last): + ... + ValueError: Base16 encoded data is invalid: + Data is not uppercase hex or it contains invalid characters. + """ # Check data validity, following RFC3548 # https://www.ietf.org/rfc/rfc3548.txt if (len(data) % 2) != 0: @@ -28,4 +63,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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 -------------------------- rotor1 = "EGZWVONAHDCLFQMSIPJBYUKXTR" rotor2 = "FOBHMDKEXQNRAULPGSJVTYICZW" rotor3 = "ZJXESIUQLHAVRMDOYGTNFWPBKC" # reflector -------------------------- reflector = { "A": "N", "N": "A", "B": "O", "O": "B", "C": "P", "P": "C", "D": "Q", "Q": "D", "E": "R", "R": "E", "F": "S", "S": "F", "G": "T", "T": "G", "H": "U", "U": "H", "I": "V", "V": "I", "J": "W", "W": "J", "K": "X", "X": "K", "L": "Y", "Y": "L", "M": "Z", "Z": "M", } # -------------------------- extra rotors -------------------------- rotor4 = "RMDJXFUWGISLHVTCQNKYPBEZOA" rotor5 = "SGLCPQWZHKXAREONTFBVIYJUDM" rotor6 = "HVSICLTYKQUBXDWAJZOMFGPREN" rotor7 = "RZWQHFMVDBKICJLNTUXAGYPSOE" rotor8 = "LFKIJODBEGAMQPXVUHYSTCZRWN" rotor9 = "KOAEGVDHXPQZMLFTYWJNBRCIUS" def _validator( rotpos: RotorPositionT, rotsel: RotorSelectionT, pb: str ) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: # Checks if there are 3 unique rotors if (unique_rotsel := len(set(rotsel))) < 3: msg = f"Please use 3 unique rotors (not {unique_rotsel})" raise Exception(msg) # Checks if rotor positions are valid rotorpos1, rotorpos2, rotorpos3 = rotpos if not 0 < rotorpos1 <= len(abc): msg = f"First rotor position is not within range of 1..26 ({rotorpos1}" raise ValueError(msg) if not 0 < rotorpos2 <= len(abc): msg = f"Second rotor position is not within range of 1..26 ({rotorpos2})" raise ValueError(msg) if not 0 < rotorpos3 <= len(abc): msg = f"Third rotor position is not within range of 1..26 ({rotorpos3})" raise ValueError(msg) # Validates string and returns dict pbdict = _plugboard(pb) return rotpos, rotsel, pbdict def _plugboard(pbstring: str) -> dict[str, str]: # tests the input string if it # a) is type string # b) has even length (so pairs can be made) if not isinstance(pbstring, str): msg = f"Plugboard setting isn't type string ({type(pbstring)})" raise TypeError(msg) elif len(pbstring) % 2 != 0: msg = f"Odd number of symbols ({len(pbstring)})" raise Exception(msg) elif pbstring == "": return {} pbstring.replace(" ", "") # Checks if all characters are unique tmppbl = set() for i in pbstring: if i not in abc: msg = f"'{i}' not in list of symbols" raise Exception(msg) elif i in tmppbl: msg = f"Duplicate symbol ({i})" raise Exception(msg) else: tmppbl.add(i) del tmppbl # Created the dictionary pb = {} for j in range(0, len(pbstring) - 1, 2): pb[pbstring[j]] = pbstring[j + 1] pb[pbstring[j + 1]] = pbstring[j] return pb def enigma( text: str, rotor_position: RotorPositionT, rotor_selection: RotorSelectionT = (rotor1, rotor2, rotor3), plugb: str = "", ) -> str: text = text.upper() rotor_position, rotor_selection, plugboard = _validator( rotor_position, rotor_selection, plugb.upper() ) rotorpos1, rotorpos2, rotorpos3 = rotor_position rotor1, rotor2, rotor3 = rotor_selection rotorpos1 -= 1 rotorpos2 -= 1 rotorpos3 -= 1 result = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: symbol = plugboard[symbol] # rotor ra -------------------------- index = abc.index(symbol) + rotorpos1 symbol = rotor1[index % len(abc)] # rotor rb -------------------------- index = abc.index(symbol) + rotorpos2 symbol = rotor2[index % len(abc)] # rotor rc -------------------------- index = abc.index(symbol) + rotorpos3 symbol = rotor3[index % len(abc)] # reflector -------------------------- # this is the reason you don't need another machine to decipher symbol = reflector[symbol] # 2nd rotors symbol = abc[rotor3.index(symbol) - rotorpos3] symbol = abc[rotor2.index(symbol) - rotorpos2] symbol = abc[rotor1.index(symbol) - rotorpos1] # 2nd plugboard if symbol in plugboard: symbol = plugboard[symbol] # moves/resets rotor positions rotorpos1 += 1 if rotorpos1 >= len(abc): rotorpos1 = 0 rotorpos2 += 1 if rotorpos2 >= len(abc): rotorpos2 = 0 rotorpos3 += 1 if rotorpos3 >= len(abc): rotorpos3 = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(symbol) return "".join(result) if __name__ == "__main__": message = "This is my Python script that emulates the Enigma machine from WWII." rotor_pos = (1, 1, 1) pb = "pictures" rotor_sel = (rotor2, rotor4, rotor8) en = enigma(message, rotor_pos, rotor_sel, pb) print("Encrypted message:", en) print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb))
--- +++ @@ -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 includes: + +- ``enigma`` function +- showcase of function usage +- ``9`` randomly generated rotors +- reflector (aka static rotor) +- original alphabet + +Created by TrapinchO +""" from __future__ import annotations @@ -56,6 +74,19 @@ def _validator( rotpos: RotorPositionT, rotsel: RotorSelectionT, pb: str ) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: + """ + Checks if the values can be used for the ``enigma`` function + + >>> _validator((1,1,1), (rotor1, rotor2, rotor3), 'POLAND') + ((1, 1, 1), ('EGZWVONAHDCLFQMSIPJBYUKXTR', 'FOBHMDKEXQNRAULPGSJVTYICZW', \ +'ZJXESIUQLHAVRMDOYGTNFWPBKC'), \ +{'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'}) + + :param rotpos: rotor_positon + :param rotsel: rotor_selection + :param pb: plugb -> validated and transformed + :return: (`rotpos`, `rotsel`, `pb`) + """ # Checks if there are 3 unique rotors if (unique_rotsel := len(set(rotsel))) < 3: @@ -81,6 +112,21 @@ def _plugboard(pbstring: str) -> dict[str, str]: + """ + https://en.wikipedia.org/wiki/Enigma_machine#Plugboard + + >>> _plugboard('PICTURES') + {'P': 'I', 'I': 'P', 'C': 'T', 'T': 'C', 'U': 'R', 'R': 'U', 'E': 'S', 'S': 'E'} + >>> _plugboard('POLAND') + {'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'} + + In the code, ``pb`` stands for ``plugboard`` + + Pairs can be separated by spaces + + :param pbstring: string containing plugboard setting for the Enigma machine + :return: dictionary containing converted pairs + """ # tests the input string if it # a) is type string @@ -124,6 +170,58 @@ rotor_selection: RotorSelectionT = (rotor1, rotor2, rotor3), plugb: str = "", ) -> str: + """ + The only difference with real-world enigma is that ``I`` allowed string input. + All characters are converted to uppercase. (non-letter symbol are ignored) + + | How it works: + | (for every letter in the message) + + - Input letter goes into the plugboard. + If it is connected to another one, switch it. + + - Letter goes through ``3`` rotors. + Each rotor can be represented as ``2`` sets of symbol, where one is shuffled. + Each symbol from the first set has corresponding symbol in + the second set and vice versa. + + example:: + + | ABCDEFGHIJKLMNOPQRSTUVWXYZ | e.g. F=D and D=F + | VKLEPDBGRNWTFCJOHQAMUZYIXS | + + - Symbol then goes through reflector (static rotor). + There it is switched with paired symbol. + The reflector can be represented as ``2`` sets, each with half of the alphanet. + There are usually ``10`` pairs of letters. + + Example:: + + | ABCDEFGHIJKLM | e.g. E is paired to X + | ZYXWVUTSRQPON | so when E goes in X goes out and vice versa + + - Letter then goes through the rotors again + + - If the letter is connected to plugboard, it is switched. + + - Return the letter + + >>> enigma('Hello World!', (1, 2, 1), plugb='pictures') + 'KORYH JUHHI!' + >>> enigma('KORYH, juhhi!', (1, 2, 1), plugb='pictures') + 'HELLO, WORLD!' + >>> enigma('hello world!', (1, 1, 1), plugb='pictures') + 'FPNCZ QWOBU!' + >>> enigma('FPNCZ QWOBU', (1, 1, 1), plugb='pictures') + 'HELLO WORLD' + + + :param text: input message + :param rotor_position: tuple with ``3`` values in range ``1``.. ``26`` + :param rotor_selection: tuple with ``3`` rotors + :param plugb: string containing plugboard configuration (default ``''``) + :return: en/decrypted string + """ text = text.upper() rotor_position, rotor_selection, plugboard = _validator( @@ -200,4 +298,4 @@ en = enigma(message, rotor_pos, rotor_sel, pb) print("Encrypted message:", en) - print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb))+ print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb))
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 number with all odd bits set to 1 odd_bits = num & 0x55555555 # Right shift even bits and left shift odd bits and swap them return even_bits >> 1 | odd_bits << 1 if __name__ == "__main__": import doctest doctest.testmod() for i in (-1, 0, 1, 2, 3, 4, 23, 24): print(show_bits(i, swap_odd_even_bits(i)), "\n")
--- +++ @@ -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 AND operations to separate the even bits (0, 2, 4, 6, etc.) and + odd bits (1, 3, 5, 7, etc.) in the input number. + 2. We then right-shift the even bits by 1 position and left-shift the odd bits by + 1 position to swap them. + 3. Finally, we combine the swapped even and odd bits using a bitwise OR operation + to obtain the final result. + >>> print(show_bits(0, swap_odd_even_bits(0))) + 0: 00000000 + 0: 00000000 + >>> print(show_bits(1, swap_odd_even_bits(1))) + 1: 00000001 + 2: 00000010 + >>> print(show_bits(2, swap_odd_even_bits(2))) + 2: 00000010 + 1: 00000001 + >>> print(show_bits(3, swap_odd_even_bits(3))) + 3: 00000011 + 3: 00000011 + >>> print(show_bits(4, swap_odd_even_bits(4))) + 4: 00000100 + 8: 00001000 + >>> print(show_bits(5, swap_odd_even_bits(5))) + 5: 00000101 + 10: 00001010 + >>> print(show_bits(6, swap_odd_even_bits(6))) + 6: 00000110 + 9: 00001001 + >>> print(show_bits(23, swap_odd_even_bits(23))) + 23: 00010111 + 43: 00101011 + """ # Get all even bits - 0xAAAAAAAA is a 32-bit number with all even bits set to 1 even_bits = num & 0xAAAAAAAA @@ -18,4 +55,4 @@ doctest.testmod() for i in (-1, 0, 1, 2, 3, 4, 23, 24): - print(show_bits(i, swap_odd_even_bits(i)), "\n")+ print(show_bits(i, swap_odd_even_bits(i)), "\n")
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) print("Decoded:", decode(encoded)) if __name__ == "__main__": main()
--- +++ @@ -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]: + """ + >>> encode("myname") + [13, 25, 14, 1, 13, 5] + """ return [ord(elem) - 96 for elem in plain] def decode(encoded: list[int]) -> str: + """ + >>> decode([13, 25, 14, 1, 13, 5]) + 'myname' + """ return "".join(chr(elem + 96) for elem in encoded) @@ -17,4 +32,4 @@ if __name__ == "__main__": - main()+ main()
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(message) i = 0 while True: if x == i: i = 0 if len(key) == len(message): break key += key[i] i += 1 return key # This function returns the encrypted text # generated with the help of the key def cipher_text(message: str, key_new: str) -> str: cipher_text = "" i = 0 for letter in message: if letter == " ": cipher_text += " " else: x = (dict1[letter] - dict1[key_new[i]]) % 26 i += 1 cipher_text += dict2[x] return cipher_text # This function decrypts the encrypted text # and returns the original text def original_text(cipher_text: str, key_new: str) -> str: or_txt = "" i = 0 for letter in cipher_text: if letter == " ": or_txt += " " else: x = (dict1[letter] + dict1[key_new[i]] + 26) % 26 i += 1 or_txt += dict2[x] return or_txt def main() -> None: message = "THE GERMAN ATTACK" key = "SECRET" key_new = generate_key(message, key) s = cipher_text(message, key_new) print(f"Encrypted Text = {s}") print(f"Original Text = {original_text(s, key_new)}") if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -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") + 'SECRETSECRETSECRE' + """ x = len(message) i = 0 while True: @@ -24,6 +31,10 @@ # This function returns the encrypted text # generated with the help of the key def cipher_text(message: str, key_new: str) -> str: + """ + >>> cipher_text("THE GERMAN ATTACK","SECRETSECRETSECRE") + 'BDC PAYUWL JPAIYI' + """ cipher_text = "" i = 0 for letter in message: @@ -39,6 +50,10 @@ # This function decrypts the encrypted text # and returns the original text def original_text(cipher_text: str, key_new: str) -> str: + """ + >>> original_text("BDC PAYUWL JPAIYI","SECRETSECRETSECRE") + 'THE GERMAN ATTACK' + """ or_txt = "" i = 0 for letter in cipher_text: @@ -64,4 +79,4 @@ import doctest doctest.testmod() - main()+ main()
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.board = [[True] * width for _ in range(height)] self.ant_position: tuple[int, int] = (width // 2, height // 2) # Initially pointing left (similar to the wikipedia image) # (0 = 0° | 1 = 90° | 2 = 180 ° | 3 = 270°) self.ant_direction: int = 3 def move_ant(self, axes: plt.Axes | None, display: bool, _frame: int) -> None: directions = { 0: (-1, 0), # 0° 1: (0, 1), # 90° 2: (1, 0), # 180° 3: (0, -1), # 270° } x, y = self.ant_position # Turn clockwise or anti-clockwise according to colour of square if self.board[x][y] is True: # The square is white so turn 90° clockwise self.ant_direction = (self.ant_direction + 1) % 4 else: # The square is black so turn 90° anti-clockwise self.ant_direction = (self.ant_direction - 1) % 4 # Move ant move_x, move_y = directions[self.ant_direction] self.ant_position = (x + move_x, y + move_y) # Flip colour of square self.board[x][y] = not self.board[x][y] if display and axes: # Display the board on the axes axes.get_xaxis().set_ticks([]) axes.get_yaxis().set_ticks([]) axes.imshow(self.board, cmap="gray", interpolation="nearest") def display(self, frames: int = 100_000) -> None: fig, ax = plt.subplots() # Assign animation to a variable to prevent it from getting garbage collected self.animation = FuncAnimation( fig, partial(self.move_ant, ax, True), frames=frames, interval=1 ) plt.show() if __name__ == "__main__": import doctest doctest.testmod() LangtonsAnt(WIDTH, HEIGHT).display()
--- +++ @@ -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. + + >>> la = LangtonsAnt(2, 2) + >>> la.board + [[True, True], [True, True]] + >>> la.ant_position + (1, 1) + """ def __init__(self, width: int, height: int) -> None: # Each square is either True or False where True is white and False is black @@ -20,6 +35,25 @@ self.ant_direction: int = 3 def move_ant(self, axes: plt.Axes | None, display: bool, _frame: int) -> None: + """ + Performs three tasks: + 1. The ant turns either clockwise or anti-clockwise according to the colour + of the square that it is currently on. If the square is white, the ant + turns clockwise, and if the square is black the ant turns anti-clockwise + 2. The ant moves one square in the direction that it is currently facing + 3. The square the ant was previously on is inverted (White -> Black and + Black -> White) + + If display is True, the board will also be displayed on the axes + + >>> la = LangtonsAnt(2, 2) + >>> la.move_ant(None, True, 0) + >>> la.board + [[True, True], [True, False]] + >>> la.move_ant(None, True, 0) + >>> la.board + [[True, False], [True, False]] + """ directions = { 0: (-1, 0), # 0° 1: (0, 1), # 90° @@ -50,6 +84,12 @@ axes.imshow(self.board, cmap="gray", interpolation="nearest") def display(self, frames: int = 100_000) -> None: + """ + Displays the board without delay in a matplotlib plot + to visually understand and track the ant. + + >>> _ = LangtonsAnt(WIDTH, HEIGHT) + """ fig, ax = plt.subplots() # Assign animation to a variable to prevent it from getting garbage collected self.animation = FuncAnimation( @@ -63,4 +103,4 @@ doctest.testmod() - LangtonsAnt(WIDTH, HEIGHT).display()+ LangtonsAnt(WIDTH, HEIGHT).display()
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: raise ValueError("key is empty") key += plaintext plaintext = plaintext.lower() key = key.lower() plaintext_iterator = 0 key_iterator = 0 ciphertext = "" while plaintext_iterator < len(plaintext): if ( ord(plaintext[plaintext_iterator]) < 97 or ord(plaintext[plaintext_iterator]) > 122 ): ciphertext += plaintext[plaintext_iterator] plaintext_iterator += 1 elif ord(key[key_iterator]) < 97 or ord(key[key_iterator]) > 122: key_iterator += 1 else: ciphertext += chr( ( (ord(plaintext[plaintext_iterator]) - 97 + ord(key[key_iterator])) - 97 ) % 26 + 97 ) key_iterator += 1 plaintext_iterator += 1 return ciphertext def decrypt(ciphertext: str, key: str) -> str: if not isinstance(ciphertext, str): raise TypeError("ciphertext must be a string") if not isinstance(key, str): raise TypeError("key must be a string") if not ciphertext: raise ValueError("ciphertext is empty") if not key: raise ValueError("key is empty") key = key.lower() ciphertext_iterator = 0 key_iterator = 0 plaintext = "" while ciphertext_iterator < len(ciphertext): if ( ord(ciphertext[ciphertext_iterator]) < 97 or ord(ciphertext[ciphertext_iterator]) > 122 ): plaintext += ciphertext[ciphertext_iterator] else: plaintext += chr( (ord(ciphertext[ciphertext_iterator]) - ord(key[key_iterator])) % 26 + 97 ) key += chr( (ord(ciphertext[ciphertext_iterator]) - ord(key[key_iterator])) % 26 + 97 ) key_iterator += 1 ciphertext_iterator += 1 return plaintext if __name__ == "__main__": import doctest doctest.testmod() operation = int(input("Type 1 to encrypt or 2 to decrypt:")) if operation == 1: plaintext = input("Typeplaintext to be encrypted:\n") key = input("Type the key:\n") print(encrypt(plaintext, key)) elif operation == 2: ciphertext = input("Type the ciphertext to be decrypted:\n") key = input("Type the key:\n") print(decrypt(ciphertext, key)) decrypt("jsqqs avvwo", "coffee")
--- +++ @@ -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 text or, more commonly, +by adding a short primer key to the front of the message. +""" def encrypt(plaintext: str, key: str) -> str: + """ + Encrypt a given `plaintext` (string) and `key` (string), returning the + encrypted ciphertext. + + >>> encrypt("hello world", "coffee") + 'jsqqs avvwo' + >>> encrypt("coffee is good as python", "TheAlgorithms") + 'vvjfpk wj ohvp su ddylsv' + >>> encrypt("coffee is good as python", 2) + Traceback (most recent call last): + ... + TypeError: key must be a string + >>> encrypt("", "TheAlgorithms") + Traceback (most recent call last): + ... + ValueError: plaintext is empty + >>> encrypt("coffee is good as python", "") + Traceback (most recent call last): + ... + ValueError: key is empty + >>> encrypt(527.26, "TheAlgorithms") + Traceback (most recent call last): + ... + TypeError: plaintext must be a string + """ if not isinstance(plaintext, str): raise TypeError("plaintext must be a string") if not isinstance(key, str): @@ -41,6 +75,31 @@ def decrypt(ciphertext: str, key: str) -> str: + """ + Decrypt a given `ciphertext` (string) and `key` (string), returning the decrypted + ciphertext. + + >>> decrypt("jsqqs avvwo", "coffee") + 'hello world' + >>> decrypt("vvjfpk wj ohvp su ddylsv", "TheAlgorithms") + 'coffee is good as python' + >>> decrypt("vvjfpk wj ohvp su ddylsv", "") + Traceback (most recent call last): + ... + ValueError: key is empty + >>> decrypt(527.26, "TheAlgorithms") + Traceback (most recent call last): + ... + TypeError: ciphertext must be a string + >>> decrypt("", "TheAlgorithms") + Traceback (most recent call last): + ... + ValueError: ciphertext is empty + >>> decrypt("vvjfpk wj ohvp su ddylsv", 2) + Traceback (most recent call last): + ... + TypeError: key must be a string + """ if not isinstance(ciphertext, str): raise TypeError("ciphertext must be a string") if not isinstance(key, str): @@ -88,4 +147,4 @@ ciphertext = input("Type the ciphertext to be decrypted:\n") key = input("Type the key:\n") print(decrypt(ciphertext, key)) - decrypt("jsqqs avvwo", "coffee")+ decrypt("jsqqs avvwo", "coffee")
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_to_numbers(self, letter: str) -> np.ndarray: index1, index2 = np.where(letter == self.SQUARE) indexes = np.concatenate([index1 + 1, index2 + 1]) return indexes def numbers_to_letter(self, index1: int, index2: int) -> str: letter = self.SQUARE[index1 - 1, index2 - 1] return letter def encode(self, message: str) -> str: message = message.lower() message = message.replace(" ", "") message = message.replace("j", "i") first_step = np.empty((2, len(message))) for letter_index in range(len(message)): numbers = self.letter_to_numbers(message[letter_index]) first_step[0, letter_index] = numbers[0] first_step[1, letter_index] = numbers[1] second_step = first_step.reshape(2 * len(message)) encoded_message = "" for numbers_index in range(len(message)): index1 = int(second_step[numbers_index * 2]) index2 = int(second_step[(numbers_index * 2) + 1]) letter = self.numbers_to_letter(index1, index2) encoded_message = encoded_message + letter return encoded_message def decode(self, message: str) -> str: message = message.lower() message.replace(" ", "") first_step = np.empty(2 * len(message)) for letter_index in range(len(message)): numbers = self.letter_to_numbers(message[letter_index]) first_step[letter_index * 2] = numbers[0] first_step[letter_index * 2 + 1] = numbers[1] second_step = first_step.reshape((2, len(message))) decoded_message = "" for numbers_index in range(len(message)): index1 = int(second_step[0, numbers_index]) index2 = int(second_step[1, numbers_index]) letter = self.numbers_to_letter(index1, index2) decoded_message = decoded_message + letter return decoded_message
--- +++ @@ -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.SQUARE = np.array(SQUARE) def letter_to_numbers(self, letter: str) -> np.ndarray: + """ + Return the pair of numbers that represents the given letter in the + polybius square + + >>> np.array_equal(BifidCipher().letter_to_numbers('a'), [1,1]) + True + + >>> np.array_equal(BifidCipher().letter_to_numbers('u'), [4,5]) + True + """ index1, index2 = np.where(letter == self.SQUARE) indexes = np.concatenate([index1 + 1, index2 + 1]) return indexes def numbers_to_letter(self, index1: int, index2: int) -> str: + """ + Return the letter corresponding to the position [index1, index2] in + the polybius square + + >>> BifidCipher().numbers_to_letter(4, 5) == "u" + True + + >>> BifidCipher().numbers_to_letter(1, 1) == "a" + True + """ letter = self.SQUARE[index1 - 1, index2 - 1] return letter def encode(self, message: str) -> str: + """ + Return the encoded version of message according to the polybius cipher + + >>> BifidCipher().encode('testmessage') == 'qtltbdxrxlk' + True + + >>> BifidCipher().encode('Test Message') == 'qtltbdxrxlk' + True + + >>> BifidCipher().encode('test j') == BifidCipher().encode('test i') + True + """ message = message.lower() message = message.replace(" ", "") message = message.replace("j", "i") @@ -48,6 +86,12 @@ return encoded_message def decode(self, message: str) -> str: + """ + Return the decoded version of message according to the polybius cipher + + >>> BifidCipher().decode('qtltbdxrxlk') == 'testmessage' + True + """ message = message.lower() message.replace(" ", "") first_step = np.empty(2 * len(message)) @@ -64,4 +108,4 @@ letter = self.numbers_to_letter(index1, index2) decoded_message = decoded_message + letter - return decoded_message+ return decoded_message
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 input_string: if character not in alpha: # Append without encryption if character is not in the alphabet result += character else: # Get the index of the new key and make sure it isn't too large new_key = (alpha.index(character) + key) % len(alpha) # Append the encoded character to the alphabet result += alpha[new_key] return result def decrypt(input_string: str, key: int, alphabet: str | None = None) -> str: # Turn on decode mode by making the key negative key *= -1 return encrypt(input_string, key, alphabet) def brute_force(input_string: str, alphabet: str | None = None) -> dict[int, str]: # Set default alphabet to lower and upper case english chars alpha = alphabet or ascii_letters # To store data on all the combinations brute_force_data = {} # Cycle through each combination for key in range(1, len(alpha) + 1): # Decrypt the message and store the result in the data brute_force_data[key] = decrypt(input_string, key, alpha) return brute_force_data if __name__ == "__main__": while True: print(f"\n{'-' * 10}\n Menu\n{'-' * 10}") print(*["1.Encrypt", "2.Decrypt", "3.BruteForce", "4.Quit"], sep="\n") # get user input choice = input("\nWhat would you like to do?: ").strip() or "4" # run functions based on what the user chose if choice not in ("1", "2", "3", "4"): print("Invalid choice, please enter a valid choice") elif choice == "1": input_string = input("Please enter the string to be encrypted: ") key = int(input("Please enter off-set: ").strip()) print(encrypt(input_string, key)) elif choice == "2": input_string = input("Please enter the string to be decrypted: ") key = int(input("Please enter off-set: ").strip()) print(decrypt(input_string, key)) elif choice == "3": input_string = input("Please enter the string to be decrypted: ") brute_force_data = brute_force(input_string) for key, value in brute_force_data.items(): print(f"Key: {key} | Message: {value}") elif choice == "4": print("Goodbye.") break
--- +++ @@ -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 to be encoded + * `key`: the number of letters to shift the message by + + Optional: + + * `alphabet` (``None``): the alphabet used to encode the cipher, if not + specified, the standard english alphabet with upper and lowercase + letters is used + + Returns: + + * A string containing the encoded cipher-text + + More on the caesar cipher + ========================= + + The caesar cipher is named after Julius Caesar who used it when sending + secret military messages to his troops. This is a simple substitution cipher + where every character in the plain-text is shifted by a certain number known + as the "key" or "shift". + + Example: + Say we have the following message: + ``Hello, captain`` + + And our alphabet is made up of lower and uppercase letters: + ``abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`` + + And our shift is ``2`` + + We can then encode the message, one letter at a time. ``H`` would become ``J``, + since ``J`` is two letters away, and so on. If the shift is ever too large, or + our letter is at the end of the alphabet, we just start at the beginning + (``Z`` would shift to ``a`` then ``b`` and so on). + + Our final message would be ``Jgnnq, ecrvckp`` + + Further reading + =============== + + * https://en.m.wikipedia.org/wiki/Caesar_cipher + + Doctests + ======== + + >>> encrypt('The quick brown fox jumps over the lazy dog', 8) + 'bpm yCqks jzwEv nwF rCuxA wDmz Bpm tiHG lwo' + + >>> encrypt('A very large key', 8000) + 's nWjq dSjYW cWq' + + >>> encrypt('a lowercase alphabet', 5, 'abcdefghijklmnopqrstuvwxyz') + 'f qtbjwhfxj fqumfgjy' + """ # Set default alphabet to lower and upper case english chars alpha = alphabet or ascii_letters @@ -25,6 +89,71 @@ def decrypt(input_string: str, key: int, alphabet: str | None = None) -> str: + """ + decrypt + ======= + + Decodes a given string of cipher-text and returns the decoded plain-text + + Parameters: + ----------- + + * `input_string`: the cipher-text that needs to be decoded + * `key`: the number of letters to shift the message backwards by to decode + + Optional: + + * `alphabet` (``None``): the alphabet used to decode the cipher, if not + specified, the standard english alphabet with upper and lowercase + letters is used + + Returns: + + * A string containing the decoded plain-text + + More on the caesar cipher + ========================= + + The caesar cipher is named after Julius Caesar who used it when sending + secret military messages to his troops. This is a simple substitution cipher + where very character in the plain-text is shifted by a certain number known + as the "key" or "shift". Please keep in mind, here we will be focused on + decryption. + + Example: + Say we have the following cipher-text: + ``Jgnnq, ecrvckp`` + + And our alphabet is made up of lower and uppercase letters: + ``abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`` + + And our shift is ``2`` + + To decode the message, we would do the same thing as encoding, but in + reverse. The first letter, ``J`` would become ``H`` (remember: we are decoding) + because ``H`` is two letters in reverse (to the left) of ``J``. We would + continue doing this. A letter like ``a`` would shift back to the end of + the alphabet, and would become ``Z`` or ``Y`` and so on. + + Our final message would be ``Hello, captain`` + + Further reading + =============== + + * https://en.m.wikipedia.org/wiki/Caesar_cipher + + Doctests + ======== + + >>> decrypt('bpm yCqks jzwEv nwF rCuxA wDmz Bpm tiHG lwo', 8) + 'The quick brown fox jumps over the lazy dog' + + >>> decrypt('s nWjq dSjYW cWq', 8000) + 'A very large key' + + >>> decrypt('f qtbjwhfxj fqumfgjy', 5, 'abcdefghijklmnopqrstuvwxyz') + 'a lowercase alphabet' + """ # Turn on decode mode by making the key negative key *= -1 @@ -32,6 +161,54 @@ def brute_force(input_string: str, alphabet: str | None = None) -> dict[int, str]: + """ + brute_force + =========== + + Returns all the possible combinations of keys and the decoded strings in the + form of a dictionary + + Parameters: + ----------- + + * `input_string`: the cipher-text that needs to be used during brute-force + + Optional: + + * `alphabet` (``None``): the alphabet used to decode the cipher, if not + specified, the standard english alphabet with upper and lowercase + letters is used + + More about brute force + ====================== + + Brute force is when a person intercepts a message or password, not knowing + the key and tries every single combination. This is easy with the caesar + cipher since there are only all the letters in the alphabet. The more + complex the cipher, the larger amount of time it will take to do brute force + + Ex: + Say we have a ``5`` letter alphabet (``abcde``), for simplicity and we intercepted + the following message: ``dbc``, + we could then just write out every combination: + ``ecd``... and so on, until we reach a combination that makes sense: + ``cab`` + + Further reading + =============== + + * https://en.wikipedia.org/wiki/Brute_force + + Doctests + ======== + + >>> brute_force("jFyuMy xIH'N vLONy zILwy Gy!")[20] + "Please don't brute force me!" + + >>> brute_force(1) + Traceback (most recent call last): + TypeError: 'int' object is not iterable + """ # Set default alphabet to lower and upper case english chars alpha = alphabet or ascii_letters @@ -76,4 +253,4 @@ elif choice == "4": print("Goodbye.") - break+ break
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 1 (True), if the inputs are same. +It's similar to adding a NOT gate to an XOR gate + +Following is the truth table of a XNOR Gate: + ------------------------------ + | Input 1 | Input 2 | Output | + ------------------------------ + | 0 | 0 | 1 | + | 0 | 1 | 0 | + | 1 | 0 | 0 | + | 1 | 1 | 1 | + ------------------------------ +Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ +""" + + +def xnor_gate(input_1: int, input_2: int) -> int: + """ + Calculate XOR of the input values + >>> xnor_gate(0, 0) + 1 + >>> xnor_gate(0, 1) + 0 + >>> xnor_gate(1, 0) + 0 + >>> xnor_gate(1, 1) + 1 + """ + return 1 if input_1 == input_2 else 0 + + +if __name__ == "__main__": + import doctest + + doctest.testmod()
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, 0, 0, 0, 0], ] # Define blinker example BLINKER = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def new_generation(cells: list[list[int]]) -> list[list[int]]: next_generation = [] for i in range(len(cells)): next_generation_row = [] for j in range(len(cells[i])): # Get the number of live neighbours neighbour_count = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i]) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i]) - 1: neighbour_count += cells[i][j + 1] if i < len(cells) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(cells) - 1: neighbour_count += cells[i + 1][j] if i < len(cells) - 1 and j < len(cells[i]) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. alive = cells[i][j] == 1 if (alive and 2 <= neighbour_count <= 3) or ( not alive and neighbour_count == 3 ): next_generation_row.append(1) else: next_generation_row.append(0) next_generation.append(next_generation_row) return next_generation def generate_images(cells: list[list[int]], frames: int) -> list[Image.Image]: images = [] for _ in range(frames): # Create output image img = Image.new("RGB", (len(cells[0]), len(cells))) pixels = img.load() # Save cells to image for x in range(len(cells)): for y in range(len(cells[0])): colour = 255 - cells[y][x] * 255 pixels[x, y] = (colour, colour, colour) # Save image images.append(img) cells = new_generation(cells) return images if __name__ == "__main__": images = generate_images(GLIDER, 16) images[0].save("out.gif", save_all=True, append_images=images[1:])
--- +++ @@ -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 state of Conway's Game of Life. + >>> new_generation(BLINKER) + [[0, 0, 0], [1, 1, 1], [0, 0, 0]] + """ next_generation = [] for i in range(len(cells)): next_generation_row = [] @@ -61,6 +70,9 @@ def generate_images(cells: list[list[int]], frames: int) -> list[Image.Image]: + """ + Generates a list of images of subsequent Game of Life states. + """ images = [] for _ in range(frames): # Create output image @@ -81,4 +93,4 @@ if __name__ == "__main__": images = generate_images(GLIDER, 16) - images[0].save("out.gif", save_all=True, append_images=images[1:])+ images[0].save("out.gif", save_all=True, append_images=images[1:])
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_using_modulo_operator(number: int) -> int: if number < 0: raise ValueError("the value of input must not be negative") result = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def benchmark() -> None: def do_benchmark(number: int) -> None: setup = "import __main__ as z" print(f"Benchmark when {number = }:") print(f"{get_set_bits_count_using_modulo_operator(number) = }") timing = timeit( f"z.get_set_bits_count_using_modulo_operator({number})", setup=setup ) print(f"timeit() runs in {timing} seconds") print(f"{get_set_bits_count_using_brian_kernighans_algorithm(number) = }") timing = timeit( f"z.get_set_bits_count_using_brian_kernighans_algorithm({number})", setup=setup, ) print(f"timeit() runs in {timing} seconds") for number in (25, 37, 58, 0): do_benchmark(number) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
--- +++ @@ -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 + >>> get_set_bits_count_using_brian_kernighans_algorithm(21) + 3 + >>> get_set_bits_count_using_brian_kernighans_algorithm(58) + 4 + >>> get_set_bits_count_using_brian_kernighans_algorithm(0) + 0 + >>> get_set_bits_count_using_brian_kernighans_algorithm(256) + 1 + >>> get_set_bits_count_using_brian_kernighans_algorithm(-1) + Traceback (most recent call last): + ... + ValueError: the value of input must not be negative + """ if number < 0: raise ValueError("the value of input must not be negative") result = 0 @@ -12,6 +31,25 @@ def get_set_bits_count_using_modulo_operator(number: int) -> int: + """ + Count the number of set bits in a 32 bit integer + >>> get_set_bits_count_using_modulo_operator(25) + 3 + >>> get_set_bits_count_using_modulo_operator(37) + 3 + >>> get_set_bits_count_using_modulo_operator(21) + 3 + >>> get_set_bits_count_using_modulo_operator(58) + 4 + >>> get_set_bits_count_using_modulo_operator(0) + 0 + >>> get_set_bits_count_using_modulo_operator(256) + 1 + >>> get_set_bits_count_using_modulo_operator(-1) + Traceback (most recent call last): + ... + ValueError: the value of input must not be negative + """ if number < 0: raise ValueError("the value of input must not be negative") result = 0 @@ -23,6 +61,10 @@ def benchmark() -> None: + """ + Benchmark code for comparing 2 functions, with different length int values. + Brian Kernighan's algorithm is consistently faster than using modulo_operator. + """ def do_benchmark(number: int) -> None: setup = "import __main__ as z" @@ -48,4 +90,4 @@ import doctest doctest.testmod() - benchmark()+ benchmark()
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) -> None: if mode == "encrypt": if key_a == 1: sys.exit( "The affine cipher becomes weak when key " "A is set to 1. Choose different key" ) if key_b == 0: sys.exit( "The affine cipher becomes weak when key " "B is set to 0. Choose different key" ) if key_a < 0 or key_b < 0 or key_b > len(SYMBOLS) - 1: sys.exit( "Key A must be greater than 0 and key B must " f"be between 0 and {len(SYMBOLS) - 1}." ) if gcd_by_iterative(key_a, len(SYMBOLS)) != 1: sys.exit( f"Key A {key_a} and the symbol set size {len(SYMBOLS)} " "are not relatively prime. Choose a different key." ) def encrypt_message(key: int, message: str) -> str: key_a, key_b = divmod(key, len(SYMBOLS)) check_keys(key_a, key_b, "encrypt") cipher_text = "" for symbol in message: if symbol in SYMBOLS: sym_index = SYMBOLS.find(symbol) cipher_text += SYMBOLS[(sym_index * key_a + key_b) % len(SYMBOLS)] else: cipher_text += symbol return cipher_text def decrypt_message(key: int, message: str) -> str: key_a, key_b = divmod(key, len(SYMBOLS)) check_keys(key_a, key_b, "decrypt") plain_text = "" mod_inverse_of_key_a = cryptomath.find_mod_inverse(key_a, len(SYMBOLS)) for symbol in message: if symbol in SYMBOLS: sym_index = SYMBOLS.find(symbol) plain_text += SYMBOLS[ (sym_index - key_b) * mod_inverse_of_key_a % len(SYMBOLS) ] else: plain_text += symbol return plain_text def get_random_key() -> int: while True: key_b = random.randint(2, len(SYMBOLS)) key_b = random.randint(2, len(SYMBOLS)) if gcd_by_iterative(key_b, len(SYMBOLS)) == 1 and key_b % len(SYMBOLS) != 0: return key_b * len(SYMBOLS) + key_b def main() -> None: message = input("Enter message: ").strip() key = int(input("Enter key [2000 - 9000]: ").strip()) mode = input("Encrypt/Decrypt [E/D]: ").strip().lower() if mode.startswith("e"): mode = "encrypt" translated = encrypt_message(key, message) elif mode.startswith("d"): mode = "decrypt" translated = decrypt_message(key, message) print(f"\n{mode.title()}ed text: \n{translated}") if __name__ == "__main__": import doctest doctest.testmod() # main()
--- +++ @@ -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, key_b = divmod(key, len(SYMBOLS)) check_keys(key_a, key_b, "encrypt") cipher_text = "" @@ -49,6 +54,11 @@ def decrypt_message(key: int, message: str) -> str: + """ + >>> decrypt_message(4545, 'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF' + ... '{xIp~{HL}Gi') + 'The affine cipher is a type of monoalphabetic substitution cipher.' + """ key_a, key_b = divmod(key, len(SYMBOLS)) check_keys(key_a, key_b, "decrypt") plain_text = "" @@ -73,6 +83,12 @@ def main() -> None: + """ + >>> key = get_random_key() + >>> msg = "This is a test!" + >>> decrypt_message(key, encrypt_message(key, msg)) == msg + True + """ message = input("Enter message: ").strip() key = int(input("Enter key [2000 - 9000]: ").strip()) mode = input("Encrypt/Decrypt [E/D]: ").strip().lower() @@ -90,4 +106,4 @@ import doctest doctest.testmod() - # main()+ # main()
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 in the message for symbol in message: if symbol.upper() in chars_a: # encrypt/decrypt the symbol sym_index = chars_a.find(symbol.upper()) if symbol.isupper(): translated += chars_b[sym_index].upper() else: translated += chars_b[sym_index].lower() else: # symbol is not in LETTERS, just add it translated += symbol return translated def encrypt_message(key: str, message: str) -> str: return translate_message(key, message, "encrypt") def decrypt_message(key: str, message: str) -> str: return translate_message(key, message, "decrypt") def main() -> None: message = "Hello World" key = "QWERTYUIOPASDFGHJKLZXCVBNM" mode = "decrypt" # set to 'encrypt' or 'decrypt' if mode == "encrypt": translated = encrypt_message(key, message) elif mode == "decrypt": translated = decrypt_message(key, message) print(f"Using the key {key}, the {mode}ed message is: {translated}") if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -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 mode == "decrypt" else LETTERS translated = "" @@ -25,10 +29,18 @@ def encrypt_message(key: str, message: str) -> str: + """ + >>> encrypt_message("QWERTYUIOPASDFGHJKLZXCVBNM", "Hello World") + 'Pcssi Bidsm' + """ return translate_message(key, message, "encrypt") def decrypt_message(key: str, message: str) -> str: + """ + >>> decrypt_message("QWERTYUIOPASDFGHJKLZXCVBNM", "Hello World") + 'Itssg Vgksr' + """ return translate_message(key, message, "decrypt") @@ -48,4 +60,4 @@ import doctest doctest.testmod() - main()+ main()
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 letter_to_numbers(self, letter: str) -> np.ndarray: index1, index2 = np.where(letter == self.SQUARE) indexes = np.concatenate([index1 + 1, index2 + 1]) return indexes def numbers_to_letter(self, index1: int, index2: int) -> str: return self.SQUARE[index1 - 1, index2 - 1] def encode(self, message: str) -> str: message = message.lower() message = message.replace("j", "i") encoded_message = "" for letter_index in range(len(message)): if message[letter_index] != " ": numbers = self.letter_to_numbers(message[letter_index]) encoded_message = encoded_message + str(numbers[0]) + str(numbers[1]) elif message[letter_index] == " ": encoded_message = encoded_message + " " return encoded_message def decode(self, message: str) -> str: message = message.replace(" ", " ") decoded_message = "" for numbers_index in range(int(len(message) / 2)): if message[numbers_index * 2] != " ": index1 = message[numbers_index * 2] index2 = message[numbers_index * 2 + 1] letter = self.numbers_to_letter(int(index1), int(index2)) decoded_message = decoded_message + letter elif message[numbers_index * 2] == " ": decoded_message = decoded_message + " " return decoded_message
--- +++ @@ -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(self, letter: str) -> np.ndarray: + """ + Return the pair of numbers that represents the given letter in the + polybius square + >>> np.array_equal(PolybiusCipher().letter_to_numbers('a'), [1,1]) + True + + >>> np.array_equal(PolybiusCipher().letter_to_numbers('u'), [4,5]) + True + """ index1, index2 = np.where(letter == self.SQUARE) indexes = np.concatenate([index1 + 1, index2 + 1]) return indexes def numbers_to_letter(self, index1: int, index2: int) -> str: + """ + Return the letter corresponding to the position [index1, index2] in + the polybius square + + >>> PolybiusCipher().numbers_to_letter(4, 5) == "u" + True + + >>> PolybiusCipher().numbers_to_letter(1, 1) == "a" + True + """ return self.SQUARE[index1 - 1, index2 - 1] def encode(self, message: str) -> str: + """ + Return the encoded version of message according to the polybius cipher + + >>> PolybiusCipher().encode("test message") == "44154344 32154343112215" + True + + >>> PolybiusCipher().encode("Test Message") == "44154344 32154343112215" + True + """ message = message.lower() message = message.replace("j", "i") @@ -39,6 +72,15 @@ return encoded_message def decode(self, message: str) -> str: + """ + Return the decoded version of message according to the polybius cipher + + >>> PolybiusCipher().decode("44154344 32154343112215") == "test message" + True + + >>> PolybiusCipher().decode("4415434432154343112215") == "testmessage" + True + """ message = message.replace(" ", " ") decoded_message = "" for numbers_index in range(int(len(message) / 2)): @@ -51,4 +93,4 @@ elif message[numbers_index * 2] == " ": decoded_message = decoded_message + " " - return decoded_message+ return decoded_message
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]: digits = list(range(block_size)) random.shuffle(digits) return digits def encrypt( message: str, key: list[int] | None = None, block_size: int | None = None ) -> tuple[str, list[int]]: message = message.upper() message_length = len(message) if key is None or block_size is None: block_size = generate_valid_block_size(message_length) key = generate_permutation_key(block_size) encrypted_message = "" for i in range(0, message_length, block_size): block = message[i : i + block_size] rearranged_block = [block[digit] for digit in key] encrypted_message += "".join(rearranged_block) return encrypted_message, key def decrypt(encrypted_message: str, key: list[int]) -> str: key_length = len(key) decrypted_message = "" for i in range(0, len(encrypted_message), key_length): block = encrypted_message[i : i + key_length] original_block = [""] * key_length for j, digit in enumerate(key): original_block[digit] = block[j] decrypted_message += "".join(original_block) return decrypted_message def main() -> None: message = "HELLO WORLD" encrypted_message, key = encrypt(message) decrypted_message = decrypt(encrypted_message, key) print(f"Decrypted message: {decrypted_message}") if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -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 key is a sequence of unique integers that +determine the order of character rearrangement. + +For more info: https://www.nku.edu/~christensen/1402%20permutation%20ciphers.pdf +""" import random def generate_valid_block_size(message_length: int) -> int: + """ + Generate a valid block size that is a factor of the message length. + + Args: + message_length (int): The length of the message. + + Returns: + int: A valid block size. + + Example: + >>> random.seed(1) + >>> generate_valid_block_size(12) + 3 + """ block_sizes = [ block_size for block_size in range(2, message_length + 1) @@ -12,6 +35,20 @@ def generate_permutation_key(block_size: int) -> list[int]: + """ + Generate a random permutation key of a specified block size. + + Args: + block_size (int): The size of each permutation block. + + Returns: + list[int]: A list containing a random permutation of digits. + + Example: + >>> random.seed(0) + >>> generate_permutation_key(4) + [2, 0, 1, 3] + """ digits = list(range(block_size)) random.shuffle(digits) return digits @@ -20,6 +57,23 @@ def encrypt( message: str, key: list[int] | None = None, block_size: int | None = None ) -> tuple[str, list[int]]: + """ + Encrypt a message using a permutation cipher with block rearrangement using a key. + + Args: + message (str): The plaintext message to be encrypted. + key (list[int]): The permutation key for decryption. + block_size (int): The size of each permutation block. + + Returns: + tuple: A tuple containing the encrypted message and the encryption key. + + Example: + >>> encrypted_message, key = encrypt("HELLO WORLD") + >>> decrypted_message = decrypt(encrypted_message, key) + >>> decrypted_message + 'HELLO WORLD' + """ message = message.upper() message_length = len(message) @@ -38,6 +92,22 @@ def decrypt(encrypted_message: str, key: list[int]) -> str: + """ + Decrypt an encrypted message using a permutation cipher with block rearrangement. + + Args: + encrypted_message (str): The encrypted message. + key (list[int]): The permutation key for decryption. + + Returns: + str: The decrypted plaintext message. + + Example: + >>> encrypted_message, key = encrypt("HELLO WORLD") + >>> decrypted_message = decrypt(encrypted_message, key) + >>> decrypted_message + 'HELLO WORLD' + """ key_length = len(key) decrypted_message = "" @@ -52,6 +122,13 @@ def main() -> None: + """ + Driver function to pass message to get encrypted, then decrypted. + + Example: + >>> main() + Decrypted message: HELLO WORLD + """ message = "HELLO WORLD" encrypted_message, key = encrypt(message) @@ -63,4 +140,4 @@ import doctest doctest.testmod() - main()+ main()
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": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", "0": "-----", "&": ".-...", "@": ".--.-.", ":": "---...", ",": "--..--", ".": ".-.-.-", "'": ".----.", '"': ".-..-.", "?": "..--..", "/": "-..-.", "=": "-...-", "+": ".-.-.", "-": "-....-", "(": "-.--.", ")": "-.--.-", "!": "-.-.--", " ": "/" } # Exclamation mark is not in ITU-R recommendation # fmt: on REVERSE_DICT = {value: key for key, value in MORSE_CODE_DICT.items()} def encrypt(message: str) -> str: return " ".join(MORSE_CODE_DICT[char] for char in message.upper()) def decrypt(message: str) -> str: return "".join(REVERSE_DICT[char] for char in message.split()) def main() -> None: message = "Morse code here!" print(message) message = encrypt(message) print(message) message = decrypt(message) print(message) if __name__ == "__main__": main()
--- +++ @@ -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!") + '... --- ... -.-.--' + >>> encrypt("SOS!") == encrypt("sos!") + True + """ return " ".join(MORSE_CODE_DICT[char] for char in message.upper()) def decrypt(message: str) -> str: + """ + >>> decrypt('... --- ... -.-.--') + 'SOS!' + """ return "".join(REVERSE_DICT[char] for char in message.split()) def main() -> None: + """ + >>> s = "".join(MORSE_CODE_DICT) + >>> decrypt(encrypt(s)) == s + True + """ message = "Morse code here!" print(message) message = encrypt(message) @@ -35,4 +55,4 @@ if __name__ == "__main__": - main()+ main()
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 to get the # target pixels coordinates grid = np.stack( np.meshgrid(np.arange(0, image.shape[1]), np.arange(0, image.shape[0])), 2 ) grid = np.round(grid - flow).astype(np.int32) # Find the locations outside of the original image invalid = (grid < 0) | (grid >= np.array([image.shape[1], image.shape[0]])) grid[invalid] = 0 warped = image[grid[:, :, 1], grid[:, :, 0]] # Set pixels at invalid locations to 0 warped[invalid[:, :, 0] | invalid[:, :, 1]] = 0 return warped def horn_schunck( image0: np.ndarray, image1: np.ndarray, num_iter: SupportsIndex, alpha: float | None = None, ) -> tuple[np.ndarray, np.ndarray]: if alpha is None: alpha = 0.1 # Initialize flow horizontal_flow = np.zeros_like(image0) vertical_flow = np.zeros_like(image0) # Prepare kernels for the calculation of the derivatives and the average velocity kernel_x = np.array([[-1, 1], [-1, 1]]) * 0.25 kernel_y = np.array([[-1, -1], [1, 1]]) * 0.25 kernel_t = np.array([[1, 1], [1, 1]]) * 0.25 kernel_laplacian = np.array( [[1 / 12, 1 / 6, 1 / 12], [1 / 6, 0, 1 / 6], [1 / 12, 1 / 6, 1 / 12]] ) # Iteratively refine the flow for _ in range(num_iter): warped_image = warp(image0, horizontal_flow, vertical_flow) derivative_x = convolve(warped_image, kernel_x) + convolve(image1, kernel_x) derivative_y = convolve(warped_image, kernel_y) + convolve(image1, kernel_y) derivative_t = convolve(warped_image, kernel_t) + convolve(image1, -kernel_t) avg_horizontal_velocity = convolve(horizontal_flow, kernel_laplacian) avg_vertical_velocity = convolve(vertical_flow, kernel_laplacian) # This updates the flow as proposed in the paper (Step 12) update = ( derivative_x * avg_horizontal_velocity + derivative_y * avg_vertical_velocity + derivative_t ) update = update / (alpha**2 + derivative_x**2 + derivative_y**2) horizontal_flow = avg_horizontal_velocity - derivative_x * update vertical_flow = avg_vertical_velocity - derivative_y * update return horizontal_flow, vertical_flow if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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%93Schunck_method +Paper: http://image.diku.dk/imagecanon/material/HornSchunckOptical_Flow.pdf +""" from typing import SupportsIndex @@ -8,6 +18,25 @@ def warp( image: np.ndarray, horizontal_flow: np.ndarray, vertical_flow: np.ndarray ) -> np.ndarray: + """ + Warps the pixels of an image into a new image using the horizontal and vertical + flows. + Pixels that are warped from an invalid location are set to 0. + + Parameters: + image: Grayscale image + horizontal_flow: Horizontal flow + vertical_flow: Vertical flow + + Returns: Warped image + + >>> warp(np.array([[0, 1, 2], [0, 3, 0], [2, 2, 2]]), \ + np.array([[0, 1, -1], [-1, 0, 0], [1, 1, 1]]), \ + np.array([[0, 0, 0], [0, 1, 0], [0, 0, 1]])) + array([[0, 0, 0], + [3, 1, 0], + [0, 2, 3]]) + """ flow = np.stack((horizontal_flow, vertical_flow), 2) # Create a grid of all pixel coordinates and subtract the flow to get the @@ -35,6 +64,28 @@ num_iter: SupportsIndex, alpha: float | None = None, ) -> tuple[np.ndarray, np.ndarray]: + """ + This function performs the Horn-Schunck algorithm and returns the estimated + optical flow. It is assumed that the input images are grayscale and + normalized to be in [0, 1]. + + Parameters: + image0: First image of the sequence + image1: Second image of the sequence + alpha: Regularization constant + num_iter: Number of iterations performed + + Returns: estimated horizontal & vertical flow + + >>> np.round(horn_schunck(np.array([[0, 0, 2], [0, 0, 2]]), \ + np.array([[0, 2, 0], [0, 2, 0]]), alpha=0.1, num_iter=110)).\ + astype(np.int32) + array([[[ 0, -1, -1], + [ 0, -1, -1]], + <BLANKLINE> + [[ 0, 0, 0], + [ 0, 0, 0]]], dtype=int32) + """ if alpha is None: alpha = 0.1 @@ -77,4 +128,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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", "XYZNOPQRSTUVW"), "H": ("ABCDEFGHIJKLM", "XYZNOPQRSTUVW"), "I": ("ABCDEFGHIJKLM", "WXYZNOPQRSTUV"), "J": ("ABCDEFGHIJKLM", "WXYZNOPQRSTUV"), "K": ("ABCDEFGHIJKLM", "VWXYZNOPQRSTU"), "L": ("ABCDEFGHIJKLM", "VWXYZNOPQRSTU"), "M": ("ABCDEFGHIJKLM", "UVWXYZNOPQRST"), "N": ("ABCDEFGHIJKLM", "UVWXYZNOPQRST"), "O": ("ABCDEFGHIJKLM", "TUVWXYZNOPQRS"), "P": ("ABCDEFGHIJKLM", "TUVWXYZNOPQRS"), "Q": ("ABCDEFGHIJKLM", "STUVWXYZNOPQR"), "R": ("ABCDEFGHIJKLM", "STUVWXYZNOPQR"), "S": ("ABCDEFGHIJKLM", "RSTUVWXYZNOPQ"), "T": ("ABCDEFGHIJKLM", "RSTUVWXYZNOPQ"), "U": ("ABCDEFGHIJKLM", "QRSTUVWXYZNOP"), "V": ("ABCDEFGHIJKLM", "QRSTUVWXYZNOP"), "W": ("ABCDEFGHIJKLM", "PQRSTUVWXYZNO"), "X": ("ABCDEFGHIJKLM", "PQRSTUVWXYZNO"), "Y": ("ABCDEFGHIJKLM", "OPQRSTUVWXYZN"), "Z": ("ABCDEFGHIJKLM", "OPQRSTUVWXYZN"), } def generate_table(key: str) -> list[tuple[str, str]]: return [alphabet[char] for char in key.upper()] def encrypt(key: str, words: str) -> str: cipher = "" count = 0 table = generate_table(key) for char in words.upper(): cipher += get_opponent(table[count], char) count = (count + 1) % len(table) return cipher def decrypt(key: str, words: str) -> str: return encrypt(key, words) def get_position(table: tuple[str, str], char: str) -> tuple[int, int]: # `char` is either in the 0th row or the 1st row row = 0 if char in table[0] else 1 col = table[row].index(char) return row, col def get_opponent(table: tuple[str, str], char: str) -> str: row, col = get_position(table, char.upper()) if row == 1: return table[0][col] else: return table[1][col] if row == 0 else char if __name__ == "__main__": import doctest doctest.testmod() # Fist ensure that all our tests are passing... """ Demo: Enter key: marvin Enter text to encrypt: jessica Encrypted: QRACRWU Decrypted with key: JESSICA """ key = input("Enter key: ").strip() text = input("Enter text to encrypt: ").strip() cipher_text = encrypt(key, text) print(f"Encrypted: {cipher_text}") print(f"Decrypted with key: {decrypt(key, cipher_text)}")
--- +++ @@ -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'), + ('ABCDEFGHIJKLM', 'WXYZNOPQRSTUV'), ('ABCDEFGHIJKLM', 'UVWXYZNOPQRST')] + """ return [alphabet[char] for char in key.upper()] def encrypt(key: str, words: str) -> str: + """ + >>> encrypt('marvin', 'jessica') + 'QRACRWU' + """ cipher = "" count = 0 table = generate_table(key) @@ -43,10 +53,18 @@ def decrypt(key: str, words: str) -> str: + """ + >>> decrypt('marvin', 'QRACRWU') + 'JESSICA' + """ return encrypt(key, words) def get_position(table: tuple[str, str], char: str) -> tuple[int, int]: + """ + >>> get_position(generate_table('marvin')[0], 'M') + (0, 12) + """ # `char` is either in the 0th row or the 1st row row = 0 if char in table[0] else 1 col = table[row].index(char) @@ -54,6 +72,10 @@ def get_opponent(table: tuple[str, str], char: str) -> str: + """ + >>> get_opponent(generate_table('marvin')[0], 'M') + 'T' + """ row, col = get_position(table, char.upper()) if row == 1: return table[0][col] @@ -78,4 +100,4 @@ cipher_text = encrypt(key, text) print(f"Encrypted: {cipher_text}") - print(f"Decrypted with key: {decrypt(key, cipher_text)}")+ print(f"Decrypted with key: {decrypt(key, cipher_text)}")
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_input(dirty: str) -> str: dirty = "".join([c.upper() for c in dirty if c in string.ascii_letters]) clean = "" if len(dirty) < 2: return dirty for i in range(len(dirty) - 1): clean += dirty[i] if dirty[i] == dirty[i + 1]: clean += "X" clean += dirty[-1] if len(clean) & 1: clean += "X" return clean def generate_table(key: str) -> list[str]: # I and J are used interchangeably to allow # us to use a 5x5 table (25 letters) alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ" # we're using a list instead of a '2d' array because it makes the math # for setting up the table and doing the actual encoding/decoding simpler table = [] # copy key chars into the table if they are in `alphabet` ignoring duplicates for char in key.upper(): if char not in table and char in alphabet: table.append(char) # fill the rest of the table in with the remaining alphabet chars for char in alphabet: if char not in table: table.append(char) return table def encode(plaintext: str, key: str) -> str: table = generate_table(key) plaintext = prepare_input(plaintext) ciphertext = "" for char1, char2 in chunker(plaintext, 2): row1, col1 = divmod(table.index(char1), 5) row2, col2 = divmod(table.index(char2), 5) if row1 == row2: ciphertext += table[row1 * 5 + (col1 + 1) % 5] ciphertext += table[row2 * 5 + (col2 + 1) % 5] elif col1 == col2: ciphertext += table[((row1 + 1) % 5) * 5 + col1] ciphertext += table[((row2 + 1) % 5) * 5 + col2] else: # rectangle ciphertext += table[row1 * 5 + col2] ciphertext += table[row2 * 5 + col1] return ciphertext def decode(ciphertext: str, key: str) -> str: table = generate_table(key) plaintext = "" for char1, char2 in chunker(ciphertext, 2): row1, col1 = divmod(table.index(char1), 5) row2, col2 = divmod(table.index(char2), 5) if row1 == row2: plaintext += table[row1 * 5 + (col1 - 1) % 5] plaintext += table[row2 * 5 + (col2 - 1) % 5] elif col1 == col2: plaintext += table[((row1 - 1) % 5) * 5 + col1] plaintext += table[((row2 - 1) % 5) * 5 + col2] else: # rectangle plaintext += table[row1 * 5 + col2] plaintext += table[row2 * 5 + col1] return plaintext if __name__ == "__main__": import doctest doctest.testmod() print("Encoded:", encode("BYE AND THANKS", "GREETING")) print("Decoded:", decode("CXRBANRLBALQ", "GREETING"))
--- +++ @@ -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 cipher +2) It is a manual symmetric encryption technique +3) It is a multiple letter encryption cipher + +The implementation in the code below encodes alphabets only. +It removes spaces, special characters and numbers from the +code. + +Playfair is no longer used by military forces because of known +insecurities and of the advent of automated encryption devices. +This cipher is regarded as insecure since before World War I. +""" import itertools import string @@ -14,6 +34,10 @@ def prepare_input(dirty: str) -> str: + """ + Prepare the plaintext by up-casing it + and separating repeated letters with X's + """ dirty = "".join([c.upper() for c in dirty if c in string.ascii_letters]) clean = "" @@ -57,6 +81,21 @@ def encode(plaintext: str, key: str) -> str: + """ + Encode the given plaintext using the Playfair cipher. + Takes the plaintext and the key as input and returns the encoded string. + + >>> encode("Hello", "MONARCHY") + 'CFSUPM' + >>> encode("attack on the left flank", "EMERGENCY") + 'DQZSBYFSDZFMFNLOHFDRSG' + >>> encode("Sorry!", "SPECIAL") + 'AVXETX' + >>> encode("Number 1", "NUMBER") + 'UMBENF' + >>> encode("Photosynthesis!", "THE SUN") + 'OEMHQHVCHESUKE' + """ table = generate_table(key) plaintext = prepare_input(plaintext) @@ -80,6 +119,16 @@ def decode(ciphertext: str, key: str) -> str: + """ + Decode the input string using the provided key. + + >>> decode("BMZFAZRZDH", "HAZARD") + 'FIREHAZARD' + >>> decode("HNBWBPQT", "AUTOMOBILE") + 'DRIVINGX' + >>> decode("SLYSSAQS", "CASTLE") + 'ATXTACKX' + """ table = generate_table(key) plaintext = "" @@ -107,4 +156,4 @@ doctest.testmod() print("Encoded:", encode("BYE AND THANKS", "GREETING")) - print("Decoded:", decode("CXRBANRLBALQ", "GREETING"))+ print("Decoded:", decode("CXRBANRLBALQ", "GREETING"))
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() def __str__(self) -> str: return "".join(self.__passcode) def __neg_pos(self, iterlist: list[int]) -> list[int]: for i in range(1, len(iterlist), 2): iterlist[i] *= -1 return iterlist def __passcode_creator(self) -> list[str]: choices = string.ascii_letters + string.digits password = [random.choice(choices) for _ in range(random.randint(10, 20))] return password def __make_key_list(self) -> list[str]: # key_list_options contain nearly all printable except few elements from # string.whitespace key_list_options = ( string.ascii_letters + string.digits + string.punctuation + " \t\n" ) keys_l = [] # creates points known as breakpoints to break the key_list_options at those # points and pivot each substring breakpoints = sorted(set(self.__passcode)) temp_list: list[str] = [] # algorithm for creating a new shuffled list, keys_l, out of key_list_options for i in key_list_options: temp_list.extend(i) # checking breakpoints at which to pivot temporary sublist and add it into # keys_l if i in breakpoints or i == key_list_options[-1]: keys_l.extend(temp_list[::-1]) temp_list.clear() # returning a shuffled keys_l to prevent brute force guessing of shift key return keys_l def __make_shift_key(self) -> int: num = sum(self.__neg_pos([ord(x) for x in self.__passcode])) return num if num > 0 else len(self.__passcode) def decrypt(self, encoded_message: str) -> str: decoded_message = "" # decoding shift like Caesar cipher algorithm implementing negative shift or # reverse shift or left shift for i in encoded_message: position = self.__key_list.index(i) decoded_message += self.__key_list[ (position - self.__shift_key) % -len(self.__key_list) ] return decoded_message def encrypt(self, plaintext: str) -> str: encoded_message = "" # encoding shift like Caesar cipher algorithm implementing positive shift or # forward shift or right shift for i in plaintext: position = self.__key_list.index(i) encoded_message += self.__key_list[ (position + self.__shift_key) % len(self.__key_list) ] return encoded_message def test_end_to_end(msg: str = "Hello, this is a modified Caesar cipher") -> str: cip1 = ShuffledShiftCipher() return cip1.decrypt(cip1.encrypt(msg)) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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. lowercase letters of the English alphabet + 3. digits from 0 to 9 + + Using unique characters from the passcode, the normal list of characters, + that can be allowed in the plaintext, is pivoted and shuffled. Refer to docstring + of __make_key_list() to learn more about the shuffling. + + Then, using the passcode, a number is calculated which is used to encrypt the + plaintext message with the normal shift cipher method, only in this case, the + reference, to look back at while decrypting, is shuffled. + + Each cipher object can possess an optional argument as passcode, without which a + new passcode is generated for that object automatically. + cip1 = ShuffledShiftCipher('d4usr9TWxw9wMD') + cip2 = ShuffledShiftCipher() + """ def __init__(self, passcode: str | None = None) -> None: + """ + Initializes a cipher object with a passcode as it's entity + Note: No new passcode is generated if user provides a passcode + while creating the object + """ self.__passcode = passcode or self.__passcode_creator() self.__key_list = self.__make_key_list() self.__shift_key = self.__make_shift_key() def __str__(self) -> str: + """ + :return: passcode of the cipher object + """ return "".join(self.__passcode) def __neg_pos(self, iterlist: list[int]) -> list[int]: + """ + Mutates the list by changing the sign of each alternate element + + :param iterlist: takes a list iterable + :return: the mutated list + + """ for i in range(1, len(iterlist), 2): iterlist[i] *= -1 return iterlist def __passcode_creator(self) -> list[str]: + """ + Creates a random password from the selection buffer of + 1. uppercase letters of the English alphabet + 2. lowercase letters of the English alphabet + 3. digits from 0 to 9 + + :rtype: list + :return: a password of a random length between 10 to 20 + """ choices = string.ascii_letters + string.digits password = [random.choice(choices) for _ in range(random.randint(10, 20))] return password def __make_key_list(self) -> list[str]: + """ + Shuffles the ordered character choices by pivoting at breakpoints + Breakpoints are the set of characters in the passcode + + eg: + if, ABCDEFGHIJKLMNOPQRSTUVWXYZ are the possible characters + and CAMERA is the passcode + then, breakpoints = [A,C,E,M,R] # sorted set of characters from passcode + shuffled parts: [A,CB,ED,MLKJIHGF,RQPON,ZYXWVUTS] + shuffled __key_list : ACBEDMLKJIHGFRQPONZYXWVUTS + + Shuffling only 26 letters of the english alphabet can generate 26! + combinations for the shuffled list. In the program we consider, a set of + 97 characters (including letters, digits, punctuation and whitespaces), + thereby creating a possibility of 97! combinations (which is a 152 digit number + in itself), thus diminishing the possibility of a brute force approach. + Moreover, shift keys even introduce a multiple of 26 for a brute force approach + for each of the already 97! combinations. + """ # key_list_options contain nearly all printable except few elements from # string.whitespace key_list_options = ( @@ -52,10 +117,23 @@ return keys_l def __make_shift_key(self) -> int: + """ + sum() of the mutated list of ascii values of all characters where the + mutated list is the one returned by __neg_pos() + """ num = sum(self.__neg_pos([ord(x) for x in self.__passcode])) return num if num > 0 else len(self.__passcode) def decrypt(self, encoded_message: str) -> str: + """ + Performs shifting of the encoded_message w.r.t. the shuffled __key_list + to create the decoded_message + + >>> ssc = ShuffledShiftCipher('4PYIXyqeQZr44') + >>> ssc.decrypt("d>**-1z6&'5z'5z:z+-='$'>=zp:>5:#z<'.&>#") + 'Hello, this is a modified Caesar cipher' + + """ decoded_message = "" # decoding shift like Caesar cipher algorithm implementing negative shift or @@ -69,6 +147,15 @@ return decoded_message def encrypt(self, plaintext: str) -> str: + """ + Performs shifting of the plaintext w.r.t. the shuffled __key_list + to create the encoded_message + + >>> ssc = ShuffledShiftCipher('4PYIXyqeQZr44') + >>> ssc.encrypt('Hello, this is a modified Caesar cipher') + "d>**-1z6&'5z'5z:z+-='$'>=zp:>5:#z<'.&>#" + + """ encoded_message = "" # encoding shift like Caesar cipher algorithm implementing positive shift or @@ -83,6 +170,10 @@ def test_end_to_end(msg: str = "Hello, this is a modified Caesar cipher") -> str: + """ + >>> test_end_to_end() + 'Hello, this is a modified Caesar cipher' + """ cip1 = ShuffledShiftCipher() return cip1.decrypt(cip1.encrypt(msg)) @@ -90,4 +181,4 @@ if __name__ == "__main__": import doctest - doctest.testmod()+ doctest.testmod()
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, "Gm": 9, "Tm": 12, "Pm": 15, "Em": 18, "Zm": 21, "Ym": 24, } def length_conversion(value: float, from_type: str, to_type: str) -> float: 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()
--- +++ @@ -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. +-> 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", @@ -25,6 +44,31 @@ 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") @@ -59,4 +103,4 @@ if __name__ == "__main__": from doctest import testmod - testmod()+ testmod()
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**t) % n y = math.gcd(x - 1, n) if x > 1 and y > 1: p = y q = n // y break # find the correct factors else: break # t is not divisible by 2, break and choose another g return sorted([p, q]) if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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: - t = t // 2 - x = (g**t) % n - y = math.gcd(x - 1, n) - if x > 1 and y > 1: - p = y - q = n // y - break # find the correct factors - else: - break # t is not divisible by 2, break and choose another g - return sorted([p, q]) - - -if __name__ == "__main__": - import doctest - - doctest.testmod()+""" +An RSA prime factor algorithm. + +The program can efficiently factor RSA prime number given the private key d and +public key e. + +| Source: on page ``3`` of https://crypto.stanford.edu/~dabo/papers/RSA-survey.pdf +| More readable source: https://www.di-mgt.com.au/rsa_factorize_n.html + +large number can take minutes to factor, therefore are not included in doctest. +""" + +from __future__ import annotations + +import math +import random + + +def rsafactor(d: int, e: int, n: int) -> list[int]: + """ + This function returns the factors of N, where p*q=N + + Return: [p, q] + + We call N the RSA modulus, e the encryption exponent, and d the decryption exponent. + The pair (N, e) is the public key. As its name suggests, it is public and is used to + encrypt messages. + The pair (N, d) is the secret key or private key and is known only to the recipient + of encrypted messages. + + >>> rsafactor(3, 16971, 25777) + [149, 173] + >>> rsafactor(7331, 11, 27233) + [113, 241] + >>> rsafactor(4021, 13, 17711) + [89, 199] + """ + 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**t) % n + y = math.gcd(x - 1, n) + if x > 1 and y > 1: + p = y + q = n // y + break # find the correct factors + else: + break # t is not divisible by 2, break and choose another g + return sorted([p, q]) + + +if __name__ == "__main__": + import doctest + + doctest.testmod()
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 = [chr(i + 65) for i in range(26)] # Remove duplicate characters from key key = remove_duplicates(key.upper()) offset = len(key) # First fill cipher with key characters cipher_alphabet = {alphabet[i]: char for i, char in enumerate(key)} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(cipher_alphabet), 26): char = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 char = alphabet[i - offset] cipher_alphabet[alphabet[i]] = char return cipher_alphabet def encipher(message: str, cipher_map: dict[str, str]) -> str: return "".join(cipher_map.get(ch, ch) for ch in message.upper()) def decipher(message: str, cipher_map: dict[str, str]) -> str: # Reverse our cipher mappings rev_cipher_map = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(ch, ch) for ch in message.upper()) def main() -> None: message = input("Enter message to encode or decode: ").strip() key = input("Enter keyword: ").strip() option = input("Encipher or decipher? E/D:").strip()[0].lower() try: func = {"e": encipher, "d": decipher}[option] except KeyError: raise KeyError("invalid input option") cipher_map = create_cipher_map(key) print(func(message, cipher_map)) if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -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 Wrd' + """ key_no_dups = "" for ch in key: @@ -8,6 +18,12 @@ def create_cipher_map(key: str) -> dict[str, str]: + """ + Returns a cipher map given a keyword. + + :param key: keyword to use + :return: dictionary cipher map + """ # Create a list of the letters in the alphabet alphabet = [chr(i + 65) for i in range(26)] # Remove duplicate characters from key @@ -28,16 +44,42 @@ def encipher(message: str, cipher_map: dict[str, str]) -> str: + """ + Enciphers a message given a cipher map. + + :param message: Message to encipher + :param cipher_map: Cipher map + :return: enciphered string + + >>> encipher('Hello World!!', create_cipher_map('Goodbye!!')) + 'CYJJM VMQJB!!' + """ return "".join(cipher_map.get(ch, ch) for ch in message.upper()) def decipher(message: str, cipher_map: dict[str, str]) -> str: + """ + Deciphers a message given a cipher map + + :param message: Message to decipher + :param cipher_map: Dictionary mapping to use + :return: Deciphered string + + >>> cipher_map = create_cipher_map('Goodbye!!') + >>> decipher(encipher('Hello World!!', cipher_map), cipher_map) + 'HELLO WORLD!!' + """ # Reverse our cipher mappings rev_cipher_map = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(ch, ch) for ch in message.upper()) def main() -> None: + """ + Handles I/O + + :return: void + """ message = input("Enter message to encode or decode: ").strip() key = input("Enter keyword: ").strip() option = input("Encipher or decipher? E/D:").strip()[0].lower() @@ -53,4 +95,4 @@ import doctest doctest.testmod() - main()+ main()
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 = False if num < 0: negative = True num = -num binary: list[int] = [] while num > 0: binary.insert(0, num % 2) num >>= 1 if negative: return "-0b" + "".join(str(e) for e in binary) return "0b" + "".join(str(e) for e in binary) def decimal_to_binary_recursive_helper(decimal: int) -> str: decimal = int(decimal) if decimal in (0, 1): # Exit cases for the recursion return str(decimal) div, mod = divmod(decimal, 2) return decimal_to_binary_recursive_helper(div) + str(mod) def decimal_to_binary_recursive(number: str) -> str: number = str(number).strip() if not number: raise ValueError("No input value was provided") negative = "-" if number.startswith("-") else "" number = number.lstrip("-") if not number.isnumeric(): raise ValueError("Input value is not an integer") return f"{negative}0b{decimal_to_binary_recursive_helper(int(number))}" if __name__ == "__main__": import doctest doctest.testmod() print(decimal_to_binary_recursive(input("Input a decimal number: ")))
--- +++ @@ -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' + >>> decimal_to_binary_iterative(7) + '0b111' + >>> decimal_to_binary_iterative(35) + '0b100011' + >>> # negatives work too + >>> decimal_to_binary_iterative(-2) + '-0b10' + >>> # other floats will error + >>> decimal_to_binary_iterative(16.16) # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: 'float' object cannot be interpreted as an integer + >>> # strings will error as well + >>> decimal_to_binary_iterative('0xfffff') # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: 'str' object cannot be interpreted as an integer + """ if isinstance(num, float): raise TypeError("'float' object cannot be interpreted as an integer") @@ -28,6 +53,17 @@ def decimal_to_binary_recursive_helper(decimal: int) -> str: + """ + Take a positive integer value and return its binary equivalent. + >>> decimal_to_binary_recursive_helper(1000) + '1111101000' + >>> decimal_to_binary_recursive_helper("72") + '1001000' + >>> decimal_to_binary_recursive_helper("number") + Traceback (most recent call last): + ... + ValueError: invalid literal for int() with base 10: 'number' + """ decimal = int(decimal) if decimal in (0, 1): # Exit cases for the recursion return str(decimal) @@ -36,6 +72,25 @@ def decimal_to_binary_recursive(number: str) -> str: + """ + Take an integer value and raise ValueError for wrong inputs, + call the function above and return the output with prefix "0b" & "-0b" + for positive and negative integers respectively. + >>> decimal_to_binary_recursive(0) + '0b0' + >>> decimal_to_binary_recursive(40) + '0b101000' + >>> decimal_to_binary_recursive(-40) + '-0b101000' + >>> decimal_to_binary_recursive(40.8) + Traceback (most recent call last): + ... + ValueError: Input value is not an integer + >>> decimal_to_binary_recursive("forty") + Traceback (most recent call last): + ... + ValueError: Input value is not an integer + """ number = str(number).strip() if not number: raise ValueError("No input value was provided") @@ -51,4 +106,4 @@ doctest.testmod() - print(decimal_to_binary_recursive(input("Input a decimal number: ")))+ print(decimal_to_binary_recursive(input("Input a decimal number: ")))
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 enumerate(input_string): num = position % (lowest * 2) # puts it in bounds num = min(num, lowest * 2 - num) # creates zigzag pattern temp_grid[num].append(character) grid = ["".join(row) for row in temp_grid] output_string = "".join(grid) return output_string def decrypt(input_string: str, key: int) -> str: grid = [] lowest = key - 1 if key <= 0: raise ValueError("Height of grid can't be 0 or negative") if key == 1: return input_string temp_grid: list[list[str]] = [[] for _ in range(key)] # generates template for position in range(len(input_string)): num = position % (lowest * 2) # puts it in bounds num = min(num, lowest * 2 - num) # creates zigzag pattern temp_grid[num].append("*") counter = 0 for row in temp_grid: # fills in the characters splice = input_string[counter : counter + len(row)] grid.append(list(splice)) counter += len(row) output_string = "" # reads as zigzag for position in range(len(input_string)): num = position % (lowest * 2) # puts it in bounds num = min(num, lowest * 2 - num) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0) return output_string def bruteforce(input_string: str) -> dict[int, str]: results = {} for key_guess in range(1, len(input_string)): # tries every key results[key_guess] = decrypt(input_string, key_guess) return results if __name__ == "__main__": import doctest doctest.testmod()
--- +++ @@ -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_string - - for position, character in enumerate(input_string): - num = position % (lowest * 2) # puts it in bounds - num = min(num, lowest * 2 - num) # creates zigzag pattern - temp_grid[num].append(character) - grid = ["".join(row) for row in temp_grid] - output_string = "".join(grid) - - return output_string - - -def decrypt(input_string: str, key: int) -> str: - grid = [] - lowest = key - 1 - - if key <= 0: - raise ValueError("Height of grid can't be 0 or negative") - if key == 1: - return input_string - - temp_grid: list[list[str]] = [[] for _ in range(key)] # generates template - for position in range(len(input_string)): - num = position % (lowest * 2) # puts it in bounds - num = min(num, lowest * 2 - num) # creates zigzag pattern - temp_grid[num].append("*") - - counter = 0 - for row in temp_grid: # fills in the characters - splice = input_string[counter : counter + len(row)] - grid.append(list(splice)) - counter += len(row) - - output_string = "" # reads as zigzag - for position in range(len(input_string)): - num = position % (lowest * 2) # puts it in bounds - num = min(num, lowest * 2 - num) # creates zigzag pattern - output_string += grid[num][0] - grid[num].pop(0) - return output_string - - -def bruteforce(input_string: str) -> dict[int, str]: - results = {} - for key_guess in range(1, len(input_string)): # tries every key - results[key_guess] = decrypt(input_string, key_guess) - return results - - -if __name__ == "__main__": - import doctest - - doctest.testmod()+"""https://en.wikipedia.org/wiki/Rail_fence_cipher""" + + +def encrypt(input_string: str, key: int) -> str: + """ + Shuffles the character of a string by placing each of them + in a grid (the height is dependent on the key) in a zigzag + formation and reading it left to right. + + >>> encrypt("Hello World", 4) + 'HWe olordll' + + >>> encrypt("This is a message", 0) + Traceback (most recent call last): + ... + ValueError: Height of grid can't be 0 or negative + + >>> encrypt(b"This is a byte string", 5) + Traceback (most recent call last): + ... + TypeError: sequence item 0: expected str instance, int found + """ + 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 enumerate(input_string): + num = position % (lowest * 2) # puts it in bounds + num = min(num, lowest * 2 - num) # creates zigzag pattern + temp_grid[num].append(character) + grid = ["".join(row) for row in temp_grid] + output_string = "".join(grid) + + return output_string + + +def decrypt(input_string: str, key: int) -> str: + """ + Generates a template based on the key and fills it in with + the characters of the input string and then reading it in + a zigzag formation. + + >>> decrypt("HWe olordll", 4) + 'Hello World' + + >>> decrypt("This is a message", -10) + Traceback (most recent call last): + ... + ValueError: Height of grid can't be 0 or negative + + >>> decrypt("My key is very big", 100) + 'My key is very big' + """ + grid = [] + lowest = key - 1 + + if key <= 0: + raise ValueError("Height of grid can't be 0 or negative") + if key == 1: + return input_string + + temp_grid: list[list[str]] = [[] for _ in range(key)] # generates template + for position in range(len(input_string)): + num = position % (lowest * 2) # puts it in bounds + num = min(num, lowest * 2 - num) # creates zigzag pattern + temp_grid[num].append("*") + + counter = 0 + for row in temp_grid: # fills in the characters + splice = input_string[counter : counter + len(row)] + grid.append(list(splice)) + counter += len(row) + + output_string = "" # reads as zigzag + for position in range(len(input_string)): + num = position % (lowest * 2) # puts it in bounds + num = min(num, lowest * 2 - num) # creates zigzag pattern + output_string += grid[num][0] + grid[num].pop(0) + return output_string + + +def bruteforce(input_string: str) -> dict[int, str]: + """Uses decrypt function by guessing every key + + >>> bruteforce("HWe olordll")[4] + 'Hello World' + """ + results = {} + for key_guess in range(1, len(input_string)): # tries every key + results[key_guess] = decrypt(input_string, key_guess) + return results + + +if __name__ == "__main__": + import doctest + + doctest.testmod()
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.append(k) return cipher, key @staticmethod def decrypt(cipher: list[int], key: list[int]) -> str: plain = [] for i in range(len(key)): p = int((cipher[i] - (key[i]) ** 2) / key[i]) plain.append(chr(p)) return "".join(plain) if __name__ == "__main__": c, k = Onepad().encrypt("Hello") print(c, k) print(Onepad().decrypt(c, k))
--- +++ @@ -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.seed(1) + >>> Onepad().encrypt(" ") + ([6969], [69]) + >>> random.seed(1) + >>> Onepad().encrypt("Hello") + ([9729, 114756, 4653, 31309, 10492], [69, 292, 33, 131, 61]) + >>> Onepad().encrypt(1) + Traceback (most recent call last): + ... + TypeError: 'int' object is not iterable + >>> Onepad().encrypt(1.1) + Traceback (most recent call last): + ... + TypeError: 'float' object is not iterable + """ plain = [ord(i) for i in text] key = [] cipher = [] @@ -16,6 +37,20 @@ @staticmethod def decrypt(cipher: list[int], key: list[int]) -> str: + """ + Function to decrypt text using pseudo-random numbers. + >>> Onepad().decrypt([], []) + '' + >>> Onepad().decrypt([35], []) + '' + >>> Onepad().decrypt([], [35]) + Traceback (most recent call last): + ... + IndexError: list index out of range + >>> random.seed(1) + >>> Onepad().decrypt([9729, 114756, 4653, 31309, 10492], [69, 292, 33, 131, 61]) + 'Hello' + """ plain = [] for i in range(len(key)): p = int((cipher[i] - (key[i]) ** 2) / key[i]) @@ -26,4 +61,4 @@ if __name__ == "__main__": c, k = Onepad().encrypt("Hello") print(c, k) - print(Onepad().decrypt(c, k))+ print(Onepad().decrypt(c, k))
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_length]) - ord_a c = (p + k) % 26 ciphertext.append(chr(c + ord_a)) return "".join(ciphertext) def running_key_decrypt(key: str, ciphertext: str) -> str: ciphertext = ciphertext.replace(" ", "").upper() key = key.replace(" ", "").upper() key_length = len(key) plaintext = [] ord_a = ord("A") for i, char in enumerate(ciphertext): c = ord(char) - ord_a k = ord(key[i % key_length]) - ord_a p = (c - k) % 26 plaintext.append(chr(p + ord_a)) return "".join(plaintext) def test_running_key_encrypt() -> None: if __name__ == "__main__": import doctest doctest.testmod() test_running_key_encrypt() plaintext = input("Enter the plaintext: ").upper() print(f"\n{plaintext = }") key = "How does the duck know that? said Victor" encrypted_text = running_key_encrypt(key, plaintext) print(f"{encrypted_text = }") decrypted_text = running_key_decrypt(key, encrypted_text) print(f"{decrypted_text = }")
--- +++ @@ -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 encrypted. + :return: The ciphertext. + """ plaintext = plaintext.replace(" ", "").upper() key = key.replace(" ", "").upper() key_length = len(key) @@ -17,6 +27,13 @@ def running_key_decrypt(key: str, ciphertext: str) -> str: + """ + Decrypts the ciphertext using the Running Key Cipher. + + :param key: The running key (long piece of text). + :param ciphertext: The ciphertext to be decrypted. + :return: The plaintext. + """ ciphertext = ciphertext.replace(" ", "").upper() key = key.replace(" ", "").upper() key_length = len(key) @@ -33,6 +50,12 @@ def test_running_key_encrypt() -> None: + """ + >>> key = "How does the duck know that? said Victor" + >>> ciphertext = running_key_encrypt(key, "DEFEND THIS") + >>> running_key_decrypt(key, ciphertext) == "DEFENDTHIS" + True + """ if __name__ == "__main__": @@ -49,4 +72,4 @@ print(f"{encrypted_text = }") decrypted_text = running_key_decrypt(key, encrypted_text) - print(f"{decrypted_text = }")+ print(f"{decrypted_text = }")
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 the ROUTE cipher. """ def main() -> None: message = input("Enter message: ") key = int(input(f"Enter key [2-{len(message) - 1}]: ")) mode = input("Encryption/Decryption [e/d]: ") if mode.lower().startswith("e"): text = encrypt_message(key, message) elif mode.lower().startswith("d"): text = decrypt_message(key, message) # Append pipe symbol (vertical bar) to identify spaces at the end. print(f"Output:\n{text + '|'}") def encrypt_message(key: int, message: str) -> str: cipher_text = [""] * key for col in range(key): pointer = col while pointer < len(message): cipher_text[col] += message[pointer] pointer += key return "".join(cipher_text) def decrypt_message(key: int, message: str) -> str: num_cols = math.ceil(len(message) / key) num_rows = key num_shaded_boxes = (num_cols * num_rows) - len(message) plain_text = [""] * num_cols col = 0 row = 0 for symbol in message: plain_text[col] += symbol col += 1 if (col == num_cols) or ( (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): col = 0 row += 1 return "".join(plain_text) if __name__ == "__main__": import doctest doctest.testmod() main()
--- +++ @@ -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) -> str: + """ + >>> decrypt_message(6, 'Hlia rDsahrij') + 'Harshil Darji' + """ num_cols = math.ceil(len(message) / key) num_rows = key num_shaded_boxes = (num_cols * num_rows) - len(message) @@ -57,4 +65,4 @@ import doctest doctest.testmod() - main()+ main()
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 = encrypt_message(key, message) elif resp.lower().startswith("d"): mode = "decrypt" translated = decrypt_message(key, message) print(f"\n{mode.title()}ion: \n{translated}") def check_valid_key(key: str) -> None: key_list = list(key) letters_list = list(LETTERS) key_list.sort() letters_list.sort() if key_list != letters_list: sys.exit("Error in the key or symbol set.") def encrypt_message(key: str, message: str) -> str: return translate_message(key, message, "encrypt") def decrypt_message(key: str, message: str) -> str: return translate_message(key, message, "decrypt") def translate_message(key: str, message: str, mode: str) -> str: translated = "" chars_a = LETTERS chars_b = key if mode == "decrypt": chars_a, chars_b = chars_b, chars_a for symbol in message: if symbol.upper() in chars_a: sym_index = chars_a.find(symbol.upper()) if symbol.isupper(): translated += chars_b[sym_index].upper() else: translated += chars_b[sym_index].lower() else: translated += symbol return translated def get_random_key() -> str: key = list(LETTERS) random.shuffle(key) return "".join(key) if __name__ == "__main__": main()
--- +++ @@ -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: + """ + >>> decrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs') + 'Harshil Darji' + """ return translate_message(key, message, "decrypt") @@ -67,4 +75,4 @@ if __name__ == "__main__": - main()+ main()
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 = "" NUMBER_IMAGES = 250 def main() -> None: img_paths, annos = get_dataset(LABEL_DIR, IMG_DIR) for index in range(NUMBER_IMAGES): idxs = random.sample(range(len(annos)), 4) new_image, new_annos, path = update_image_and_anno( img_paths, annos, idxs, OUTPUT_SIZE, SCALE_RANGE, filter_scale=FILTER_TINY_SCALE, ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' letter_code = random_chars(32) file_name = path.split(os.sep)[-1].rsplit(".", 1)[0] file_root = f"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}" cv2.imwrite(f"{file_root}.jpg", new_image, [cv2.IMWRITE_JPEG_QUALITY, 85]) print(f"Succeeded {index + 1}/{NUMBER_IMAGES} with {file_name}") annos_list = [] for anno in new_annos: width = anno[3] - anno[1] height = anno[4] - anno[2] x_center = anno[1] + width / 2 y_center = anno[2] + height / 2 obj = f"{anno[0]} {x_center} {y_center} {width} {height}" annos_list.append(obj) with open(f"{file_root}.txt", "w") as outfile: outfile.write("\n".join(line for line in annos_list)) def get_dataset(label_dir: str, img_dir: str) -> tuple[list, list]: img_paths = [] labels = [] for label_file in glob.glob(os.path.join(label_dir, "*.txt")): label_name = label_file.split(os.sep)[-1].rsplit(".", 1)[0] with open(label_file) as in_file: obj_lists = in_file.readlines() img_path = os.path.join(img_dir, f"{label_name}.jpg") boxes = [] for obj_list in obj_lists: obj = obj_list.rstrip("\n").split(" ") xmin = float(obj[1]) - float(obj[3]) / 2 ymin = float(obj[2]) - float(obj[4]) / 2 xmax = float(obj[1]) + float(obj[3]) / 2 ymax = float(obj[2]) + float(obj[4]) / 2 boxes.append([int(obj[0]), xmin, ymin, xmax, ymax]) if not boxes: continue img_paths.append(img_path) labels.append(boxes) return img_paths, labels def update_image_and_anno( all_img_list: list, all_annos: list, idxs: list[int], output_size: tuple[int, int], scale_range: tuple[float, float], filter_scale: float = 0.0, ) -> tuple[list, list, str]: output_img = np.zeros([output_size[0], output_size[1], 3], dtype=np.uint8) scale_x = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) scale_y = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) divid_point_x = int(scale_x * output_size[1]) divid_point_y = int(scale_y * output_size[0]) new_anno = [] path_list = [] for i, index in enumerate(idxs): path = all_img_list[index] path_list.append(path) img_annos = all_annos[index] img = cv2.imread(path) if i == 0: # top-left img = cv2.resize(img, (divid_point_x, divid_point_y)) output_img[:divid_point_y, :divid_point_x, :] = img for bbox in img_annos: xmin = bbox[1] * scale_x ymin = bbox[2] * scale_y xmax = bbox[3] * scale_x ymax = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) elif i == 1: # top-right img = cv2.resize(img, (output_size[1] - divid_point_x, divid_point_y)) output_img[:divid_point_y, divid_point_x : output_size[1], :] = img for bbox in img_annos: xmin = scale_x + bbox[1] * (1 - scale_x) ymin = bbox[2] * scale_y xmax = scale_x + bbox[3] * (1 - scale_x) ymax = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) elif i == 2: # bottom-left img = cv2.resize(img, (divid_point_x, output_size[0] - divid_point_y)) output_img[divid_point_y : output_size[0], :divid_point_x, :] = img for bbox in img_annos: xmin = bbox[1] * scale_x ymin = scale_y + bbox[2] * (1 - scale_y) xmax = bbox[3] * scale_x ymax = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) else: # bottom-right img = cv2.resize( img, (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) output_img[ divid_point_y : output_size[0], divid_point_x : output_size[1], : ] = img for bbox in img_annos: xmin = scale_x + bbox[1] * (1 - scale_x) ymin = scale_y + bbox[2] * (1 - scale_y) xmax = scale_x + bbox[3] * (1 - scale_x) ymax = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) # Remove bounding box small than scale of filter if filter_scale > 0: new_anno = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def random_chars(number_char: int) -> str: assert number_char > 1, "The number of character should greater than 1" letter_code = ascii_lowercase + digits return "".join(random.choice(letter_code) for _ in range(number_char)) if __name__ == "__main__": main() print("DONE ✅")
--- +++ @@ -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. + """ img_paths, annos = get_dataset(LABEL_DIR, IMG_DIR) for index in range(NUMBER_IMAGES): idxs = random.sample(range(len(annos)), 4) @@ -49,6 +55,11 @@ def get_dataset(label_dir: str, img_dir: str) -> tuple[list, list]: + """ + - label_dir <type: str>: Path to label include annotation of images + - img_dir <type: str>: Path to folder contain images + Return <type: list>: List of images path and labels + """ img_paths = [] labels = [] for label_file in glob.glob(os.path.join(label_dir, "*.txt")): @@ -81,6 +92,18 @@ scale_range: tuple[float, float], filter_scale: float = 0.0, ) -> tuple[list, list, str]: + """ + - all_img_list <type: list>: list of all images + - all_annos <type: list>: list of all annotations of specific image + - idxs <type: list>: index of image in list + - output_size <type: tuple>: size of output image (Height, Width) + - scale_range <type: tuple>: range of scale image + - filter_scale <type: float>: the condition of downscale image and bounding box + Return: + - output_img <type: narray>: image after resize + - new_anno <type: list>: list of new annotation after scale + - path[0] <type: string>: get the name of image file + """ output_img = np.zeros([output_size[0], output_size[1], 3], dtype=np.uint8) scale_x = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) scale_y = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) @@ -147,6 +170,12 @@ def random_chars(number_char: int) -> str: + """ + Automatic generate random 32 characters. + Get random string code: '7b7ad245cdff75241935e4dd860f3bad' + >>> len(random_chars(32)) + 32 + """ assert number_char > 1, "The number of character should greater than 1" letter_code = ascii_lowercase + digits return "".join(random.choice(letter_code) for _ in range(number_char)) @@ -154,4 +183,4 @@ if __name__ == "__main__": main() - print("DONE ✅")+ print("DONE ✅")
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, key: str) -> str: decrypted_text = "" for i in range(len(ciphertext)): ct = ord(ciphertext[i]) - ord(key[i % len(key)]) while ct < 0: ct = 26 + ct decrypted_text += chr(65 + ct) return decrypted_text if __name__ == "__main__": from doctest import testmod testmod() # Example usage plaintext = "HELLO" key = "KEY" encrypted_text = vernam_encrypt(plaintext, key) decrypted_text = vernam_decrypt(encrypted_text, key) print("\n\n") print("Plaintext:", plaintext) print("Encrypted:", encrypted_text) print("Decrypted:", decrypted_text)
--- +++ @@ -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(ciphertext: str, key: str) -> str: + """ + >>> vernam_decrypt("RIJVS","KEY") + 'HELLO' + """ decrypted_text = "" for i in range(len(ciphertext)): ct = ord(ciphertext[i]) - ord(key[i % len(key)]) @@ -31,4 +39,4 @@ print("\n\n") print("Plaintext:", plaintext) print("Encrypted:", encrypted_text) - print("Decrypted:", decrypted_text)+ print("Decrypted:", decrypted_text)
https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/ciphers/vernam_cipher.py