id int64 1 120 | name stringlengths 3 28 | full_name stringlengths 6 32 | before stringlengths 64 6.66k | after stringlengths 72 6.88k | tests stringlengths 80 9.12k | instruction_descriptive stringlengths 84 1.01k | instruction_lazy stringlengths 30 640 | taxonomy dict |
|---|---|---|---|---|---|---|---|---|
10 | csv_parser | 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 | 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
def header(self) -> list[str]:
lines = s... | ### START TESTS ###
if True: # pragma: no cover
parser = CSVParser('''bim,boom,bam,bap
duck,duck,goose,duck
1,0,1,0''')
p2 = CSVParser('''''')
p3 = CSVParser('''thing''')
p4 = CSVParser('''thing1, thing2
a, a''')
p5 = CSVParser(''',
,''')
assert parser.contents() == [["bim", "boom", "bam", "b... | Add a function called `header` which returns the first row of a csv file as a list of strings, where
every element in the list is a column in the row. | Add a method called `header` which returns the header of a csv file as a list | {
"change_kind": "adaptive",
"libraries": [],
"topic": "Language"
} |
11 | fibonacci | 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 | class Fib:
def __init__(self):
self.prev = 0
self.prev_prev = 1
def __iter__(self):
self.prev_prev = 0
self.prev = 1
return self
def __next__(self) -> int:
output = self.prev + self.prev_prev
self.prev_prev = self.prev
self.prev = output
... | ### START TESTS ###
if True: # pragma: no cover
f = Fib()
iterator = iter(f)
assert next(iterator) == 1
assert next(iterator) == 2
assert next(iterator) == 3
assert next(iterator) == 5
iterator = iter(f)
assert next(iterator) == 1
assert next(iterator) == 2
assert next(iterator... | add a method `next_n_fibs(n: int)` which takes in an integer, and produces a list containing the next `n` integers in the fibonacci sequence
starting from what the object would return if its `__next__` method was called. The method should not mutate the state of the object. When asked
for the next fibonacci number aft... | create a function `next_n_fibs` which takes an integer `n` and produces a list containing the next `n` numbers in the sequence.
the `Fib` object should not have its state changed by this function. | {
"change_kind": "adaptive",
"libraries": [],
"topic": "DSA"
} |
13 | maze_solver | 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]])... | 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]])... | ### START TESTS ###
if True: # pragma: no cover
exp, path = Maze([
[2, 0, 0, 1, 0],
[1, 1, 0, 1, 0],
[0, 0, 0, 0, 0],
[1, 1, 1, 1, 0],
[3, 0, 0, 0, 0],
]).solve()
assert exp == 14
assert path == [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), (2, 3),
... | Change the `solve` function in the `Maze` class to use A* with manhattan distance as the heuristic instead
of using Uniform Cost Search (UCS). The manhattan distance heuristic is
mathematically defined as follows: `h(n) = |n.x - goal.x| + |n.y - goal.y|`;
Where `n` is the current node and `goal` is the goal node. | Change the `solve` function to use A* with manhattan distance instead of using UCS. | {
"change_kind": "perfective",
"libraries": [],
"topic": "DSA"
} |
14 | matrix_operations | 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])
... | class Matrix:
def __init__(self, matrix: list[list[int]]):
self.matrix = matrix
def add(self, other):
if self.same_size(self.matrix, other.matrix):
result = []
for i in range(len(self.matrix)):
row = []
for j in range(len(self.matrix[0]))... | ### START TESTS ###
if True: # pragma: no cover
m1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
m2 = [
[9, 9, 9],
[8, 8, 8],
[0, 1, -2]
]
m3 = [
[-1, 5, 0],
[2, -8, 7],
[4, 3, -2],
[0, 6, 1]
]
mat1 = Matrix(m1)
... | Modify the Matrix class to check that the matrices received are of the same size before subtracting or adding them. This should be done with a helper function 'same_size' that returns true if the matrices have the same dimension. | Edit the methods add and subtract to check that dimension of matrices match using a helper method named 'same_size'. | {
"change_kind": "perfective",
"libraries": [],
"topic": "Math"
} |
15 | pandas_random_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... | 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... | ### START TESTS ###
if True: # pragma: no cover
random.seed(42)
dm = GradeManipulator()
assert dm.data.shape == (100, 4), "Data shape is not as expected."
top_3_scorers = dm.top_scorers(3)
assert top_3_scorers.shape[0] == 3, "top_scorers does not return the correct number of top scorers."
asse... | Add two methods to the `GradeManipulator` class:
1. `average_score_by_grade(self)` - returns a DataFrame of the average "Score" column for each category of "Grade" (i.e., "A", "B", "C", "D", and "F"). Do not reset the index.
2. `top_scorers(self, n)` - returns a DataFrame of the n students with the highest "Score" valu... | Add two methods to the grade manipulator: `average_score_by_grade` and `top_scorers(n)`,
which returns a data frame of the average score for each grade and a data frame of the top n students, respectively. | {
"change_kind": "adaptive",
"libraries": [
"pandas"
],
"topic": "Math"
} |
16 | interpreter | 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_... | """
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... | ### START TESTS ###
if True: # pragma: no cover
assert Number(1).eval({}) == 1
assert BinOp(Number(1), "+", Number(2)).eval({}) == 3
assert BinOp(Number(1), "-", Number(2)).eval({}) == -1
assert BinOp(Number(1), "*", Number(2)).eval({}) == 2
assert BinOp(Number(30), "*", Number(2)).eval({}) == 60
... | Add two new operations to the AST of the programming language: "*" and "/".
The `eval` method in the `BinOp` class should evaluate the two operands and return the result of the operation. "*" should multiply the operands, and "/" should perform integer division on the operands (i.e. the result should be the floored quo... | Add multiplication ("*") and integer division ("/") to the programming language. Throw a zero division error when necessary. | {
"change_kind": "adaptive",
"libraries": [],
"topic": "Language"
} |
17 | quiz | 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_... | 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
self.skipped = 0
def check_answer(self, question_index, answer) -> bool:
... | ### START TESTS ###
if True: # pragma: no cover
questions = ["How many days in a week?", "What color absorbs the most light?",
"Which language has more native speakers? English or Spanish?", "Who has won the most academy awards?"]
answers = ["7", "Black", "Spanish", "Walt Disney"]
quiz = ... | Add a new method `skip_question` and a field `skipped` to the Quiz class. This represents a new functionality in the Quiz class that allows users to skip a question, and keep track of how many questions were skipped. Output the number of question skipped as a game statistic in the `display_results` method. | Modify the `Quiz` class to allow the user to skip a question using `self.skip_question()`, and record the number of questions that were skipped in `self.skipped`. | {
"change_kind": "adaptive",
"libraries": [],
"topic": "Misc"
} |
18 | deck_of_cards | 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... | 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... | ### START TESTS ###
if True: # pragma: no cover
random.seed(42)
card = Card("Hearts", "Ace")
assert str(card) == "Ace of Hearts"
deck = Deck()
assert len(deck.cards) == 52
first_card = deck.cards[0]
assert str(first_card) == "2 of Spades"
deck.shuffle()
shuffled_first_card = deck... | Implement the `draw` method in the `Deck` class, and the `receive_card` method in the `Player` class.
The `draw` method should remove a card from the front of the deck and return it. It should also
return `None` if the deck is empty. The `receive_card` method should take a card as an argument and append it to the end... | Implement the `draw` method in the deck class to draw a card from the front of the deck, and the `receive_card` method in the player class to give a card to the player. | {
"change_kind": "adaptive",
"libraries": [],
"topic": "Misc"
} |
19 | traffic_analysis | 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... | 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... | ### START TESTS ###
if True: # pragma: no cover
atlanta = City('Atlanta', 500000, 0.5)
boston = City('Boston', 200000, 0.3)
chicago = City('Chicago', 1000000, 0.7)
denver = City('Denver', 300000, 0.4)
el_paso = City('El Paso', 100000, 0.1)
fargo = City('Fargo', 50000, 0.05)
four_way_inters... | Add a new type of intersection called 'Roundabout', and implement the functionality to handle it in the `TrafficAnalysisVisitor` class.
The 'Roundabout' intersection should reduce traffic by 30%, therefore make sure that the traffic value is adjusted by 0.7.
Also, there is a clear problem in the `visit` method of the ... | Add a new type of intersection, 'Roundabout', which should reduce traffic by 30%.
Also, make the visitor actually recur through children intersections too. | {
"change_kind": "adaptive",
"libraries": [],
"topic": "DSA"
} |
1 | cipher | 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... | 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... | ### START TESTS ###
if True: # pragma: no cover
cipher = Cipher()
default = cipher.ciphers["default"]
assert default['m'] == 'l'
assert default['n'] == 'o'
assert default['d'] == 'd'
assert default['w'] == 'v'
assert cipher.translate("default", "willthedogsbark") == "vhmmuicdnfrabsj"
... | Create a new method `caesar_cipher` that takes in an argument `shift`. It should shift every character in `self.alphabet` by the given `shift` amount. For example, if the shift is 4, then the letter `a` would be mapped `e`. This method should append the generated cipher into `self.ciphers` and name it `caesar` followed... | Create a new method `caesar_cipher` that creates a new cipher in `self.ciphers` that shifts every letter by a given amount. | {
"change_kind": "adaptive",
"libraries": [],
"topic": "DSA"
} |
20 | html_parser | 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... | 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}"
... | ### START TESTS ###
if True: # pragma: no cover
content = "<div>Hello <span>world</span></div>"
elements = parse(content)
assert "\n".join(str(elem) for elem in elements) == content
ex2 = """<head>
<title>My awesome page</title>
</head>
<body>
<div>
<h1>Super awesome page</h1>
<p>This is my awesome pa... | Add support for HTML attributes for the `parse(content: str)` function and `HTMLElement` class.
In the `HTMLElement` class add an `attributes` field that is a dictionary of the HTML attributes,
and update the `__str__` function to include the attributes in the opening tag.
The `parse(content: str)` function should pars... | Add support for HTML attributes to the parser and `HTMLElement` class. | {
"change_kind": "adaptive",
"libraries": [],
"topic": "Language"
} |
21 | dijkstra_bellman | 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... | class Graph:
def __init__(self):
self.nodes = set()
self.edges = []
def add_node(self, value):
self.nodes.add(value)
def add_edge(self, from_node, to_node, weight):
self.edges.append((from_node, to_node, weight))
def distances_to(self, start):
"""
Compu... | ### START TESTS ###
if True: # pragma: no cover
graph1 = Graph()
for node in ['A', 'B', 'C', 'D']:
graph1.add_node(node)
graph1.add_edge('A', 'B', 1)
graph1.add_edge('B', 'C', 2)
graph1.add_edge('C', 'D', 3)
graph1.add_edge('A', 'D', 10)
shortest_path1 = graph1.distances_to('A')
... | Add support for negative weights in `distances_to` function, throwing a `ValueError` if there are any negative cycles in the graph.
One way to do this, is to use the Bellman-Ford algorithm to find the shortest path from the source to all other nodes.
If there are any negative cycles, the algorithm will detect them and... | Make the `distances_to` function support negative weights; but throw a `ValueError` if there are any negative cycles in the graph. | {
"change_kind": "perfective",
"libraries": [],
"topic": "DSA"
} |
22 | diff_format | 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)]
... | 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)]
... | ### START TESTS ###
if True: # pragma: no cover
b1 = '''bleh
bleh'''
a1 = '''bob
bleh
bleh'''
b2 = '''hello
hello'''
a2 = '''hello
hey
hello'''
b3 = '''replacethis
hey'''
a3 = '''replaced
hey'''
b4 = '''lots
of
stuff'''
a4 = ''''''
b5 = '''only
one
thing
to
delete'''
a5 = '... | The following code takes a before and after string and creates a relative diff syntax which can edit the before string into the after. It has 3 operations <add>, <del>, and <del><add>.
x<add>string adds the given string after the xth line in the before. x<del> deletes the xth line in the before. x<del><add>string repla... | The following code takes a before and after string and creates a relative diff syntax which can edit the before string into the after.
It has 3 operations `line`<add>`string`, `line`<del>, and `line`<del><add>`string` which do their operations relative to the lines in the before.
Example 1:
Before:
hey
hey
After:... | {
"change_kind": "perfective",
"libraries": [],
"topic": "Language"
} |
23 | bpe_tokenizer | 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] = {}
... | from typing import Dict, List
class BPETokenizerTrainer(object):
def __init__(self, training_set: str, max_num_merges: int, max_num_tokens: int) -> None:
self.max_num_merges = max_num_merges
self.last_token_id = 0
self.max_num_tokens = max_num_tokens
self.training_set_symbolized: ... | ### START TESTS ###
if True: # pragma: no cover
training_set = "Think slow when you write in ink"
trainer0 = BPETokenizerTrainer(training_set=training_set, max_num_merges=250, max_num_tokens=100)
assert len(trainer0.get_lookup_table()) == 15
assert "in" not in trainer0.get_lookup_table()
trainer0.... | Add a `max_num_tokens` parameter to the Trainer constructor. `max_num_tokens` should limit the max size of the `lookup_table` on the Trainer.
During training, the while loop should terminate early if the `lookup_table` reaches a length of `max_num_tokens`. | Add a `max_num_tokens` parameter to the Trainer which limits the number of tokens that are defined. | {
"change_kind": "perfective",
"libraries": [],
"topic": "Math"
} |
24 | tree_abstractions | 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
... | 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
... | ### START TESTS ###
if True: # pragma: no cover
add_ten = lambda e : e + 10
is_positive = lambda e : e > 0
contains_x = lambda e : "x" in e
count_length = lambda e : len(e)
assert Leaf(3).tree_map(add_ten).value == Leaf(13).value
assert Leaf(-10).tree_andmap(is_positive) == False
assert L... | Change the `tree_map` and `tree_filter` methods in `Tree` and its subclasses to return new objects rather than modifying in place. | Change `Tree` and its subclasses not modify in place and be chainable. | {
"change_kind": "perfective",
"libraries": [],
"topic": "DSA"
} |
25 | sudoku_solver | 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... | 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... | ### START TESTS ###
if True: # pragma: no cover
def __eval_secret_check_valid(board: List[List[int]]) -> bool:
for row in board:
if len(set(row)) != 9:
return False
for col in zip(*board):
if len(set(col)) != 9:
return False
for i in... | This version of the sudoku solver and checker does not reflect the original game of sudoku; the
original game also checks for the uniqueness of 3x3 subgrids in addition to the rows and columns.
Update the `assert_uniq` function to add new constraints for all nine 3x3 subgrids, and update the
`check_valid` function to ... | Make both the sudoku solver and verifier support the nine 3x3 subgrids that are in the original sudoku game. | {
"change_kind": "corrective",
"libraries": [
"z3"
],
"topic": "DSA"
} |
26 | kl_divergence | 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() | import torch
def kl_div(q: torch.distributions.Distribution, p: torch.distributions.Distribution, num_samples: int = 100000) -> torch.Tensor:
x = q.sample((num_samples,))
log_q = q.log_prob(x)
log_p = p.log_prob(x)
kl_div = torch.mean(log_q - log_p)
return kl_div | ### START TESTS ###
if True: # pragma: no cover
torch.manual_seed(10)
P1 = torch.distributions.Normal(loc=0.0, scale=1.0)
Q1 = torch.distributions.Normal(loc=0.1, scale=1.0)
assert torch.allclose(torch.distributions.kl_divergence(
q=Q1, p=P1), kl_div(q=Q1, p=P1), atol=1e-2)
P2 = torch.distribu... | Replace the `kl_div` function body to compute a monte carlo kl divergence approximation by sampling `num_samples` from distribution q.
`num_samples` should be a parameter on `kl_div` with a default value of 100000. | Change `kl_div` to compute a monte carlo approximation of the kl divergence given `num_samples` as a parameter, which by default is set to 100000. | {
"change_kind": "perfective",
"libraries": [
"torch"
],
"topic": "Math"
} |
28 | password_strength_checker | 28_password_strength_checker | def minLength(password):
assert type(password) == str
return len(password) >= 8
def isPasswordStrong(password):
return minLength(password) | def minLength(password):
assert type(password) == str
return len(password) >= 8
def containsSpecialChar(password):
specialChar = '`~!@#$%^&*()-_+=[]{}|\\:;<>,.?/\"\''
assert type(password) == str
for char in password:
if char in specialChar:
return True
return False
def isP... | ### START TESTS ###
if True: # pragma: no cover
assert containsSpecialChar('1243i4u@') == True
assert containsSpecialChar('pqighp') == False
assert containsSpecialChar('') == False
assert containsSpecialChar('!@#$') == True
assert isPasswordStrong('ThisPAsswordIsStrong!') == True
assert isPass... | 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 function named `containsSpecialChar` which iterates over the given password and returns True if any character matches the predefined set of special chara... | Add a function `containsSpecialChar` that checks if a string contains a special character. Update `isPasswordStrong` to check for the presence of a special character in the password. | {
"change_kind": "adaptive",
"libraries": [],
"topic": "Language"
} |
29 | genetic_algorithm | 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... | 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 ... | ### START TESTS ###
if True: # pragma: no cover
# checking that nothing that shouldn't change has changed
cities = generate_cities(10)
assert cities == [City(2, 7), City(7, 2), City(6, 5), City(6, 8), City(1, 8), City(1, 1), City(7, 4), City(0, 10), City(10, 3), City(5, 3)]
assert distance(cities[0]... | Edit the genetic algorithm to not generate any routes with repeating cities when calling `next_generation`. | Edit the code to not generate any routes with repeating cities in any generation. | {
"change_kind": "corrective",
"libraries": [
"numpy"
],
"topic": "DSA"
} |
30 | cross_correlation | 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... | import numpy as np
def cross_correlation(image, kernel, padding):
ih, iw = image.shape
kh, kw = kernel.shape
oh = ih - kh + 1
ow = iw - kw + 1
oh = ih + 2 * padding - kh + 1
ow = iw + 2 * padding - kw + 1
output = np.zeros((oh, ow))
padded = np.pad(image, ((padding, padding), (padd... | ### START TESTS ###
if True: # pragma: no cover
import numpy as np
import torch
import torch.nn.functional as F
im_size, ker_size, padding = 6, 3, 3
im_sizes = [5, 10, 8]
ker_sizes = [3, 2, 4]
paddings = [0, 2, 3]
for im_size, ker_size, pad in zip(im_sizes, ker_sizes, paddings):
... | Change the method `cross_correlation` to also take in an argument `padding`, which pads the image of the method by the number indicated on all sides before performing the cross correlation operation on the padded image. | Change the `cross_correlation` method to take in an argument `padding`, which corresponds to the padding of a cross correlation operation. | {
"change_kind": "perfective",
"libraries": [
"numpy"
],
"topic": "Math"
} |
31 | bookkeeping | 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... | 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... | ### START TESTS ###
if True: # pragma: no cover
y1 = Yarn(2, 3, "black")
y2 = Yarn(4, 9, "yellow")
y3 = Yarn(1, 4, "blue")
y4 = Yarn(2, 5, "red")
y5 = Yarn(3, 3, "white")
s = Store(100)
# purchase price of this should be 62
stock = {
y1: 5,
y2: 5,
y3: 10,
... | Edit the `buy_yarn` and `sell_yarn` methods in the `Store` class to calculate the price of the order depending on whether its a purchase or a sale, rather than taking in an argument that specifies the total cost of the order. | Edit the `buy_yarn` and `sell_yarn` methods in the `Store` class to calculate the price of the order rather than taking in an argument for it. | {
"change_kind": "adaptive",
"libraries": [],
"topic": "Misc"
} |
32 | markov_transition | 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() | from typing import Dict, List
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()
def translate_from_list(s... | ### START TESTS ###
if True: # pragma: no cover
chain = MarkovChain()
l1 = {
0: [1, 3],
1: [0, 2],
2: [1, 3],
3: [0, 2, 4],
4: [3]
}
l2 = {
0: [4],
1: [2, 3, 4],
2: [1, 5, 6],
3: [1, 7, 8, 2],
4: [1, 9, 0, 3],
5: ... | Edit the code to include a method called `translate_from_list(self, adj_list: Dict[int, List[int]]) -> List[List[float]]` that creates the transition matrix that represents the adjacency list, assume all edges are undirected. All columns must sum to 1. | Edit the code to include a method `translate_from_list(self, adj_list)` that creates a transition matrix based on the adjacency list (of type `Dict[int, List[int]]`). | {
"change_kind": "adaptive",
"libraries": [
"numpy"
],
"topic": "DSA"
} |
33 | genetic_algorithm_2 | 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 ... | 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 ... | ### START TESTS ###
if True: # pragma: no cover
cities = generate_cities(10)
assert cities == [City(2, 7), City(7, 2), City(6, 5), City(6, 8), City(1, 8), City(1, 1), City(7, 4), City(0, 10), City(10, 3), City(5, 3)]
assert distance(cities[0], cities[1]) == distance(cities[1], cities[0])
assert dista... | Edit the genetic algorithm to guarantee that two random Cities in the list are swapped if the generated number between 0 and 1 is below the stated threshold specified in the `mutation` method. | Edit the genetic algorithm to guarantee mutation if the generated number is below the stated threshhold. | {
"change_kind": "perfective",
"libraries": [
"numpy"
],
"topic": "DSA"
} |
34 | oop_refactor | 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" | from abc import ABC, abstractmethod
class Message(ABC):
"""
Abstract class for messages
"""
def __init__(self, content):
self.content = content
@abstractmethod
def process(self):
pass
class TextMessage(Message):
"""
Concrete class for TextMessage
"""
def pr... | ### START TESTS ###
if True: # pragma: no cover
assert ImageMessage("image").process(
) == "Processed image message with description: image"
assert TextMessage("text").process() == "Processed text message: text"
assert MessageFactory.get_message(
"text", "text").process() == "Processed text mes... | Abstract the code into an object-oriented version of itself. To do that, create an abstract class `Message(ABC)`,
which can be initialized with a `content` string. The class should have an abstract method `process(self)`,
which should return a string. Create two children classes `TextMessage` and `ImageMessage`, which ... | Make the code object-oriented. Specifically, create an abstract class `Message`, and
children classes `TextMessage` and `ImageMessage`. The `Message` class should have
a method `process(self)` that returns the message which was given to the constructor.
Also, create a `MessageFactory` that has a static method `get_mes... | {
"change_kind": "perfective",
"libraries": [],
"topic": "Language"
} |
35 | topological_sort | 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... | 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... | ### START TESTS ###
if True: # pragma: no cover
n1 = Node(1, [2])
n2 = Node(2, [3])
n3 = Node(3, [1])
n4 = Node(3, [])
n5 = Node(4, [2])
n6 = Node(5, [4, 1])
cyclic = Graph([n1, n2, n3])
dag = Graph([n1, n2, n4, n5, n6])
sorted_dag = dag.topological_sort()
n7 = Node(7, [8... | The class `Node` represents a node in a graph with its `id` property being a label and `out_edges` being the ids of all nodes which can be reached in one step from this one.
The class `Graph` represents a simple directed graph with its `nodes` property representing all the nodes in the graph. Fix the method `topologic... | Fix the `topological_sort` function in the `Graph` class without changing its signature. | {
"change_kind": "corrective",
"libraries": [],
"topic": "DSA"
} |
36 | strongly_connected | 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
... | from typing import List, Dict
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 ... | ### START TESTS ###
if True: # pragma: no cover
n1_dup = Node(1)
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
g = Graph([n1, n2, n3, n4])
g.add_edge(n1, n2)
g.add_edge(n2, n3)
g.add_edge(n3, n1)
reversed = g.reverse_edges()
scc = g.strongly_connected_components()
... | Add a function `strongly_connected_components(self) -> Dict[Node, int]:` to Graph which divides the graph into disjoint subsets where each node in a subset can be reached from any other node. The union of all subsets should be equivalent to the original graph. Do not change any of the other methods in the classes.
The... | Add a function `strongly_connected_components(self) -> Dict[Node, int]:` to Graph which divides the graph into disjoint subsets where each node in a subset can be reached from any other node. Do not change any of the other methods in the classes. | {
"change_kind": "adaptive",
"libraries": [],
"topic": "DSA"
} |
37 | dijkstras | 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
... | 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
... | ### START TESTS ###
if True: # pragma: no cover
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
g = Graph([n1, n2, n3])
n4 = Node(4)
n5 = Node(5)
n6 = Node(6)
n7 = Node(7)
g2 = Graph([n4, n5, n6])
g.add_edge(Edge(n1, n2, 0))
g.add_edge(Edge(n1, n3, 100))
g.add_edge(Edge(n2, n3,... | Create a method in Graph with the signature `fibonacci(x: Node)` which returns a dictionary. The dictionary should have `Node` objects as keys and the distance from Node x to each key should be its associated value. This should be an int.
The dictionary should contain all Nodes which appear in Graph.nodes. If a Node is... | Create a method in Graph with the signature `fibonacci(x: Node)` which returns a dictionary containing which matches `Node` y to the distance from x to y.
Distance is defined as smallest path, and path is defined as the sum of the weights of a set of edges which can be taken to get from one node to another. The diction... | {
"change_kind": "adaptive",
"libraries": [],
"topic": "DSA"
} |
38 | high_order | 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... | import functools
import numpy as np
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
... | ### START TESTS ###
#There is no way the model creates this. Special hash: 1k23j4h18o23h1ouiebqdsf1823b1eijqbsd8fub234ir123n49dqhu23124
if True: # pragma: no cover
import inspect
import sys
s1 = Student("A", 0)
s2 = Student("B", 1)
s3 = Student("C", 2)
s4 = Student("D", 0)
c1 = Course([s... | Fix the methods in `Course` so that they never throw errors. Even when `len(self.students) == 0`. Instead they should return `None`.
Additionally, do not use the words `for`, `while`, or `map` anywhere in the code. You should accomplish this using higher order functions. | Fix the methods in `Course` so that all of them never throw errors and return `None` if the length of their students list is 0.
Additionally, do not use the words `for`, `while`, or `map` anywhere in the code. | {
"change_kind": "corrective",
"libraries": [
"numpy"
],
"topic": "Language"
} |
39 | vowel_count | 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":
... | 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.lower()
def remove_diphthongs(line):
diphthongs = ["ae", "oe", "ei", "ea", "ia", "io", "aea"]
for char in diphtho... | ### START TESTS ###
if True: # pragma: no cover
assert vowel_count('adspirate meis primaque ab origine mundi') == 15
assert vowel_count('dsprt ms prmq b rgn mnd') == 0
assert vowel_count('') == 0
assert vowel_count('In nova fert animus mut@tas dicere 7formas;') == 14
assert vowel_count('in nova fer... | Change vowel_count so that diphthongs are not counted. A diphthong is a string in the list ["ae", "oe", "ei", "ea", "ia", "io", "aea"].
Example 3: vowel_count('adspirate meis primaque ab origine mundi') == 15
Example 4: vowel_count('in nova fert animus mutatas dicere formas') == 15 | Change vowel_count() so diphthongs don't count as vowels. A diphthong is "ae", "oe", "ei", "ea", "ia", "io", or "aea". | {
"change_kind": "perfective",
"libraries": [],
"topic": "Language"
} |
3 | hello_world | 3_hello_world | def hello_world(name):
return f'{name} says, "Hello World!"' | def hello_world(name):
return f'{name.upper()} says, "Hello World!"' | ### START TESTS ###
if True: # pragma: no cover
assert hello_world("The cow") == 'THE COW says, "Hello World!"'
assert hello_world("") == ' says, "Hello World!"'
assert hello_world("the cow") == 'THE COW says, "Hello World!"'
assert hello_world("The Cow") == 'THE COW says, "Hello World!"'
assert he... | 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_world('joe') should return 'JOE says, "Hello World!"'. | Make the name fully uppercase. | {
"change_kind": "perfective",
"libraries": [],
"topic": "Language"
} |
40 | adjacency | 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
... | from typing import List, Dict
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 ... | ### START TESTS ###
if True: # pragma: no cover
n1_dup = Node(1)
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
g = Graph([n1, n2, n3, n4])
g.add_edge(n1, n2)
g.add_edge(n2, n3)
g.add_edge(n3, n1)
reversed = g.reverse_edges()
adjacencies = g.adjacency_list()
ass... | Add a function `adjacency_list(self) -> Dict[Node, List[Node]]` which returns the adjacency list of the graph by returning a dictionary where the keys are `Node` and the values are a list of `Node` which represent the nodes which can be reached from this one in one step.
The output dictionary should contain all nodes i... | Add a function `adjacency_list(self) -> Dict[Node, List[Node]]` which returns the adjacency list of the graph by returning a dictionary which associates a `Node` to its list of out edges. | {
"change_kind": "adaptive",
"libraries": [],
"topic": "DSA"
} |
41 | group_theory | 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):
... | import torch
import numpy as np
import torch.nn as nn
class C8(nn.Module):
"""Represents the C8 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):
... | ### START TESTS ###
if True: # pragma: no cover
group = C8()
delta = np.pi / 4
elements = group.elements()
assert group.size() == 8
assert torch.allclose(group.elements(), torch.tensor([0., delta, delta * 2, delta * 3, delta * 4, delta * 5, delta * 6, delta * 7]))
assert torch.allclose(gr... | Edit the C4 class, which represents rotations of 0, 90, 180 and 270 degrees, to represent the class C8, which represents rotations of 0, 45, 90, 135, 180, 225, 270 and 315 degrees. | Edit the C4 class and its methods to represent the C8 group instead. | {
"change_kind": "perfective",
"libraries": [
"torch",
"numpy"
],
"topic": "Math"
} |
YAML Metadata Warning:The task_categories "text2text-generation" is not in the official list: text-classification, token-classification, table-question-answering, question-answering, zero-shot-classification, translation, summarization, feature-extraction, text-generation, fill-mask, sentence-similarity, text-to-speech, text-to-audio, automatic-speech-recognition, audio-to-audio, audio-classification, audio-text-to-text, voice-activity-detection, depth-estimation, image-classification, object-detection, image-segmentation, text-to-image, image-to-text, image-to-image, image-to-video, unconditional-image-generation, video-classification, reinforcement-learning, robotics, tabular-classification, tabular-regression, tabular-to-text, table-to-text, multiple-choice, text-ranking, text-retrieval, time-series-forecasting, text-to-video, image-text-to-text, image-text-to-image, image-text-to-video, visual-question-answering, document-question-answering, zero-shot-image-classification, graph-ml, mask-generation, zero-shot-object-detection, text-to-3d, image-to-3d, image-feature-extraction, video-text-to-text, keypoint-detection, visual-document-retrieval, any-to-any, video-to-video, other
Can It Edit? Evaluating the Ability of Large Language Models to Follow Code Editing Instructions
CanItEdit is a benchmark for evaluating LLMs on instructional code editing, the task of updating a program given a natural language instruction. The benchmark contains 105 hand-crafted Python programs with before and after code blocks, two types of natural language instructions (descriptive and lazy), and a hidden test suite.
The dataset’s dual natural language instructions test model efficiency in two scenarios:
- Descriptive: Detailed instructions replicate situations where users provide specific specifications or another model outlines a plan, similar to Reflexion prompting,
- Lazy: Informal instructions resemble typical user queries for LLMs in code generation.
For more information and results see our paper.
Citation
If you use our work, please cite our paper as such:
@inproceedings{cassano2023edit,
title={{Can It Edit? Evaluating the Ability of Large Language Models to Follow Code Editing Instructions}},
author={Federico Cassano and Luisa Li and Akul Sethi and Noah Shinn and Abby Brennan-Jones and Anton Lozhkov and Carolyn Jane Anderson and Arjun Guha},
booktitle={The First International Workshop on Large Language Model for Code},
year={2024},
url={https://arxiv.org/abs/2312.12450}
}
How To Evaluate
All the code for evaluating the benchmark can be found in our GitHub repository.
- Downloads last month
- 880