id
stringlengths
21
47
content
stringlengths
729
19.3k
canitedit_data_10_csv_parser
class CSVParser: def __init__(self, csv: str): self.csv = csv def contents(self) -> list[list[str]]: lines = self.csv.split("\n") output = [] for line in lines: output.append(line.split(",")) return output Add a function called `header` which returns the fir...
canitedit_data_11_fibonacci
class Fib: def __iter__(self): self.prev_prev = 0 self.prev = 1 return self def __next__(self): output = self.prev + self.prev_prev self.prev_prev = self.prev self.prev = output return output add a method `next_n_fibs(n: int)` which takes in an integer, a...
canitedit_data_13_maze_solver
from typing import List, Literal, Tuple from queue import PriorityQueue Move = Literal["up", "down", "left", "right"] # 0 = up, 1 = down, 2 = left, 3 = right MoveIndex = Literal[0, 1, 2, 3] # 0 = empty, 1 = wall, 2 = start, 3 = end Cell = Literal[0, 1, 2, 3] class Maze: def __init__(self, maze: List[List[Cell]])...
canitedit_data_14_matrix_operations
class Matrix: def __init__(self, matrix: list[list[int]]): self.matrix = matrix def add(self, other): result = [] for i in range(len(self.matrix)): row = [] for j in range(len(self.matrix[0])): row.append(self.matrix[i][j] + other.matrix[i][j]) ...
canitedit_data_15_pandas_random_data
import pandas as pd import random import string class GradeManipulator: def __init__(self): self.data = self._generate_random_data() def _generate_random_data(self): names = [''.join(random.choices(string.ascii_uppercase, k=5)) for _ in range(100)] ages = [random.ran...
canitedit_data_16_interpreter
""" A programming language interpreter for the following language: expr ::= expr <binop> expr | <number> | <name> | var <name> = <expr> in <expr> binop ::= + | - """ from abc import ABC, abstractmethod class AST(ABC): @abstractmethod def eval(self, env) -> int: pass class BinOp(AST): def __init_...
canitedit_data_17_quiz
class Quiz: def __init__(self, questions, answers): self.questions = questions self.answers = answers self.total_questions = len(questions) self.score = 0 self.current_question = 0 def check_answer(self, question_index, answer) -> bool: if self.answers[question_...
canitedit_data_18_deck_of_cards
import random class Card: def __init__(self, suit, value): self.suit = suit self.value = value def __str__(self): return f"{self.value} of {self.suit}" class Deck: def __init__(self): self.cards = [] self.build() def build(self): for suit in ["Spades...
canitedit_data_19_traffic_analysis
from typing import Optional, Literal from abc import ABC, abstractmethod class Visitor(ABC): """ A visitor. """ @abstractmethod def visit(self, city_intersection: 'CityIntersection'): """ Visit a city intersection. """ class City: """ A city with a name, populati...
canitedit_data_1_cipher
class Cipher: def __init__(self): self.ciphers = { "default": { 'a': 'b', 'b': 'a', 'c': 'e', 'd': 'd', 'e': 'c', 'f': 'g', 'g': 'f', 'h': 'i', 'i': 'h...
canitedit_data_20_html_parser
from typing import List, Union import re class HTMLElement: def __init__(self, name, content: List[Union[str, 'HTMLElement']]): self.name = name self.content = content def __str__(self): return f"<{self.name}>{''.join(str(c) for c in self.content)}</{self.name}>" def __repr__(sel...
canitedit_data_21_dijkstra_bellman
import heapq class Graph: def __init__(self): self.nodes = set() self.edges = {} def add_node(self, value): self.nodes.add(value) self.edges[value] = [] def add_edge(self, from_node, to_node, weight): self.edges[from_node].append((to_node, weight)) self.ed...
canitedit_data_22_diff_format
from typing import List def opt(before: str, after: str): before_l = list(enumerate(before.split("\n"))) b = len(before_l) after_l = list(enumerate(after.split("\n"))) a = len(after_l) # OPT[N][M] is best for first n of before and m of after OPT = [[None] * (a + 1) for i in range(b + 1)] ...
canitedit_data_23_bpe_tokenizer
from typing import Dict, List class BPETokenizerTrainer(object): def __init__(self, training_set: str, max_num_merges: int) -> None: self.max_num_merges = max_num_merges self.last_token_id = 0 self.training_set_symbolized: List[str] = [] self.lookup_table: Dict[str, int] = {} ...
canitedit_data_24_tree_abstractions
from abc import abstractmethod class Tree: @abstractmethod def tree_map(self, func): pass @abstractmethod def tree_filter(self, func, filler): pass @abstractmethod def tree_andmap(self, func): pass @abstractmethod def tree_ormap(self, func): pass ...
canitedit_data_25_sudoku_solver
from typing import List, Optional from z3 import ArithRef, Int, Solver, Distinct, And, sat, IntVal def make_9x9_z3_board(board_text: str, solver: Solver) -> List[List[ArithRef]]: """ Creates a board of z3 variables from a string representation of a board. For unknown cells, make the value be 0, and for kn...
canitedit_data_26_kl_divergence
import torch def kl_div(q: torch.distributions.Distribution, p: torch.distributions.Distribution) -> torch.Tensor: return torch.distributions.kl_divergence(q, p).mean() Replace the `kl_div` function body to compute a monte carlo kl divergence approximation by sampling `num_samples` from distribution q. `num_samp...
canitedit_data_28_password_strength_checker
def minLength(password): assert type(password) == str return len(password) >= 8 def isPasswordStrong(password): return minLength(password) Revise the `isPasswordStrong` function to include an additional check that validates the presence of at least one special character within the password. Define a new ...
canitedit_data_29_genetic_algorithm
import numpy as np import random import math random.seed(100) class City: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f"({self.x}, {self.y})" def __eq__(self, other): if isinstance(other, City): return self.x == other.x and self...
canitedit_data_30_cross_correlation
import numpy as np def cross_correlation(image, kernel): ih, iw = image.shape kh, kw = kernel.shape oh = ih - kh + 1 ow = iw - kw + 1 output = np.zeros((oh, ow)) for i in range(oh): for j in range(ow): region = image[i:i+kh, j:j+kw] element_wise_product = re...
canitedit_data_31_bookkeeping
class Yarn: """Represents the yarns that a yarn store sells""" def __init__(self, purchase_price: int, sell_price: int, color: str): self.purchase_price = purchase_price self.sell_price = sell_price self.color = color class BankAccount: """Represents the bank account of this ya...
canitedit_data_32_markov_transition
import numpy as np class MarkovChain: def create_transition_matrix(self, matrix): matrix = np.array(matrix) column_sums = np.sum(matrix, axis=0) normalized_matrix = matrix / column_sums return normalized_matrix.tolist() Edit the code to include a method called `translate_...
canitedit_data_33_genetic_algorithm_2
import numpy as np import random import math random.seed(100) class City: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f"({self.x}, {self.y})" def __eq__(self, other): if isinstance(other, City): return self.x == other.x and ...
canitedit_data_34_oop_refactor
def process_message(message, message_type): if message_type == "text": return f"Processed text message: {message}" elif message_type == "image": return f"Processed image message with description: {message}" else: return "Unknown message type" Abstract the code into an object-oriente...
canitedit_data_35_topological_sort
from typing import List class Node: '''Simple node (No duplicate edges between nodes)''' def __init__(self, id: int, out_edges: List[int]): uniques = {} for edge in out_edges: if edge in uniques.keys(): raise RuntimeError else: uniques[edg...
canitedit_data_36_strongly_connected
from typing import List class Node: '''Simple node (No duplicate edges between nodes)''' def __init__(self, id: int): self.id = id self.out_edges = [] self.in_edges = [] def __eq__(self, __value: object) -> bool: if not isinstance(__value, Node): return False ...
canitedit_data_37_dijkstras
from typing import List class Node: '''Simple node (No duplicate edges between nodes)''' def __init__(self, id: int): self.id = id self.out_edges = [] self.in_edges = [] def __eq__(self, __value: object) -> bool: if not isinstance(__value, Node): return False ...
canitedit_data_38_high_order
class Student: def __init__(self, name, gpa) -> None: self.name = name self.gpa = gpa def __eq__(self, __value: object) -> bool: if not isinstance(__value, Student): return False else: return __value.name == self.name class Course: def __init__(self...
canitedit_data_39_vowel_count
import string def prepare_line(line): for char in string.punctuation: line = line.replace(char, "") for char in string.digits: line = line.replace(char, "") return line def vowel_count(line): vowel_count = 0 for letter in prepare_line(line): if letter in "aeiouy": ...
canitedit_data_3_hello_world
def hello_world(name): return f'{name} says, "Hello World!"' The function hello_world should return the string parameter "name" converted to uppercase concatenated to the string ' says, "Hello World!"'. For example, hello_world('the cow') should return 'THE COW says, "Hello World!"'. For another example, hello_wor...
canitedit_data_40_adjacency
from typing import List class Node: '''Simple node (No duplicate edges between nodes)''' def __init__(self, id: int): self.id = id self.out_edges = [] self.in_edges = [] def __eq__(self, __value: object) -> bool: if not isinstance(__value, Node): return False ...
canitedit_data_41_group_theory
import torch import numpy as np import torch.nn as nn class C4(nn.Module): """Represents the C4 class of group theory, where each element represents a discrete rotation.""" def __init__(self): super().__init__() self.register_buffer('identity', torch.Tensor([0.])) def size(self): ...
canitedit_data_44_html_to_markdown
from typing import Dict, List, Union import re class HTMLElement: def __init__(self, name, content: List[Union[str, 'HTMLElement']], attributes: Dict[str, str]): self.name = name self.content = content self.attributes = attributes def __str__(self): prelude = f"<{self.name}" ...
canitedit_data_45_double_consonant
import string def prepare_string(line): for char in string.punctuation: line = line.replace(char, "") for char in string.digits: line = line.replace(char, "") return line.lower() def double_consonant(substring): consonant_streak = 0 consonant_count = 0 consonants = "qwrtypsdfgh...
canitedit_data_46_consonants_within
import string def prepare_string(line): for char in string.punctuation: line = line.replace(char, "") for char in string.digits: line = line.replace(char, "") return line.lower() def consonant_within(line): consonants = "qwrtypsdfghjklzcmnvbx" word_con_count = 0 total_con_count...
canitedit_data_47_merge_sort
from typing import List def merge_sort(lst: List[int]) -> List[int]: if len(lst) > 1: mid = len(lst) // 2 L = lst[:mid] R = lst[mid:] merge_sort(L) merge_sort(R) i = j = k = 0 while i < len(L) and j < len(R): if L[i] < R[j]: lst[k]...
canitedit_data_48_max_sum_subarray
from typing import List def max_sublstay_sum(lst: List[int]) -> int: max_so_far = lst[0] curr_max = lst[0] for i in range(1, len(lst)): curr_max = max(lst[i], curr_max + lst[i]) max_so_far = max(max_so_far, curr_max) return max_so_far Adapt the function to return the indices of the sub...
canitedit_data_49_binary_search
from typing import List def binary_search(lst: List[int], x: int) -> int: low = 0 high = len(lst) - 1 mid = 0 while low <= high: mid = (high + low) // 2 if lst[mid] < x: low = mid + 1 elif lst[mid] > x: high = mid - 1 else: return mid...
canitedit_data_4_tensor_operations
class Tensor: def __init__(self, matrix): self.matrix = matrix def m(self): return len(self.matrix) def n(self): return len(self.matrix[0]) def relu(self): for i in range(self.m()): for j in range(self.n()): self.matrix[i][j] = ...
canitedit_data_50_syllable_count
import string def prepare_string(line): for char in string.punctuation: line = line.replace(char, "") for char in string.digits: line = line.replace(char, "") return line.lower() def vowel_count(line): vowel_count = 0 for c in line: if c in "aeiouy": vowel_count...
canitedit_data_51_managers_manager
from typing import List, Union class Manager: def __init__(self, name: str, direct_reports: List[Union["Manager", "IC"]]): self.name = name self.team = direct_reports def find_managers_manager(self, name: str) -> List[str]: all_managers_managers_names = [] for direct_report...
canitedit_data_52_magic_square
from z3 import Sum, Distinct, Solver, Int, And, sat from typing import List, Union def magic_square() -> Union[str, List[List[int]]]: y = [[Int(f'x_{i}_{j}') for j in range(3)] for i in range(3)] s = Solver() s.add([And(x > 0, x <= 9) for row in y for x in row]) s.add(Distinct([x for row in y for x in ...
canitedit_data_53_minimax_to_alphabeta
import copy from typing import List, Literal, Optional, Tuple Player = Literal['X', 'O'] WinStatus = Literal[Player, 'TIE', None] class ConnectNGame: """ A game of Connect N, of width x height, where N is the number of pieces in a row/column/diagonal to win. """ def __init__(self, width, height, n):...
canitedit_data_55_bm25
import math from typing import List, Dict class BM25: def __init__(self, corpus: List[List[str]], k1: float = 1.5, b: float = 0.75) -> None: self.corpus = corpus self.corpus_size = len(corpus) self.avgdl = sum(len(doc) for doc in corpus) / self.corpus_size self.k1 = k1 self....
canitedit_data_56_interference_vars
from abc import ABC, abstractmethod from typing import Dict, Literal, Set # A-Normal Form (ANF) is a way of writing programs where every subexpression is # a variable or a function call. This is useful for compilers because it makes # it easier to reason about the program and to perform optimizations. # the kind of ...
canitedit_data_57_string_formatter
def format_string(name1, name2, message): formattedString = f'Hello, {name1.lower().capitalize()}! You have a message from {name2.lower().capitalize()}. The message is: {message}' return formattedString Change the function format_string so that the word order of the string message is changed from subject-verb-...
canitedit_data_58_dependency_solver
from typing import List, Literal class Semver: def __init__(self, major: int, minor: int, patch: int): self.major = major self.minor = minor self.patch = patch def __str__(self): return f'{self.major}.{self.minor}.{self.patch}' def __eq__(self, other): return self...
canitedit_data_60_unique_number
from typing import List def find_non_pair(numbers: List[int]) -> int: count = {} for number in numbers: count[number] = count.get(number, 0) + 1 for number, occurrence in count.items(): if occurrence != 2: return number return 0 Change the implementation such that `find_no...
canitedit_data_6_locked_box
from typing import Optional class MyBox: def __init__(self, data: str): self.data = data def lock(self, pin: int) -> 'LockedMyBox': return LockedMyBox(self.data, pin) def duplicate(self) -> 'MyBox': return MyBox(self.data) class LockedMyBox(MyBox): def __init__(self, data: s...
canitedit_data_7_temperature_converter
def fahrenheit_to_celsius(temperature): return ((temperature - 32)*5)/9 Add a function called 'celsius_to_fahrenheit' that has the parameter temperature, an integer or float, and returns ((temperature*9)/5) + 32. def fahrenheit_to_celsius(temperature): return ((temperature - 32)*5)/9 def celsius_to_fahrenhei...
canitedit_data_8_vector_lib
from abc import ABC, abstractmethod class Vector(ABC): def __init__(self, *args: int): self.vals = args @abstractmethod def manhattan_distance(other) -> float: pass @abstractmethod def cosine_similarity(other) -> float: pass Create a class called `MyVector` which extends ...
canitedit_data_9_sorting
class Sorter: def __init__(self): pass def sort(self, nums: list[int]) -> list[int]: if len(nums) == 0: return nums else: return self.insert(self.sort(nums[1:]), nums[0]) def insert(self, nums: list[int], num: int) -> list[int]: output = [] ...
canitedit_data_59_standard_scaling
import pandas as pd from sklearn.preprocessing import StandardScaler def standardize_data(data, scaler): """Standardizes the numeric columns in the data""" numeric = data.select_dtypes(include=['float64']).columns data_copy = data.copy() data_copy[numeric] = scaler.fit_transform(data[numeric]) ret...
canitedit_data_61_ridge_regression
from sklearn.linear_model import LinearRegression from sklearn.preprocessing import MinMaxScaler def normalize_data(data, scaler): """Normalizes the columns with float values""" numeric = data.select_dtypes(include=['float64']).columns data_copy = data.copy() data_copy[numeric] = scaler.fit_transform(d...
canitedit_data_65_tournament_tree
from typing import Optional, Union class Player: """ A player and its rating; the rating is always a positive integer (>= 0). """ def __init__(self, name, rating): self.name = name assert isinstance(rating, int) and rating >= 0 self.rating = rating class TournamentTreeNode: ...
canitedit_data_63_knary_trees
from abc import ABC, abstractmethod class KNaryTree(ABC): """Represents the abstract idea of a tree with an arbitrary number of children at each level""" @abstractmethod def total(self): """Returns the sum of all values in this KNaryTree""" pass @abstractmethod def depth(self): ...
canitedit_data_66_product_analysis
import pandas as pd from io import StringIO # data data = """ date,product_id,country,sales_channel,units_sold,unit_price,customer_age,customer_gender 2024-01-01,P1001,USA,Online,120,15.99,30,Female 2024-01-01,P2002,UK,In-store,75,45.50,45,Male 2024-01-02,P1001,Canada,Online,90,15.99,24,Female 2024-01-02,P3003,Germany...
canitedit_data_68_prime_numbers_problem
from typing import List def sum_of_prime_products(n: int) -> int: """ Let P be the set of the first 15 prime numbers. Find the sum of all distinct products that can be formed by multiplying any two different primes in P. """ def is_prime(n: int) -> bool: if n <= 1: return False ...
canitedit_data_67_test_invariants
class Employer: """ Represents an entity that employs workers. """ def __init__(self, name, funds): self.name = name self.funds = funds class Worker: """ Represents a person who does work for an employer. Name should be "[first name] [last name]" and pay should be pos...
canitedit_data_12_linkedlist_sort
from abc import ABC, abstractmethod class LinkedList: @abstractmethod def sort(self): pass @abstractmethod def remove(self, element): pass @abstractmethod def insert(self, element): pass class Cons(LinkedList): def __init__(self, first, rest: LinkedList): s...
canitedit_data_70_sieve_of_eratosthenes
def find_primes(end: int): primes = [] is_prime = [True] * (end + 1) for num in range(1, int(end**0.5) + 1): if is_prime[num]: primes.append(num) for multiple in range(num * num, end + 1, num): is_prime[multiple] = False for num in range(int(end**0.5) +...
canitedit_data_71_euclidean_algorithm
def gcd(a, b): return a if b == 0 else gcd(a % b, b) def lcm(a, b): return (a * b) / gcd(a, b) The code is recursing infinitely when one tries to compute the least common multiple. Fix the code to correctly compute the least common multiple and the greatest common divisor def gcd(a, b): return a if b == ...
canitedit_data_72_disjoint_cycles
def find_cycles(permutation): cycles = [] visited = set() for i in range(len(permutation)): if i not in visited: cycle = [] current = i while current not in visited: visited.add(current) cycle.append(current) ...
canitedit_data_73_permutation_equality
def cycle_equality(c1, c2): """ Takes two lists, c1 and c2, and returns True if the two lists represent the same cycle within a permutation group. """ if len(c1) != len(c2): return False start_index_b = c2.index(c1[0]) if c1[0] in c2 else -1 if start_index_b == -1: return False...
canitedit_data_76_memory_alloc
from typing import Any, List class Free: def __repr__(self): return "Free" # singleton FREE = Free() class MemoryAllocation: def __init__(self, size, address, buf): self.size = size self.address = address self.buffer = buf def __repr__(self): return f"MemoryAll...
canitedit_data_77_step_counter
class StepCounter: def __init__(self): self.steps = 0 self.distance = 0.0 # distance in kilometers self.steps_per_km = 1250 # average steps per km for walking def add_steps(self, steps): self.steps += steps self._update_distance() def _update_distance(self): ...
canitedit_data_78_llm_inference
from flask import Flask, request, jsonify from threading import Lock from vllm import LLM, SamplingParams HUMAN_HEADER = "Question:" AI_HEADER = "Answer:" class Inferencer: def __init__(self, model_name): self.model_name = model_name self.model_lock = Lock() self.model = None def get...
canitedit_data_79_int_to_key
import abc class Encoder(abc.ABC): @abc.abstractmethod def encode(self, n: int) -> str: raise NotImplementedError class LowerAlphaEncoder(Encoder): def encode(self, n: int) -> str: key = "" while n > 0: n, remainder = divmod(n - 1, 26) key = chr(97 + remaind...
canitedit_data_80_circular_queue
class CircularQueue: def __init__(self, capacity): self.capacity = capacity self.queue = [None] * capacity self.front = self.rear = -1 def enqueue(self, item): if self.is_full() or not self.is_empty(): self.front = (self.front + 1) % self.capacity elif self.i...
canitedit_data_81_linked_list_debug
class Node: def __init__(self, value: int) -> None: self.value = value self.next = None class LinkedList: def __init__(self): self.head = None def add(self, value: int) -> None: if not self.head: self.head = Node(value) else: current = se...
canitedit_data_85_dpll
from copy import deepcopy from typing import Optional class DPLLSolver: def __init__(self, cnf): """ initializes the DPLL Solver with a given CNF (Conjunctive Normal Form) input. :param cnf: a string representing the CNF, where each clause is on a new line, literals ar...
canitedit_data_86_pyast
import ast class UsageCounter(ast.NodeVisitor): """ Counts the usages of each identifier in the given AST. An usage does not count the definition or assignment itself; only identifiers that are used after their definition/assignment are counted. NOTE: This class does not handle the scoping rules o...
canitedit_data_87_documentation
import ast from typing import Tuple def build_documentation(code: str) -> Tuple[str, str]: results = [] parsed_ast = ast.parse(code) def visit_FunctionDef(node: ast.FunctionDef) -> None: name = node.name args_node = node.args return_annotation = node.returns if return_annot...
canitedit_data_88_correlation_clustering
import numpy as np import pandas as pd from scipy.cluster.hierarchy import linkage, fcluster from scipy.spatial.distance import squareform class FeatureSelector: """Selects features from a set of data according to their correlations""" def __init__(self, data: pd.DataFrame, columns: list[str]): self....
canitedit_data_89_palindrome_detector
def reverseString(originalString): reversedString = "" for i in range(0, len(originalString)): reversedString += originalString[i] return reversedString def isPalindrome(originalString): return originalString.lower() == reverseString(originalString.lower()) The function reverseString outputs t...
canitedit_data_90_dna_transcriber
def dnaToRna(base): if base == "T": return "A" elif base == "A": return "U" elif base == "C": return "G" elif base == "G": return "C" def transcribe(dna): rna = "" for i in range(len(dna)-1): rna += dnaToRna(dna[i]) return rna Fix my program, which i...
canitedit_data_91_interest_calculator
def simpleInterest(principal, rate, periods): return principal * rate * periods def compoundInterest(principal, rate, compoundFreq, periods): return principal * ((1 + (rate / compoundFreq)) * (compoundFreq * periods)) I want compoundInterest to return the correct compound interest. For example, compoundIntere...
canitedit_data_92_heron_area
import math def heronArea(sideLength1, sideLength2, sideLength3): semiperimeter = (sideLength1 + sideLength2 + sideLength3)/2 return math.sqrt(semiperimeter * (semiperimeter - sideLength1) * (semiperimeter - sideLength2) * semiperimeter - sideLength3) I want heronArea to return the heron area. For example, he...
canitedit_data_94_knn
from typing import List from math import sqrt class Label: def __init__(self, name: str) -> None: self.name = name def __hash__(self) -> int: return 1 def __eq__(self, __value: object) -> bool: return True class Point: def __init__(self, x: int, y: int, label: Label | None)...
canitedit_data_95_dbscan
import numpy as np from scipy.spatial import distance_matrix from collections import deque class DBSCAN: def __init__(self, eps: float = 0.5, min_samples: int = 5) -> None: self.eps = eps self.min_samples = min_samples self.labels_ = [] def fit(self, X: np.ndarray) -> None: n_s...
canitedit_data_96_distribution_clustering
import numpy as np from scipy.stats import multivariate_normal class GMM: def __init__(self, n_components: int, n_iter: int) -> None: self.n_components = n_components self.n_iter = n_iter self.means = None self.covariances = None self.pi = None self.reg_covar = 1e-6 ...
canitedit_data_101_house_prices
from typing import List, Tuple class House: def __init__(self, location: Tuple[int, int], bedrooms: int, bathrooms: int): self.location = location self.bedrooms = bedrooms self.bathrooms = bathrooms def distance_to(self, other: 'House') -> float: return ((self.location[0] - ot...
canitedit_data_102_nfa
from typing import Literal, List Input = Literal["a", "b", ""] State = Literal[0, 1, 2] class NFA: def __init__(self) -> None: self.current: State = 0 self.accept: set[State] = {1, 2} def transition(self, input: Input) -> List[State]: table = { 0: {"a": [1, 2], "b": [], "...
canitedit_data_2_cov_corr
class Probability: def sample_mean(self, X): """Computes the sample mean of the data""" return sum(X) / len(X) def variance(self, X): """Computes the variance of the data""" mean = sum(X) / len(X) return sum((x - mean) ** 2 for x in X) / len(X) def correlation(self...
canitedit_data_97_nash_equilibrium
from typing import List, Tuple class Cell: def __init__(self, pay1, pay2): self.pay1 = pay1 self.pay2 = pay2 class Game: def __init__(self, p1: List[str], p2: List[str], payoffs: List[List[Cell]]) -> None: """ p1: list of strategies for player 1 p2: list of strategies...
canitedit_data_98_encoder_decoder_dataset
import torch from typing import List, Tuple from torch.nn.utils.rnn import pad_sequence from abc import ABC, abstractmethod def tokens_to_tensor(token_ids, sp): return torch.cat((torch.tensor([sp.bos_id()]), torch.tensor(token_ids), torch.tensor([sp.eos_id()]))) class...
canitedit_data_99_secondary_keys
from typing import Any, Hashable, Optional class KeyValueCache: def __init__(self) -> None: self.primary_cache = {} self.secondary_key_map = {} def put(self, primary_key: Hashable, value: Any, secondary_keys: Optional[list[Hashable]] = None) -> None: self.primary_cache[primary_key] = v...
canitedit_data_103_postfix
from typing import Literal, List Op = Literal["+", "-", "*", "/"] Token = int | Op class PostfixParser: def parse(self, inputs: List[Token]) -> float: """parses a sequence of input tokens using postfix notation and computes the result""" def parseHelp(inputs: List[Token], stack: List[float]) -> ...
canitedit_data_104_filesystem
from typing import Callable, List from abc import ABC, abstractmethod class File(ABC): """ Represents a file in the file system. """ def __init__(self, name: str, permissions: int, owner: str): assert 0 <= permissions <= 0o777, "Invalid permissions..." self.name = name self.pe...
canitedit_data_105_descent_methods
from typing import List, Tuple import numpy as np from autograd import grad class descent: def __init__( self, step: float = 0.1, max_iter: int = 50, convergence: float = 1e-3, initial_points: Tuple[float, float] = (-1, -0.9), ): self.step = ...
canitedit_data_106_conways_game
from typing import List class ConwaysGameOfLife: """ Represents a grid of conway's game of life, where each cell is either alive or dead. The rules of the game are the following: 1. Any live cell with fewer than two live neighbors dies, as if by underpopulation. 2. Any live cell with two or three ...
canitedit_data_107_multiindex_sort
class Comparators: """ A class for that allows for custom comparator actions that work in conjuction with Python's default sorted function Example usage: `sorted(lorem_ipsum, key=Comparators.by_length)` """ def by_length(obj): """Comparing by length of object""" return len(obj) ...
canitedit_data_54_strategy
from abc import ABC from abc import abstractmethod from typing import List, Tuple class Strategy(ABC): @abstractmethod def returnMove(self, board: List[List[bool]]) -> Tuple[int, int]: '''Returns a tuple(row, column) which indicates where to move in a 3x3 grid.''' pass class Corner...
canitedit_data_110_integration
from typing import Optional import numpy as np from autograd import grad class integrator: def __init__(self, lower: float, upper: float, stepsize: float): self.lower = lower self.upper = upper self.stepsize = stepsize def rectangle_left(self, f): result = 0 x = self.l...
canitedit_data_100_pandas_apply
import pandas as pd class StringOperations: """A class containing a series of string operations""" def remove_duplicates(text): """Returns the text with only unique characters""" unique = [] for char in text: if char not in unique: unique.append(char) ...
canitedit_data_111_coprime_euler
import math def gcd(a : int, b : int) -> int: """Compute the Greatest Common Divisor (GCD) of a and b.""" assert a > 0 and b > 0 while b != 0: a, b = b, a % b return a def euler_totient(n : int) -> int: """Compute the Euler's Totient function of n.""" assert n > 0 if n == 1 : retu...
canitedit_data_112_elliptic_curves
import random def is_prime(n): """Check if a number is prime.""" if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True class EllipticCurve: def __init__(self, a : int, b : int, p : int): self.a = a self.b = ...
canitedit_data_113_schnorr_zk
import hashlib from typing import Tuple def keygen(p: int, g: int, x: int) -> Tuple[Tuple[int, int, int], int]: """generate public and private key with given prime (p), base (g), and private key (x).""" y = pow(g, x, p) # public key return (p, g, y), x def prover_commitment(p: int, g: int, r: int) -> T...
canitedit_data_114_grid_world_dp
import json from typing import Tuple, Literal, List, Union # defining a bunch of types to make the code more readable State = Tuple[int, int] Action = Literal["left", "right", "up", "down"] actions: List[Action] = ["left", "right", "up", "down"] Policy = List[List[Union[List[Action], Literal["TERM"]]]] StateValue = L...
canitedit_data_115_arrangement_selections
import math def permutation(n, r): return int(math.factorial(n) / math.factorial(n - r)) def combination(n, r): return int(math.factorial(n) / (math.factorial(r) * math.factorial(n - r))) def arrangement_unlimited_rep(n, r): return int(n ** r) def combination_unlimited_rep(n, r): return int(combina...