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... |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 3