id
stringlengths
32
32
input
stringlengths
181
3.45k
output
stringlengths
284
35.2k
domain
stringclasses
2 values
generation_algorithm
stringclasses
2 values
llm_judgement
stringlengths
446
1.62k
unit_tests
stringlengths
277
6.65k
tests_execution_status
stringclasses
708 values
average_test_score
stringclasses
11 values
45ec4865601377389e9590693d52df71
You are tasked with implementing a custom sorting algorithm in Python to sort a list of integers in ascending order. Your function should be named `custom_sort`. The algorithm you choose to implement must be either bubble sort or selection sort. Your function should return the sorted list. **Input:** - A list of integ...
Here's an implementation of the **selection sort** algorithm in Python, as requested. The function `custom_sort` will sort the input list in ascending order. ### ✅ Selection Sort Implementation: ```python def custom_sort(arr): # Selection Sort implementation n = len(arr) for i in range(n): # Find ...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirement by implementing a custom sorting algorithm (selection sort) that sorts a list of integers in ascending order and is named `custom_sort`."}, "logical_correctness": {"score": 5, "justification": "The logic of the selection...
["\nassert custom_sort([64, 25, 12, 22, 11]) == [11, 12, 22, 25, 64]\n", "\nassert custom_sort([5, 2, 9, 1, 5, 6]) == [1, 2, 5, 5, 6, 9]\n", "\nassert custom_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]\n", "\nassert custom_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]\n", "\nassert custom_sort([]) == []\n", "\nassert custom_so...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
677939876b07542e01433f5406ed0a25
You are given a directed graph with `n` nodes and `m` edges. Each node `i` has an associated profit `p_i`, and each edge `j` connecting node `u_j` to node `v_j` has an associated cost `c_j`. Your task is to find a path starting from node 1 that maximizes the total profit minus the total cost. If multiple paths yield th...
To solve this problem, we need to find a path starting from **node 1** in a **directed graph** that **maximizes the total profit minus the total cost**. Each node has a **profit**, and each edge has a **cost**. So, for any path, the total value is: $$ \text{Total Value} = \sum (\text{profit of nodes}) - \sum (\text{co...
algorithmic
self-instruct
{"requirement_conformance": {"score": 4, "justification": "The solution addresses the main requirement of finding a path starting from node 1 that maximizes the total profit minus the total cost. However, it does not handle the case where no path exists from node 1 to any other node, which could result in an incorrect ...
["\nassert max_profit_minus_cost(1, 0, [10], []) == 10\n", "\nassert max_profit_minus_cost(2, 1, [10, 20], [(1, 2, 5)]) == 25\n", "\nassert max_profit_minus_cost(3, 2, [10, 20, 30], [(1, 2, 5), (2, 3, 10)]) == 45\n", "\nassert max_profit_minus_cost(3, 2, [10, 20, 30], [(1, 2, 25), (2, 3, 10)]) == 10\n", "\nassert max_p...
["pass", "pass", "pass", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0.3
59922d1e09a12101a8018344e6f34b44
You are tasked with implementing a function to display a tree structure in the console. The tree is represented as a dictionary where each key is a node name and each value is a list of its child node names. Your function should print the tree starting from the root node, with each level of the tree indented by two spa...
Here's a Python function that prints a tree structure in the console, with each level indented by two spaces: ```python def print_tree(tree, root, indent=0): print(" " * indent + root) for child in tree[root]: print_tree(tree, child, indent + 1) # Example usage: tree = { "root": ["child1", "child...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirements by correctly printing the tree structure with each level indented by two spaces."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and optimally structured. The function uses recur...
["\nassert print_tree({\"root\": [\"child1\", \"child2\"]}, \"root\") == \"root\\n child1\\n child2\"\n", "\nassert print_tree({\"root\": [\"child1\"]}, \"root\") == \"root\\n child1\"\n", "\nassert print_tree({\"root\": []}, \"root\") == \"root\"\n", "\nassert print_tree({\"root\": [\"child1\", \"child2\"], \"child...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
fd546ced41c1bc61f2e0254a837b2484
You are given the task of simulating the placement of `n` stars in a spiral constellation centered at the origin (0,0) on a 2D plane. The first star should be positioned at the topmost point (0, radius). The stars must be distributed along a logarithmic spiral defined by the equation `r = a * e^(b * θ)`, where `a` and ...
To simulate the placement of `n` stars in a **logarithmic spiral** constellation, we need to: 1. **Understand the logarithmic spiral**: The equation of a logarithmic spiral is: $$ r = a \cdot e^{b \cdot \theta} $$ where: - `r` is the radial distance from the origin. - `θ` is the angle in radians. ...
generic
evol-instruct
{"requirement_conformance": {"score": 4, "justification": "The function generates a spiral pattern of stars and returns a list of tuples representing the coordinates. It meets the basic requirements but could benefit from more detailed specifications for constants a and b, and the angle increment calculation could be m...
["\nassert len(generate_constellation(1)) == 1\n", "\nassert generate_constellation(1) == [(0.0, 1.0)]\n", "\nassert len(generate_constellation(5)) == 5\n", "\nassert generate_constellation(0) == []\n", "\nassert generate_constellation(2)[0][1] > generate_constellation(2)[1][1]\n", "\nassert generate_constellation(3)[0...
["pass", "fail", "pass", "fail", "fail", "fail", "pass", "fail", "fail", "pass"]
0.4
09904b654c87c0697844fcf03431e7d4
You are given a string `s`. Your task is to write a function `count_vowels_consonants` that processes the string and returns a dictionary with two keys: `'vowels'` and `'consonants'`. The values associated with these keys should represent the number of vowels and consonants in the string, respectively. The function sho...
Here's a Python function that meets your requirements: ```python def count_vowels_consonants(s): vowels = set("aeiouAEIOU") vowels_count = 0 consonants_count = 0 for char in s: if char.isalpha(): if char in vowels: vowels_count += 1 else: ...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets all the specified requirements. It takes a string as input, returns a dictionary with counts of vowels and consonants, ignores non-alphabetic characters, and is case-insensitive."}, "logical_correctness": {"score": 5, "justification": "...
["\nassert count_vowels_consonants(\"Hello, World!\") == {'vowels': 3, 'consonants': 7}\n", "\nassert count_vowels_consonants(\"Python Programming\") == {'vowels': 4, 'consonants': 11}\n", "\nassert count_vowels_consonants(\"AEIOU\") == {'vowels': 5, 'consonants': 0}\n", "\nassert count_vowels_consonants(\"bcdfg\") == ...
["pass", "fail", "pass", "pass", "pass", "pass", "fail", "pass", "pass", "pass"]
0.8
c9023f53e0045f9faf7d58cfc1a6a3a8
You are given a hypergraph `H` represented as a list of edges, where each edge is a set of nodes. Your task is to compute the s-centrality of nodes or edges in the hypergraph using a provided centrality measure function `func`. The s-centrality should be calculated without modifying or removing any edges from the hyper...
To compute the **s-centrality** of nodes in a hypergraph using a provided centrality measure function `func`, we need to: 1. **Convert the hypergraph into a NetworkX Graph**. 2. **Apply the given centrality function** to the graph. 3. **Return the result as a dictionary**. However, there's a key point to clarify: **s...
generic
evol-instruct
{"requirement_conformance": {"score": 3, "justification": "The solution converts the hypergraph to a simple graph and computes centrality using the provided function. However, it does not explicitly handle the s-centrality measure, which is a specific type of centrality measure for hypergraphs. The solution also does n...
["\nassert compute_s_centrality([{'a', 'b'}, {'b', 'c'}], nx.degree_centrality) == {'a': 0.5, 'b': 1.0, 'c': 0.5}\n", "\nassert compute_s_centrality([{'x', 'y', 'z'}, {'x', 'w'}], nx.degree_centrality) == {'x': 1.0, 'y': 0.5, 'z': 0.5, 'w': 0.5}\n", "\nassert compute_s_centrality([{'a', 'b', 'c'}, {'b', 'c', 'd'}, {'d'...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
fbbb0c0887a9a0c73bd3a8120ee916e6
You are given a sequence of integers. Your task is to implement a function `sum_of_even_elements` that computes the sum of all even numbers in the sequence. The sequence can be a list, tuple, or range of integers. If the sequence is a list or tuple and contains more than 5 even numbers, return the sum of these even num...
To solve this problem, we need to: 1. **Identify even numbers** in the given sequence. 2. **Check if the sequence is a list or tuple** and contains **more than 5 even numbers**. 3. If so, **sort the even numbers in ascending order** and compute their **sum**. 4. Otherwise, just **sum the even numbers** as usual. Here...
generic
evol-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets all specified requirements, including handling different types of input sequences and the additional requirement of sorting and summing even numbers when the sequence is a list or tuple with more than 5 even numbers."}, "logical_correct...
["\nassert sum_of_even_elements([1, 2, 3, 4, 5]) == 6\n", "\nassert sum_of_even_elements(range(1, 11)) == 30\n", "\nassert sum_of_even_elements((1, 3, 5, 7, 9)) == 0\n", "\nassert sum_of_even_elements([10, 2, 8, 4, 6, 12, 14, 16]) == 60\n", "\nassert sum_of_even_elements([2, 4, 6, 8, 10]) == 30\n", "\nassert sum_of_eve...
["pass", "pass", "pass", "fail", "pass", "pass", "pass", "pass", "pass", "pass"]
0.9
a60116ba63b3ef08f472bde38f8f9633
You are given a list of distinct integers `elements` and an integer `n`. Your task is to write a function `generate_combinations` that returns all possible combinations of `n` elements from the `elements` list. The function should utilize Python's `itertools` module to generate these combinations. The original list sho...
Here's the implementation of the `generate_combinations` function that meets your requirements: ```python import itertools def generate_combinations(elements, n): # Check if n is greater than the length of elements if n > len(elements): return [] # Generate all combinations of size n using it...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets the requirements by using the itertools module to generate combinations and handling cases where n is greater than the length of the elements list."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct...
["\nassert generate_combinations([1, 2, 3, 4], 2) == [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]\n", "\nassert generate_combinations([1, 2, 3], 4) == []\n", "\nassert generate_combinations(['a', 'b', 'c'], 2) == [('a', 'b'), ('a', 'c'), ('b', 'c')]\n", "\nassert generate_combinations([], 1) == []\n", "\nassert gen...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
3a0e0f6ee90a20df30951c09c29ada0d
You are tasked with implementing a `Matrix` class in Python that supports basic matrix operations. The class should be able to handle the following operations: 1. **Initialization**: Create a matrix from a given list of lists (rows). 2. **Addition**: Add two matrices of the same dimensions. 3. **Subtraction**: Subtrac...
Here's a complete implementation of the `Matrix` class in Python that supports all the required operations, including error handling and a clean string representation: ```python class Matrix: def __init__(self, data): # Validate input if not all(isinstance(row, list) for row in data): r...
generic
self-instruct
{"requirement_conformance": {"score": 4, "justification": "The class meets most of the specified requirements, including initialization, addition, subtraction, multiplication, transposition, determinant calculation, and string representation. However, it does not include a check for the size attribute in the constructo...
["\nassert str(Matrix([[1, 2], [3, 4]])) == \"1\\t2\\n3\\t4\"\n", "\nassert (Matrix([[1, 2], [3, 4]]) + Matrix([[5, 6], [7, 8]])).data == [[6, 8], [10, 12]]\n", "\nassert (Matrix([[1, 2], [3, 4]]) - Matrix([[1, 1], [1, 1]])).data == [[0, 1], [2, 3]]\n", "\nassert (Matrix([[1, 2], [3, 4]]) * Matrix([[2, 0], [1, 2]])).da...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
07ef99918679cecd9602bbdee0ee65ee
You are given three integers `a`, `b`, and `c`. Your task is to implement a function `rotate_numbers(a, b, c)` that returns a tuple with the integers rotated in the following manner: the first integer should move to the second position, the second integer should move to the third position, and the third integer should ...
To rotate the numbers such that: - `a` → second position - `b` → third position - `c` → first position We can achieve this by returning a tuple in the order `(c, a, b)`. Here's the implementation of the function: ```python def rotate_numbers(a, b, c): return (c, a, b) ``` ### Example: ```python print(rotate_n...
generic
evol-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets the requirement by correctly rotating the input integers and returning them in the specified order."}, "logical_correctness": {"score": 5, "justification": "The logic of the function is completely correct and directly implements the req...
["\nassert rotate_numbers(1, 2, 3) == (3, 1, 2)\n", "\nassert rotate_numbers(4, 5, 6) == (6, 4, 5)\n", "\nassert rotate_numbers(0, 0, 0) == (0, 0, 0)\n", "\nassert rotate_numbers(-1, -2, -3) == (-3, -1, -2)\n", "\nassert rotate_numbers(10, 20, 30) == (30, 10, 20)\n", "\nassert rotate_numbers(100, 200, 300) == (300, 100...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
b6dbfa73932fba72ffdad2685940342e
You are tasked with implementing a function `is_palindrome` that checks if a given string is a palindrome. A string is considered a palindrome if, after removing all non-alphanumeric characters and converting all uppercase letters to lowercase, it reads the same forwards and backwards. Your function should return `True...
Here's a Python function `is_palindrome` that meets your requirements: ### ✅ Key Points: - **No regex or built-in string methods** for removing non-alphanumeric characters. - **Case-insensitive** comparison. - **In-place processing** to avoid extra memory usage. - Efficient for large strings (up to 100,000 characters)...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets the requirements by considering only alphanumeric characters, ignoring case, and returning the correct boolean value for palindrome checking."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct. The ...
["\nassert is_palindrome(\"A man, a plan, a canal: Panama\") == True\n", "\nassert is_palindrome(\"race a car\") == False\n", "\nassert is_palindrome(\"No 'x' in Nixon\") == True\n", "\nassert is_palindrome(\"Was it a car or a cat I saw?\") == True\n", "\nassert is_palindrome(\"12321\") == True\n", "\nassert is_palindr...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
2946f9b1e5009eb04a124cdfd9b7548b
You are given a text file named "data.txt". Your task is to write a program that reads this file and counts the frequency of each word, excluding common stop words. The stop words are: "the", "and", "is", "in", "at", "which", "on", "a", "an". The comparison for stop words should be case-insensitive. The output should l...
Here's a Python program that reads the `data.txt` file, counts the frequency of each word (excluding the specified stop words), and prints the results in descending order of frequency. ### ✅ Python Code: ```python from collections import Counter import re # List of stop words (case-insensitive) stop_words = {"the", ...
algorithmic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets all specified requirements. It reads a text file, counts the number of times each word appears, ignores common stop words in a case-insensitive manner, and outputs the count of each word in descending order of frequency."}, "logical_cor...
["\nassert word_count('empty.txt') == None\n", "\nassert word_count('single_word.txt') == None\n", "\nassert word_count('stop_words_only.txt') == None\n", "\nassert word_count('mixed_case.txt') == None\n", "\nassert word_count('punctuation.txt') == None\n", "\nassert word_count('multiple_lines.txt') == None\n", "\nasse...
["fail", "pass", "pass", "fail", "pass", "pass", "fail", "fail", "fail", "fail"]
0.4
ada5f48d6e408a6af5cb7bec05351a3d
You are tasked with implementing a Python class `Employee` to manage employee details in a company's database. The class should support the following functionalities: - Initialize an employee with a name, ID, department, and salary. - Provide a method to give a raise to the employee, which increases the salary by a sp...
Here's the implementation of the `Employee` class in Python that meets all the specified requirements: ```python class Employee: def __init__(self, name, id, department, salary): self.name = name self.id = id self.department = department self.salary = salary def give_raise(self...
generic
self-instruct
{"requirement_conformance": {"score": 3, "justification": "The class meets basic requirements by including the specified attributes and methods, but it does not include any additional methods or properties that might be expected in a more comprehensive Employee class."}, "logical_correctness": {"score": 4, "justificati...
["\nassert Employee(\"John Doe\", 1, \"HR\", 50000).name == \"John Doe\"\n", "\nassert Employee(\"Jane Smith\", 2, \"Engineering\", 75000).id == 2\n", "\nassert Employee(\"Alice Johnson\", 3, \"Marketing\", 60000).department == \"Marketing\"\n", "\nassert Employee(\"Bob Brown\", 4, \"Finance\", 80000).salary == 80000\n...
["pass", "pass", "pass", "pass", "fail", "pass", "pass", "pass", "pass", "pass"]
0.9
897396a94bdeb10a842a66c3cabf216f
You are given a list of `n` intervals, where each interval is represented by a pair of integers `(start, end)`. Your task is to calculate the total overlap between all pairs of intervals. The overlap between two intervals is defined as the length of their intersection. If two intervals do not intersect, their overlap i...
To solve the problem of calculating the **total overlap between all pairs of intervals**, we can follow these steps: --- ### ✅ **Approach:** 1. **Sort the intervals** by their **start points**. 2. For **each pair of intervals**, compute the **overlap** between them. 3. Sum up the overlaps for all **unordered pairs**...
generic
evol-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets all specified requirements. It sorts the intervals by their start points and calculates the total overlap between all pairs of intervals."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and optim...
["\nassert total_overlap([(1, 5), (3, 7), (2, 4), (6, 8)]) == 6\n", "\nassert total_overlap([(1, 3), (4, 6), (7, 9)]) == 0\n", "\nassert total_overlap([(1, 10), (2, 5), (3, 7)]) == 8\n", "\nassert total_overlap([(5, 10), (10, 15), (15, 20)]) == 0\n", "\nassert total_overlap([(1, 2), (2, 3), (3, 4)]) == 0\n", "\nassert ...
["pass", "pass", "fail", "pass", "pass", "pass", "pass", "fail", "pass", "pass"]
0.8
f1e5ef7044585a580153c15d6d06e0d7
Chef and Chefu are eagerly looking to purchase cakes of equal price from a cake shop. Chef has coins of denomination $N$ and Chefu has coins of denomination $M$. They wish to determine the minimum amount they must spend to buy cakes such that each of them pays an equal amount using only their respective coins. Implemen...
To solve this problem, we need to find the **Least Common Multiple (LCM)** of two integers $ N $ and $ M $, which represents the **minimum amount** both Chef and Chefu must spend such that they each pay the same amount using their respective coin denominations. ### Key Insight: The **LCM** of two numbers $ N $ and $ M...
algorithmic
evol-instruct
{"requirement_conformance": {"score": 3, "justification": "The solution attempts to find the minimum amount to be spent by calculating the LCM of the two denominations. However, it does not fully meet the requirement of not using multiplication or division operations, as it uses division in the calculation of the LCM."...
["\nassert minimum_amount(12, 18) == 36\n", "\nassert minimum_amount(5, 10) == 10\n", "\nassert minimum_amount(7, 3) == 21\n", "\nassert minimum_amount(21, 6) == 42\n", "\nassert minimum_amount(8, 12) == 24\n", "\nassert minimum_amount(1, 1) == 1\n", "\nassert minimum_amount(13, 17) == 221\n", "\nassert minimum_amount(...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
6066118a6c1e9af805f3b37e8b7ed55d
You are tasked with writing a program that reads a JSON file and retrieves the value associated with a specified key. Your program should prompt the user to input the filename and the key. The program must handle the following scenarios: - If the file does not exist, output an error message: "Error: The file '{filename...
Here's a Python program that fulfills your requirements. It reads a JSON file, prompts the user for the filename and key, and handles the specified error scenarios. ```python import json import os def read_json_value(filename, key): try: # Check if the file exists if not os.path.exists(filename): ...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The program fully meets all specified requirements. It prompts the user for the file name and key, handles cases where the file does not exist, and handles cases where the key is not found in the JSON file."}, "logical_correctness": {"score": 5, "justification"...
["\nassert read_json_key(\"data.json\", \"name\") == \"John\"\n", "\nassert read_json_key(\"data.json\", \"age\") == 30\n", "\nassert read_json_key(\"data.json\", \"address\") == \"Key 'address' not found in the JSON data.\"\n", "\nassert read_json_key(\"non_existent_file.json\", \"name\") == \"Error: The file 'non_exi...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
d55496138ee703c02f2732b0ed19c799
You are tasked with developing a keyword extraction system for a document analysis project. Implement a function `extract_keywords(text: str, num_keywords: int) -> List[str]` that processes a given text and identifies the top `num_keywords` most frequently occurring words. The function should handle punctuation and be ...
Here's a Python function that implements the `extract_keywords` function as described. It processes the input text to extract the top `num_keywords` most frequent words, handling punctuation and being case-insensitive. ```python import re from collections import Counter from typing import List def extract_keywords(te...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets the requirements by taking a string `text` and an integer `num_keywords` as input and returning a list of the top `num_keywords` most frequent words in the text. It also considers punctuation and case sensitivity."}, "logical_correctnes...
["\nassert extract_keywords(\"hello world hello\", 1) == [\"hello\"]\n", "\nassert extract_keywords(\"test test test test\", 2) == [\"test\"]\n", "\nassert extract_keywords(\"a b c d e f g\", 3) == [\"a\", \"b\", \"c\"]\n", "\nassert extract_keywords(\"Python is great, and python is fun.\", 2) == [\"python\", \"is\"]\n...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
0fb19322cc1987058b2f94ebe9b56c82
You are given a function `f(x1, x2, ..., xn) = x1^2 + x2^2 + ... + xn^2` where each variable `xi` must be an integer between 1 and 10 inclusive. Your task is to find the set of integers `(x1, x2, ..., xn)` that minimizes the function `f`. Implement a genetic algorithm to solve this optimization problem. Your program sh...
To solve this optimization problem using a **Genetic Algorithm (GA)**, we need to follow these steps: ### **Key Concepts:** - **Fitness Function:** `f(x1, x2, ..., xn) = x1² + x2² + ... + xn²` - **Goal:** Minimize the function, so **lower fitness is better**. - **Constraints:** Each `xi` must be an integer between 1 a...
algorithmic
self-instruct
{"requirement_conformance": {"score": 4, "justification": "The solution addresses the main requirements of implementing a genetic algorithm to optimize the sum of squares function with constraints on variable values. However, it does not specify the exact number of variables or generations, which are part of the proble...
["\nassert genetic_algorithm(10, 1, 10)[1] >= 1 and genetic_algorithm(10, 1, 10)[1] <= 100\n", "\nassert genetic_algorithm(20, 2, 20)[1] >= 2 and genetic_algorithm(20, 2, 20)[1] <= 200\n", "\nassert genetic_algorithm(30, 3, 30)[1] >= 3 and genetic_algorithm(30, 3, 30)[1] <= 300\n", "\nassert all(1 <= x <= 10 for x in g...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
31803e17ff08a171b7c1bceb2ae258b2
You are given a list of distinct words `W` and a list of tuples `T`. Each tuple in `T` contains a sequence of words. Your task is to construct a new list of tuples `T'` where each tuple is formed by removing the first word from the corresponding tuple in `T` and appending a new word from `W`. The new word must not alre...
To solve this problem, we need to process each tuple in the list `T` as follows: 1. **Remove the first word** from the tuple. 2. **Append a new word** from the list `W`: - The new word must **not already be in the tuple**. - It should be the **next word in `W` in a circular manner** (i.e., wrap around to the beg...
generic
evol-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets all specified requirements. It removes the first word from each tuple, appends a new word from the list of words, and ensures no word is repeated within a single tuple."}, "logical_correctness": {"score": 5, "justification": "The logic ...
["\nassert transform_tuples([\"apple\", \"banana\", \"cherry\"], [(\"orange\", \"banana\"), (\"cherry\", \"date\")]) == [(\"banana\", \"apple\"), (\"date\", \"banana\")]\n", "\nassert transform_tuples([\"apple\", \"banana\", \"cherry\"], [(\"apple\", \"banana\"), (\"banana\", \"cherry\")]) == [(\"banana\", \"cherry\"),...
["pass", "fail", "pass", "pass", "pass", "pass", "fail", "fail", "pass", "fail"]
0.6
4968e29cd2aaded9b8613650a17f50c0
You are given two dictionaries, `dict1` and `dict2`. Your task is to update `dict1` in-place with values from `dict2` under the following conditions: - Only update the values of keys that are present in both `dict1` and `dict2`. - A value in `dict1` should only be updated if the corresponding value in `dict2` is strict...
Here's the Python function that performs the described operation: ```python def merge_dicts(dict1: dict, dict2: dict) -> dict: for key in dict1: if key in dict2 and dict2[key] > dict1[key]: dict1[key] = dict2[key] return dict1 ``` ### Explanation: - We iterate through the keys of `dict1`. ...
generic
evol-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets all specified requirements. It updates the values of `dict1` in-place only if the corresponding value in `dict2` is strictly greater, and it does not modify the keys of `dict1`."}, "logical_correctness": {"score": 5, "justification": "T...
["\nassert merge_dicts({'a': 1, 'b': 2}, {'b': 3, 'c': 4}) == {'a': 1, 'b': 3}\n", "\nassert merge_dicts({'x': 10, 'y': 20}, {'x': 5, 'y': 25}) == {'x': 10, 'y': 25}\n", "\nassert merge_dicts({'m': 100, 'n': 200}, {'m': 100, 'n': 200}) == {'m': 100, 'n': 200}\n", "\nassert merge_dicts({'p': 1, 'q': 2}, {'r': 3, 's': 4}...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
388dd359dc4decd2fc8b601ea4f6d9d9
You are given a list of convex polygons, each defined by the number of its sides. For each polygon, determine the number of ways to draw non-intersecting diagonals inside it. Output a list of these counts. **Input:** - The first line contains an integer `T` (1 ≤ T ≤ 100), the number of test cases. - Each of the next `...
To solve this problem, we need to compute the number of ways to draw **non-intersecting diagonals** inside a convex polygon with `N` sides. This is a well-known combinatorial problem related to **Catalan numbers**. --- ### 🧠 Key Insight: The number of ways to draw **non-intersecting diagonals** in a convex polygon ...
algorithmic
evol-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirements by calculating the number of non-intersecting diagonals for each polygon in the list using the Catalan number formula."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct. The soluti...
["\nassert non_intersecting_diagonals([3]) == [1]\n", "\nassert non_intersecting_diagonals([4]) == [1]\n", "\nassert non_intersecting_diagonals([5]) == [2]\n", "\nassert non_intersecting_diagonals([6]) == [5]\n", "\nassert non_intersecting_diagonals([7]) == [14]\n", "\nassert non_intersecting_diagonals([8]) == [42]\n",...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
a35b9faff916765db87cf32ed1fe1dbc
You are tasked with implementing a function `extract_emails` that identifies and extracts all valid email addresses from a provided text string. The function should utilize regular expressions to accurately match email addresses, accommodating various formats, including those with subdomains and special characters. You...
To solve the problem of extracting valid email addresses from a text string, we can use **regular expressions (regex)**. The goal is to match valid email formats while being flexible enough to handle common variations, such as subdomains, special characters in the local part, and multiple dots in the domain. ### ✅ **R...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets the requirement by extracting email addresses from a given text using regular expressions and handling different email formats, including those with subdomains and special characters."}, "logical_correctness": {"score": 4, "justificatio...
["\nassert extract_emails(\"contact@example.com\") == [\"contact@example.com\"]\n", "\nassert extract_emails(\"support@my-subdomain.example.co.uk\") == [\"support@my-subdomain.example.co.uk\"]\n", "\nassert extract_emails(\"admin@company.org\") == [\"admin@company.org\"]\n", "\nassert extract_emails(\"user.name+tag+sor...
["pass", "pass", "pass", "pass", "pass", "fail", "pass", "pass", "pass", "pass"]
0.9
3befca9a6d9ae69d1f6c548bf6cac1f7
You are given a message encrypted using a modified Vigenere cipher. In this variant, the ASCII value of each character in the key is offset by a random integer between -5 and 5 before being used to shift the characters in the ciphertext. Your task is to decrypt the message. The key is repeated as necessary to match the...
To decrypt the message, we need to reverse the encryption process of the modified Vigenère cipher. Here's how it works: ### **Encryption Process Recap (Modified Vigenère Cipher):** 1. Each character in the **key** is first offset by a value from the `offsets` list. 2. The ASCII value of the key character is adjusted b...
generic
evol-instruct
{"requirement_conformance": {"score": 4, "justification": "The solution addresses the core requirement of decrypting a message encrypted with a modified Vigenere cipher, considering an offset for each key character. However, it assumes the alphabet is based on ASCII values (0-255) rather than strictly alphabetic charac...
["\nassert decrypt_modified_vigenere(\"b\", \"a\", [1]) == \"a\"\n", "\nassert decrypt_modified_vigenere(\"a\", \"b\", [-1]) == \"a\"\n", "\nassert decrypt_modified_vigenere(\"f\", \"a\", [5]) == \"a\"\n", "\nassert decrypt_modified_vigenere(\"a\", \"f\", [-5]) == \"a\"\n", "\nassert decrypt_modified_vigenere(\"m\", \"...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
2ec799cdcce1ff1d9ceef1b7748fdce0
You are tasked with designing a RESTful API using Flask to manage a simple to-do list application. The API must support the following operations: 1. **GET /tasks**: Retrieve all tasks. 2. **POST /tasks**: Create a new task. The request body must be a JSON object with at least a 'title' field. 3. **GET /tasks/<task_id>...
Here's a complete implementation of a RESTful API using **Flask** to manage a simple to-do list application, based on your requirements. --- ## ✅ Requirements - **Python 3.7+** - **Flask** (Install via `pip install flask`) - **Flask-RESTful** (Optional, but can be used for better structure) --- ## 📁 Project Struc...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets all the specified requirements by implementing all the required RESTful API endpoints for managing a to-do list."}, "logical_correctness": {"score": 4, "justification": "The logic is largely correct and consistent, handling tasks approp...
["\nassert get_tasks().json == {'tasks': [{'id': 1, 'title': 'Buy groceries', 'description': 'Milk, Cheese, Pizza, Fruit', 'done': False}, {'id': 2, 'title': 'Learn Python', 'description': 'Need to find a good Python tutorial on the web', 'done': False}]}\n", "\nassert get_task(1).json == {'task': {'id': 1, 'title': 'B...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
5eb796d9734418c88a24c07bc1ac0a73
You are given a list of integers. Your task is to implement a function that computes the median of the list. The function should handle edge cases where the list is empty or contains only one element. **Input:** - A list of integers `lst` (0 ≤ len(lst) ≤ 10^5), where each integer `x` satisfies -10^9 ≤ x ≤ 10^9. **Ou...
Here's a Python function that computes the **median** of a list of integers, with proper handling of edge cases such as an empty list. ### ✅ Function Implementation: ```python def compute_median(lst): if not lst: raise ValueError("The list is empty") # Sort the list lst_sorted = sorted(lst) ...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets the requirements by calculating the median and handling edge cases where the list is empty or contains only one element."}, "logical_correctness": {"score": 5, "justification": "The logic for finding the median is completely correct and...
["\nassert find_median([1, 3, 5]) == 3\n", "\nassert find_median([1, 3, 5, 7]) == 4.0\n", "\nassert find_median([1]) == 1\n", "\nassert find_median([7, 3, 1, 5]) == 4.0\n", "\nassert find_median([10, 20, 30, 40, 50]) == 30\n", "\nassert find_median([1, 2, 3, 4, 5, 6]) == 3.5\n", "\nassert find_median([5, 5, 5, 5, 5]) =...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
827041a2e7bc57c884acc86d5e271e4f
You are given a list of distinct items. Your task is to write a function `generate_combinations` that generates all possible combinations of these items. The function should return a list of lists, where each inner list represents a unique combination of the items. The order of the combinations in the output does not m...
You can use Python's `itertools` module to generate all possible combinations of different lengths (from 0 to the length of the list). Here's the implementation of the `generate_combinations` function: ```python import itertools def generate_combinations(items): combinations = [] for r in range(len(items) + 1...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets the requirement by generating all possible combinations of the input list and returning them as a list of lists."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and optimally structured. It uses ...
["\nassert generate_combinations([]) == [[]]\n", "\nassert generate_combinations(['a']) == [[], ['a']]\n", "\nassert generate_combinations(['a', 'b']) == [[], ['a'], ['b'], ['a', 'b']]\n", "\nassert generate_combinations(['a', 'b', 'c']) == [[], ['a'], ['b'], ['c'], ['a', 'b'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]\...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
99dbb44e76ad466dc936f7976fff75ff
You are given a task to develop a program that verifies the integrity of a file by comparing its SHA-1 hash with a provided hash value. The program should handle case sensitivity and special characters in filenames across different operating systems. Your program will receive two inputs: a filename and a SHA-1 hash val...
Here's a Python program that verifies the integrity of a file by comparing its SHA-1 hash with a provided hash value. It handles case sensitivity and special characters in filenames, and works across different operating systems. ### ✅ Python Code: ```python import hashlib def compute_sha1_hash(filename): """Comp...
generic
evol-instruct
{"requirement_conformance": {"score": 4, "justification": "The solution addresses the main requirements of verifying file integrity using SHA-1 hash and handling filenames with case sensitivity and special characters. However, it does not explicitly handle cross-operating system differences in filename handling."}, "lo...
["\nassert verify_file_integrity(\"testfile.txt\", \"da39a3ee5e6b4b0d3255bfef95601890afd80709\") == False\n", "\nassert verify_file_integrity(\"testfile.txt\", \"2ef7bde608ce5404e97d5f042f95f89f1c232871\") == True\n", "\nassert verify_file_integrity(\"TestFile.txt\", \"2ef7bde608ce5404e97d5f042f95f89f1c232871\") == Fal...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
34f8c8f01f1f5968c940ea7f26b7e7df
You are tasked with developing a Python function `extract_keywords` that processes a given text and returns a list of the most frequent keywords. The function should utilize the Natural Language Toolkit (NLTK) for text processing and keyword extraction. The keywords should be limited to nouns, adjectives, verbs, and ad...
Here's a Python function `extract_keywords` that processes the given text using **NLTK** to extract the top `n` most frequent keywords, limited to **nouns, adjectives, verbs, and adverbs**, while ignoring **stopwords** and **punctuation**. ### ✅ Requirements: - Install NLTK if not already installed: ```bash pip in...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets the requirements by extracting the most frequent keywords from the input text using NLTK. It also allows specifying the number of top keywords to return."}, "logical_correctness": {"score": 5, "justification": "The logic is completely c...
["\nassert extract_keywords(\"The quick brown fox jumps over the lazy dog.\") == ['quick', 'brown', 'fox', 'jumps', 'lazy']\n", "\nassert extract_keywords(\"Python is great and Python is fun.\", top_n=2) == ['python', 'great']\n", "\nassert extract_keywords(\"NLTK is a leading platform for building Python programs to w...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
9be1cf77ab32f990d408e770baaa4d7c
You are tasked with implementing a function `filter_even_numbers` that processes a list of integers. Your goal is to return a new list consisting solely of the even numbers from the provided list. The current implementation utilizes a `for` loop, but you must refactor it to use a list comprehension. **Input:** - A li...
To refactor the function `filter_even_numbers` from using a `for` loop to using a **list comprehension**, we can take advantage of the concise syntax that list comprehensions provide in Python. Here's the implementation: ```python def filter_even_numbers(numbers): return [num for num in numbers if num % 2 == 0] `...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirement by rewriting the function using a list comprehension to filter even numbers."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and optimally structured, using a list comprehension t...
["\nassert filter_even_numbers([1, 2, 3, 4, 5, 6]) == [2, 4, 6]\n", "\nassert filter_even_numbers([10, 15, 20, 25, 30]) == [10, 20, 30]\n", "\nassert filter_even_numbers([11, 13, 17, 19]) == []\n", "\nassert filter_even_numbers([]) == []\n", "\nassert filter_even_numbers([0, -2, -4, -5]) == [0, -2, -4]\n", "\nassert fi...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
04e293f6f763e88e5c21786341ec7c2b
You are given a positive integer \( n \). Your task is to implement a function that computes the \( n \)-th Fibonacci number using memoization. The Fibonacci sequence is defined as follows: \( F(1) = 1 \), \( F(2) = 1 \), and \( F(n) = F(n-1) + F(n-2) \) for \( n > 2 \). **Input:** - A single integer \( n \) (1 ≤ \( n...
To compute the $ n $-th Fibonacci number efficiently using **memoization**, we can use a recursive approach with a dictionary to store already computed values. This avoids redundant calculations and significantly improves performance, especially for larger values of $ n $. Here's the Python implementation: ```python ...
algorithmic
self-instruct
{"requirement_conformance": {"score": 4, "justification": "The solution meets the basic requirement of calculating the nth Fibonacci number using memoization. However, it does not handle the case when n is less than 1, which is not specified in the question but is an important edge case."}, "logical_correctness": {"sco...
["\nassert fibonacci(1) == 1\n", "\nassert fibonacci(2) == 1\n", "\nassert fibonacci(3) == 2\n", "\nassert fibonacci(4) == 3\n", "\nassert fibonacci(5) == 5\n", "\nassert fibonacci(6) == 8\n", "\nassert fibonacci(7) == 13\n", "\nassert fibonacci(8) == 21\n", "\nassert fibonacci(9) == 34\n", "\nassert fibonacci(10) == 5...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
f4480f0cf22a893ec64202a8ea7443f2
You are tasked with implementing a function `parse_log_entry(entry)` that processes a log entry string and extracts specific components. The log entry is formatted as `"[timestamp] [log_level] message"`. Your function should return a dictionary with keys `timestamp`, `log_level`, and `message` corresponding to the extr...
Here's a Python function `parse_log_entry(entry)` that processes a log entry string according to the specified format and returns the appropriate dictionary: ```python def parse_log_entry(entry): # Split the entry into parts parts = entry.split(" [", 1) # Split only once to separate timestamp from the rest ...
generic
self-instruct
{"requirement_conformance": {"score": 4, "justification": "The function meets the basic requirements by parsing the log entry into a dictionary with the correct keys. However, it does not handle the case where the timestamp and log level are not enclosed in square brackets as specified in the question."}, "logical_corr...
["\nassert parse_log_entry(\"2023-04-01 12:34:56 [INFO] Server started successfully\") == {\"timestamp\": \"2023-04-01 12:34:56\", \"log_level\": \"INFO\", \"message\": \"Server started successfully\"}\n", "\nassert parse_log_entry(\"[2023-04-01 12:34:56] [INFO] Server started successfully\") == {}\n", "\nassert parse_...
["fail", "fail", "pass", "pass", "fail", "fail", "fail", "fail", "pass", "pass"]
0.4
a97cf0c3abad742b13e37f737696cb61
You are tasked with implementing a `Car` class in Python to simulate a car's attributes and behaviors. The class should encapsulate the following properties: `make`, `model`, `year`, and `mileage`. Your implementation should include the following methods: - `drive(distance: int)`: This method should increase the car's...
Here's the implementation of the `Car` class in Python that meets all the requirements: ```python class Car: def __init__(self, make, model, year, mileage): self.make = make self.model = model self.year = year self.mileage = mileage def drive(self, distance): """Increas...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The class Car fully meets all the specified requirements by including the attributes make, model, year, and mileage, and the methods drive, update_year, and display_info."}, "logical_correctness": {"score": 5, "justification": "The logic of the class is complet...
["\nassert Car(\"Toyota\", \"Corolla\", 2020, 15000).make == \"Toyota\"\n", "\nassert Car(\"Toyota\", \"Corolla\", 2020, 15000).model == \"Corolla\"\n", "\nassert Car(\"Toyota\", \"Corolla\", 2020, 15000).year == 2020\n", "\nassert Car(\"Toyota\", \"Corolla\", 2020, 15000).mileage == 15000\n", "\ncar = Car(\"Honda\", \...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
08fe2029a1043378709beee20b45f7b3
You are given a list of integers. Your task is to determine the length of the longest increasing subsequence within this list. An increasing subsequence is defined as a sequence where each element is strictly greater than the preceding one. For example, in the list `[10, 9, 2, 5, 3, 7, 101, 18]`, the longest increasing...
To solve the problem of finding the **length of the longest increasing subsequence (LIS)** in a list of integers, we can use an efficient algorithm with **O(n log n)** time complexity. ### ✅ **Approach:** We maintain a list `tails`, where `tails[i]` represents the smallest possible tail value of an increasing subseque...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function correctly implements the logic to find the length of the longest increasing subsequence as specified in the question."}, "logical_correctness": {"score": 5, "justification": "The logic used in the function is completely correct and consistently str...
["\nassert longest_increasing_subsequence([10, 9, 2, 5, 3, 7, 101, 18]) == 4\n", "\nassert longest_increasing_subsequence([0, 1, 0, 3, 2, 3]) == 4\n", "\nassert longest_increasing_subsequence([7, 7, 7, 7, 7, 7, 7]) == 1\n", "\nassert longest_increasing_subsequence([1, 2, 3, 4, 5]) == 5\n", "\nassert longest_increasing_...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
f9fcb503e66d124039403bcd09fadff1
You are given a text file named `input.txt` containing a body of text. Your task is to write a Python script that reads this file, counts the occurrences of each word (ignoring case and punctuation), and writes the results to another file named `output.txt`. Each line in the output file should contain a word followed b...
Here's a Python script that reads the `input.txt` file, processes the text to count word occurrences (ignoring case and punctuation), and writes the sorted results to `output.txt`. ### ✅ Python Script: ```python import string from collections import Counter def process_text(file_path): with open(file_path, 'r') ...
algorithmic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The script fully meets all specified requirements by reading from an input file, counting word occurrences while ignoring case and punctuation, and writing the results to an output file."}, "logical_correctness": {"score": 5, "justification": "The logic is comp...
["\nassert open('output.txt').read() == \"a 2\\nhello 1\\nworld 1\\n\" after count_words('input1.txt', 'output.txt') with 'input1.txt' containing \"Hello, world! a\\na\"\n", "\nassert open('output.txt').read() == \"test 2\\nthis 1\\n\" after count_words('input2.txt', 'output.txt') with 'input2.txt' containing \"Test th...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
da38a635d02525b50785630fbb94d678
You are tasked with writing a Python program to generate the first `N` prime numbers. Implement a function to check if a number is prime and use it to generate the required list of prime numbers. Your program should output the first `N` prime numbers in ascending order. **Input:** - An integer `N` (1 ≤ N ≤ 100), repre...
Here's a Python program that generates the first `N` prime numbers. It includes a helper function to check if a number is prime and uses it to generate the list of primes. ### ✅ Python Code: ```python def is_prime(n): """Check if a number is prime.""" if n <= 1: return False if n <= 3: ret...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirement by generating a list of the first 20 prime numbers using a function to check if a number is prime."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and optimally structured. The fu...
["\nassert generate_primes(0) == []\n", "\nassert generate_primes(1) == [2]\n", "\nassert generate_primes(2) == [2, 3]\n", "\nassert generate_primes(5) == [2, 3, 5, 7, 11]\n", "\nassert generate_primes(10) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n", "\nassert generate_primes(15) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
9db0281651185ed79c41a6c5a2d82538
You are given a binary tree. Your task is to find the node whose children have the maximum greatest common divisor (GCD) among all pairs of siblings in the tree, with the additional condition that the sum of the values of the siblings must be a prime number. Return the value of such a node. If no such siblings exist, r...
To solve this problem, we need to: 1. **Traverse the binary tree** and identify **sibling pairs** (i.e., two children of the same parent). 2. For each such pair, check: - Their **sum is a prime number**. - Their **GCD**. 3. Track the **node whose children have the maximum GCD** under the above condition. 4. If n...
algorithmic
evol-instruct
{"requirement_conformance": {"score": 4, "justification": "The solution addresses the main requirements of finding the node with the maximum GCD of its siblings where the sum of the siblings is a prime number. However, it does not explicitly ensure a single pass through the binary tree, as it uses a depth-first search ...
["\nassert find_max_gcd_with_prime_siblings(TreeNode(10, TreeNode(2, TreeNode(3), TreeNode(7)), TreeNode(14, TreeNode(8), TreeNode(9)))) == 2\n", "\nassert find_max_gcd_with_prime_siblings(TreeNode(5, TreeNode(3, TreeNode(1), TreeNode(2)), TreeNode(7, TreeNode(4), TreeNode(6)))) == 1\n", "\nassert find_max_gcd_with_pri...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
173227f52279d285bba17a592c052fc5
You are given a CSV file named `data.csv` with the first row containing column headers and subsequent rows containing numerical data. Your task is to write a Python program that reads this file, calculates the average of each numerical column, and prints the results in a formatted table. If a column contains non-numeri...
Here's a Python program that reads the `data.csv` file, calculates the average for each numerical column, and prints the results in a formatted table. It also handles non-numeric and empty data appropriately. ```python import csv def calculate_column_averages(file_path): with open(file_path, 'r') as file: ...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets all specified requirements. It reads a CSV file, calculates the average of each column, and displays the results in a formatted table."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and optimall...
["\nassert read_csv('data.csv')['Column1'] == [1.0, 2.0, 3.0]\n", "\nassert read_csv('data.csv')['Column2'] == [4.0, 5.0, 6.0]\n", "\nassert calculate_averages({'Column1': [1.0, 2.0, 3.0]}) == {'Column1': 2.0}\n", "\nassert calculate_averages({'Column2': [4.0, 5.0, 6.0]}) == {'Column2': 5.0}\n", "\nassert calculate_ave...
["fail", "fail", "pass", "pass", "pass", "pass", "pass", "pass", "fail", "pass"]
0.7
e4a614802d27bac0eb0654d19aa91f25
You are given a binary file named `data.bin` containing a sequence of big-endian encoded integers. Each integer is encoded using the minimum number of bytes necessary based on the following rule: if the first byte of the integer is `0x80` or higher, then the integer is encoded using 4 bytes; otherwise, it is encoded us...
To solve this problem, we need to: 1. Read the binary file `data.bin`. 2. Process the bytes in the file according to the encoding rule: - If the first byte of an integer is `0x80` or higher, it uses **4 bytes**. - Otherwise, it uses **2 bytes**. 3. Convert the appropriate number of bytes to an integer using **bi...
generic
evol-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets all specified requirements. It correctly reads the binary file, infers the length of each integer based on the first byte, and returns a list of integers."}, "logical_correctness": {"score": 5, "justification": "The logic is completely ...
["\nassert read_big_endian_integers(\"test1.bin\") == [1, 2]\n", "\nassert read_big_endian_integers(\"test2.bin\") == [128, 255]\n", "\nassert read_big_endian_integers(\"test3.bin\") == [32767, 65535]\n", "\nassert read_big_endian_integers(\"test4.bin\") == [2147483647, 1]\n", "\nassert read_big_endian_integers(\"test5...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
a0f8a5727d450f06604ec92a5f58eb1c
You are tasked with implementing a function `fibonacci_series` that generates a Fibonacci sequence up to, but not including, a given integer `n`. The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding ones. Your function should return a list of Fibonacci numbers starting ...
Here's a Python function `fibonacci_series` that generates the Fibonacci sequence up to, but not including, a given integer `n`. It handles edge cases where `n` is 0 or 1 by returning an empty list. ### ✅ Implementation: ```python def fibonacci_series(n): if n <= 1: return [] fib_sequence = [0, 1...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets the specified requirements. It generates a Fibonacci series up to a given number `n` and returns a list containing the Fibonacci numbers from 0 up to, but not including, `n`. It also correctly returns an empty list if `n` is 0 or 1."}, ...
["\nassert fibonacci_series(0) == []\n", "\nassert fibonacci_series(1) == []\n", "\nassert fibonacci_series(2) == [0, 1]\n", "\nassert fibonacci_series(10) == [0, 1, 1, 2, 3, 5, 8]\n", "\nassert fibonacci_series(15) == [0, 1, 1, 2, 3, 5, 8, 13]\n", "\nassert fibonacci_series(21) == [0, 1, 1, 2, 3, 5, 8, 13]\n", "\nasse...
["pass", "pass", "fail", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
0.9
be107f507e0139285332a0c86a4f3749
You are tasked with implementing a function `get_constant` that retrieves the value of a specified mathematical constant. The function should accept two parameters: a string `constant_name` representing the name of the constant and a boolean `approx` indicating whether an approximate value is acceptable. The function s...
To implement the `get_constant` function as described, we can use the `sympy` library, which provides exact symbolic representations of mathematical constants like `pi`, `e`, `sqrt2`, and `sqrt3`. If an exact representation is not available, we return `None`. If an approximate value is acceptable, we return the value w...
generic
evol-instruct
{"requirement_conformance": {"score": 4, "justification": "The function meets the basic requirements by returning approximate and exact values for specified constants. However, it does not return None for non-exact values when approx is False, as it returns the sympy object instead."}, "logical_correctness": {"score": ...
["\nassert get_constant('pi', True) == 3.141592653589793\n", "\nassert get_constant('e', True) == 2.718281828459045\n", "\nassert get_constant('tau', True) == 6.283185307179586\n", "\nassert get_constant('sqrt2', True) == 1.4142135623730951\n", "\nassert get_constant('sqrt3', True) == 1.7320508075688772\n", "\nassert g...
["pass", "pass", "pass", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0.3
1ca80c0c530df2c1c7fc105ea42e6ec9
You are tasked with implementing a `Book` class that models a book with attributes for its title, author, and publication year. The class should have a constructor that initializes these attributes and a method `get_info` that returns a formatted string containing the book's details. **Input:** - The constructor will ...
Here's the implementation of the `Book` class as per your requirements: ```python class Book: def __init__(self, title, author, year): self.title = title self.author = author self.year = year def get_info(self): return f"Title: {self.title}, Author: {self.author}, Year: {self.y...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets all specified requirements by defining a class `Book` with a constructor that takes `title`, `author`, and `year` as parameters and includes a method `get_info` that returns the required string format."}, "logical_correctness": {"score"...
["\nassert Book(\"1984\", \"George Orwell\", 1949).get_info() == \"Title: 1984, Author: George Orwell, Year: 1949\"\n", "\nassert Book(\"To Kill a Mockingbird\", \"Harper Lee\", 1960).get_info() == \"Title: To Kill a Mockingbird, Author: Harper Lee, Year: 1960\"\n", "\nassert Book(\"The Great Gatsby\", \"F. Scott Fitzg...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
106fbdf4a786d12b628b1581125f556a
In a game, you are given a grid with specified width and height. The grid is divided into segments, each with its own scaling factor. Each tile in the grid is square-shaped, and its dimensions are calculated based on the grid's dimensions, a fixed ratio (106.25/500), and the segment's scaling factor. Your task is to co...
To solve this problem, we need to compute the dimensions of a single tile for each segment in the grid. Each segment has its own scaling factor, and the tile dimensions are determined based on the grid's width and height, a fixed ratio, and the segment's scaling factor. --- ### 🔍 **Understanding the Problem** - **G...
generic
evol-instruct
{"requirement_conformance": {"score": 3, "justification": "The function meets the basic requirements by calculating the tile dimensions for each segment. However, it does not specify which grid dimension (width or height) to use for the calculation, leading to potential confusion."}, "logical_correctness": {"score": 3,...
["\nassert calculate_tile_dimensions(1000, 500, [1.0]) == [(106, 213)]\n", "\nassert calculate_tile_dimensions(800, 400, [0.5]) == [(53, 106)]\n", "\nassert calculate_tile_dimensions(1200, 600, [1.5]) == [(159, 320)]\n", "\nassert calculate_tile_dimensions(500, 250, [2.0]) == [(213, 213)]\n", "\nassert calculate_tile_d...
["fail", "fail", "fail", "fail", "fail", "pass", "fail", "fail", "fail", "pass"]
0.2
45bc227e11eb6cabd2a815fb84c9fb30
You are given a list of integers. Your task is to write a function that returns a new list with the elements in reverse order. You are not allowed to use any built-in functions that directly reverse the list. **Input:** - A list of integers `input_list` (1 ≤ len(input_list) ≤ 1000). **Output:** - A list of integers ...
You can reverse a list manually by iterating through the original list and building a new list in reverse order. Here's a Python function that does this without using built-in reverse functions like `list.reverse()` or slicing (`[::-1]`): ```python def reverse_list(input_list): reversed_list = [] for i in rang...
algorithmic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirement of reversing the list without using built-in functions."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and consistently reverses the list as intended."}, "edge_case_consideration...
["\nassert reverse_list([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]\n", "\nassert reverse_list(['a', 'b', 'c']) == ['c', 'b', 'a']\n", "\nassert reverse_list([]) == []\n", "\nassert reverse_list([10]) == [10]\n", "\nassert reverse_list([True, False, True]) == [True, False, True]\n", "\nassert reverse_list([None, 1, 'two', 3.0]...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
5a7d4c418516ea9190bb42d387b529a3
You are given a non-negative integer `n`. Your task is to compute the nth Fibonacci number. The Fibonacci sequence is defined as follows: F(0) = 0, F(1) = 1, and F(n) = F(n-1) + F(n-2) for n > 1. **Input:** - The first line contains a single integer `n` (0 ≤ n ≤ 50). **Output:** - Print a single integer, the nth Fibo...
To compute the nth Fibonacci number, we can use a simple iterative approach, which is efficient and works well for the given constraint `0 ≤ n ≤ 50`. ### ✅ **Approach:** - Start with the first two Fibonacci numbers: `F(0) = 0`, `F(1) = 1`. - Use a loop to compute the next Fibonacci numbers up to `n`. - Return the nth ...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirements by calculating the nth Fibonacci number for non-negative integers and handling the base cases correctly."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and efficiently calculate...
["\nassert fibonacci(0) == 0\n", "\nassert fibonacci(1) == 1\n", "\nassert fibonacci(2) == 1\n", "\nassert fibonacci(3) == 2\n", "\nassert fibonacci(4) == 3\n", "\nassert fibonacci(5) == 5\n", "\nassert fibonacci(10) == 55\n", "\nassert fibonacci(15) == 610\n", "\nassert fibonacci(20) == 6765\n", "\nassert fibonacci(25...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
9ed1d6787703815e7d8bbe083b51e726
You are given the task of computing the factorial of a non-negative integer \( n \). Due to the limitations of recursion, your solution must use an iterative approach to efficiently calculate the factorial without causing stack overflow errors. Implement a function `factorial_iterative` that takes an integer \( n \) as...
Here's the implementation of the `factorial_iterative` function as per your requirements: ```python def factorial_iterative(n): if n < 0: raise ValueError("Factorial is not defined for negative numbers") result = 1 for i in range(1, n + 1): result *= i return result ``` ### Explan...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirement by rewriting the factorial calculation using an iterative approach, which avoids stack overflow errors for large numbers."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and optim...
["\nassert factorial_iterative(0) == 1\n", "\nassert factorial_iterative(1) == 1\n", "\nassert factorial_iterative(5) == 120\n", "\nassert factorial_iterative(10) == 3628800\n", "\nassert factorial_iterative(12) == 479001600\n", "\nassert factorial_iterative(15) == 1307674368000\n", "\nassert factorial_iterative(20) ==...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
adf829f3f7ac523351016a055842d974
You are given a nested list of integers. Your task is to write a function `flatten_list(nested_list)` that returns a single list containing all the integers from the nested list in the order they appear. The input list can contain integers and other nested lists of arbitrary depth. **Input:** - A nested list of intege...
You can solve this problem using a **recursive approach**. The idea is to iterate through each element in the input list, and if the element is a list, recursively flatten it. Otherwise, add the integer to the result. Here's the implementation of the `flatten_list` function: ```python def flatten_list(nested_list): ...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets the requirement by correctly flattening a nested list of integers into a single list."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and optimally structured. The function uses recursion to hand...
["\nassert flatten_list([[1, 2, [3]], 4, [5, 6]]) == [1, 2, 3, 4, 5, 6]\n", "\nassert flatten_list([1, [2, [3, [4, [5]]]]]) == [1, 2, 3, 4, 5]\n", "\nassert flatten_list([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]\n", "\nassert flatten_list([]) == []\n", "\nassert flatten_list([[], [], []]) == []\n", "\nassert flatten_list([[[...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
f4175b057caf0df04057f163de700745
You are tasked with implementing a simple library management system. The system should support the following operations: - **Add Book**: Add a specified number of copies of a book to the library. - **Borrow Book**: Borrow a book if it is available. If the book is not available, print an appropriate message. - **Return ...
Here's a complete implementation of the `Library` class in Python that supports all the required operations: ```python class Library: def __init__(self): self.books = {} # Dictionary to store book titles and their quantities def add_book(self, title, quantity): if quantity <= 0: p...
algorithmic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets all the specified requirements by implementing methods to add books, borrow books, return books, and display all available books."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and optimally str...
["\nassert library.books == {}\n", "\nlibrary.add_book(\"Python Programming\", 3); assert library.books == {\"Python Programming\": 3}\n", "\nlibrary.add_book(\"Data Structures\", 2); assert library.books == {\"Python Programming\": 3, \"Data Structures\": 2}\n", "\nlibrary.borrow_book(\"Python Programming\"); assert l...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
7ae127b9124c14482ee17ed80fe43487
You are given a list of monsters, each with a specific health value. In each turn, you must choose an attacking monster and a defending monster to engage in combat. The attacking monster's health must be a prime number that is one more than a multiple of 3 and also a Fibonacci number. The defending monster's health mus...
To solve this problem, we need to simulate a battle between monsters, following specific rules for selecting attackers and defenders. The goal is to **minimize the final health** of the last remaining monster. --- ### 🔍 **Step-by-step Breakdown of the Rules:** #### ✅ **Attacker Requirements:** - **Health must be a ...
algorithmic
evol-instruct
{"requirement_conformance": {"score": 2, "justification": "The solution does not fully meet the requirements. It does not consider the Fibonacci sequence for attackers and does not check if the composite number has divisors only from prime numbers congruent to 3 modulo 4."}, "logical_correctness": {"score": 3, "justifi...
["\nassert min_final_health([7, 10, 13, 15]) == 10\n", "\nassert min_final_health([4, 6, 8, 9]) == 4\n", "\nassert min_final_health([10, 15, 21, 25]) == 10\n", "\nassert min_final_health([13, 19, 25, 31]) == 25\n", "\nassert min_final_health([7, 13, 19, 25]) == 25\n", "\nassert min_final_health([4, 9, 16, 25]) == 4\n",...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
169b1a54d26f3b51db1c25801ba1fd7c
You are tasked with implementing a function `create_spiral_matrix` that constructs a `num_rows` x `num_cols` matrix filled with integers in a spiral order starting from the top-left corner and moving clockwise. The integers should be unique and sequentially increasing from 1. If the matrix cannot be completely filled d...
To solve this problem, we need to construct a matrix of size `num_rows` x `num_cols` filled with numbers in a **spiral order**, starting from the top-left corner and moving **clockwise**. The numbers should be **unique and sequentially increasing from 1**, and any **unfilled positions** should be filled with **zero**. ...
generic
evol-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets all specified requirements. It generates a spiral matrix of the given dimensions and fills it with integers in a spiral pattern starting from 1, ensuring no duplicates. If the matrix cannot be filled completely, the remaining positions ...
["\nassert create_spiral_matrix(1, 1) == [[1]]\n", "\nassert create_spiral_matrix(2, 2) == [[1, 2], [4, 3]]\n", "\nassert create_spiral_matrix(3, 3) == [[1, 2, 3], [8, 9, 4], [7, 6, 5]]\n", "\nassert create_spiral_matrix(3, 4) == [[1, 2, 3, 4], [10, 11, 12, 5], [9, 8, 7, 6]]\n", "\nassert create_spiral_matrix(4, 3) == ...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
a0cb85262fbba5856753a342a7318966
Given a string `s`, write a function to find the longest palindromic substring in `s`. A palindrome is a string that reads the same forward and backward. The function should handle edge cases such as an empty string or a string with a single character. Your solution should be efficient. **Examples:** - Input: `"babad...
To find the **longest palindromic substring** in a given string `s`, we can use an **efficient approach** with **O(n²)** time complexity and **O(1)** space complexity (using the **expand around center** technique). This is more efficient than the brute-force method. --- ### ✅ **Approach: Expand Around Center** Each ...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirements by returning the longest palindromic substring, handling edge cases like an empty string or a single character string, and efficiently finding the longest palindrome."}, "logical_correctness": {"score": 5, "justificatio...
["\nassert longest_palindromic_substring(\"babad\") == \"bab\" or longest_palindromic_substring(\"babad\") == \"aba\"\n", "\nassert longest_palindromic_substring(\"cbbd\") == \"bb\"\n", "\nassert longest_palindromic_substring(\"a\") == \"a\"\n", "\nassert longest_palindromic_substring(\"\") == \"\"\n", "\nassert longes...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
2f26755fa43b4836543d993bbd1b6b7f
You are given a string `s` consisting of lowercase English letters, digits, and special characters. Your task is to determine if the string, after removing all non-alphabetic characters, is in alphabetical order. Return `True` if it is, otherwise return `False`. **Examples:** - Input: `"abc123"` - Output: `True` - ...
To solve this problem, we need to: 1. **Filter out non-alphabetic characters** from the string. 2. **Check if the resulting string is in alphabetical order**. ### Steps: - Iterate through the string and keep only the alphabetic characters. - Then, check if the filtered string is in non-decreasing alphabetical order. ...
algorithmic
evol-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirements by removing all non-alphabetic characters and checking if the resulting string is in alphabetical order."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct. It uses a generator expr...
["\nassert isAlphabetic(\"abc\") == True\n", "\nassert isAlphabetic(\"a1b2c3\") == True\n", "\nassert isAlphabetic(\"a!b@c#\") == True\n", "\nassert isAlphabetic(\"cba\") == False\n", "\nassert isAlphabetic(\"c3b2a1\") == False\n", "\nassert isAlphabetic(\"c!b@a#\") == False\n", "\nassert isAlphabetic(\"a\") == True\n"...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
05f9eb0a9d8d7155281ad503512a5754
You are given two integers, `K` and `M`. Your task is to determine the number of ways to form each sum from 2 to 2K using exactly `M` distinct positive integers, each not exceeding `K`. Implement a recursive solution with memoization to solve this problem. **Input:** - The first line contains two integers `K` and `M` ...
To solve this problem, we need to count the number of ways to form each sum from 2 to 2K using **exactly M** **distinct positive integers**, each **not exceeding K**. ### Key Points: - We must use **exactly M** distinct integers. - Each integer must be between **1 and K**. - The sum of these M integers must be between...
algorithmic
evol-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirements by using a recursive approach with memoization to find the number of combinations for each sum from 2 to 2K using exactly M different numbers."}, "logical_correctness": {"score": 5, "justification": "The logic is comple...
["\nassert count_combinations(3, 2) == {2: 1, 3: 2, 4: 2, 5: 1, 6: 1}\n", "\nassert count_combinations(4, 2) == {2: 1, 3: 2, 4: 3, 5: 4, 6: 4, 7: 3, 8: 2, 9: 1}\n", "\nassert count_combinations(5, 2) == {2: 1, 3: 2, 4: 3, 5: 5, 6: 6, 7: 7, 8: 7, 9: 6, 10: 5, 11: 4, 12: 3, 13: 2, 14: 1}\n", "\nassert count_combinations(...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
8208132022746493a9f470ac27f8f2d5
You are given a list of integers. Your task is to write a function `sort_numbers` that sorts the list in ascending order. The function should modify the list in place and not return anything. Note that the provided code snippet contains both syntax and logical errors. Correct the code to achieve the desired functionali...
To solve this problem, we need to write a function `sort_numbers` that **sorts a list of integers in ascending order in-place**, meaning it modifies the list directly and does **not return anything**. ### ✅ Requirements: - Sort the list **in-place**. - Do **not return** anything. - The function should be named `sort_n...
algorithmic
self-instruct
{"requirement_conformance": {"score": 4, "justification": "The solution addresses the requirement to sort a list of numbers but does not handle potential errors or edge cases."}, "logical_correctness": {"score": 4, "justification": "The logic is correct for sorting the list in place, but it does not return the sorted l...
["\nassert sort_numbers([3, 1, 2]) == None\n", "\nassert sort_numbers([3, 1, 2]) == [1, 2, 3]\n", "\nassert sort_numbers([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]\n", "\nassert sort_numbers([]) == []\n", "\nassert sort_numbers([1]) == [1]\n", "\nassert sort_numbers([1, 1, 1, 1]) == [1, 1, 1, 1]\n", "\nassert sort_numbers([-1...
["pass", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0.1
4e11513f0a9ef965ed15cde680583c4b
You are tasked with implementing a `Graph` class that supports storing and retrieving user data with compression. The `Graph` class should have the following methods: - `store_user_data(user_data)`: Accepts a dictionary `user_data` and stores it internally after compressing it using a chosen compression algorithm. - `...
Here's the implementation of the `Graph` class that meets the specified requirements using the `zlib` library for compression and `pickle` for serialization: ```python import zlib import pickle class Graph: def __init__(self): self._compressed_data = None def store_user_data(self, user_data): ...
generic
evol-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets all specified requirements. It implements the `Graph` class with `store_user_data` and `retrieve_user_data` methods that compress and decompress data respectively."}, "logical_correctness": {"score": 5, "justification": "The logic is co...
["\nassert Graph().retrieve_user_data() == {}\n", "\nassert Graph().retrieve_user_data() == {}\n", "\ng = Graph(); g.store_user_data({\"name\": \"Alice\", \"age\": 30}); assert g.retrieve_user_data() == {\"name\": \"Alice\", \"age\": 30}\n", "\ng = Graph(); g.store_user_data({\"key\": \"value\"}); assert g.retrieve_use...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
5271d6c5a95c8b69c1fa11c351641e73
You are given a nested dictionary. Your task is to write a function that recursively flattens this dictionary into a single-level dictionary. The keys in the new dictionary should be concatenated using a dot (`.`) to represent the hierarchy of keys from the original dictionary. **Input:** - A nested dictionary `d`. ...
You can achieve this by writing a recursive function that traverses the dictionary and builds the flattened keys by concatenating the current key with the keys from nested dictionaries. Here's the implementation: ```python def flatten_dict(d, parent_key='', sep='.'): """ Recursively flattens a nested dictiona...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirement of recursively flattening a nested dictionary into a single-level dictionary with keys concatenated using a dot (`.`) to represent the hierarchy."}, "logical_correctness": {"score": 5, "justification": "The logic is comp...
["\nassert flatten_dict({'a': 1, 'b': {'c': 2}}) == {'a': 1, 'b.c': 2}\n", "\nassert flatten_dict({'x': {'y': {'z': 3}}}) == {'x.y.z': 3}\n", "\nassert flatten_dict({'key': 'value'}) == {'key': 'value'}\n", "\nassert flatten_dict({}) == {}\n", "\nassert flatten_dict({'a': 1, 'b': 2, 'c': {'d': 3, 'e': {'f': 4}}}) == {'...
["pass", "pass", "pass", "pass", "pass", "pass", "fail", "fail", "pass", "fail"]
0.7
c4f652fb4391578a9dcace58b1444376
You are given a list of strings. Your task is to implement a function that returns a new list containing only the unique strings from the input list, while preserving the order of their first appearance. The function should be optimized to handle large lists efficiently. **Sample Input:** ```python ["apple", "banana",...
To solve this problem efficiently, we can use a **set** to track the elements we've already seen and a **list** to preserve the order of first appearances. ### ✅ Key Points: - Use a **set** for O(1) lookups to check for duplicates. - Use a **list** to maintain the **order of first appearances**. - This approach is **O...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets the requirement by returning a list of unique strings while preserving the original order of their first appearance. It also handles large lists efficiently using a set for tracking seen strings."}, "logical_correctness": {"score": 5, "...
["\nassert unique_strings([\"apple\", \"banana\", \"apple\", \"orange\"]) == [\"apple\", \"banana\", \"orange\"]\n", "\nassert unique_strings([\"hello\", \"world\", \"hello\", \"world\"]) == [\"hello\", \"world\"]\n", "\nassert unique_strings([\"a\", \"b\", \"c\", \"a\", \"b\", \"c\"]) == [\"a\", \"b\", \"c\"]\n", "\na...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
ce602920e031f37eb41a87de0699abcc
Implement a stack using a list in Python. Your stack should support the following operations: - `is_empty()`: Returns `True` if the stack is empty, otherwise `False`. - `push(item)`: Adds an item to the top of the stack. - `pop()`: Removes and returns the top item of the stack. Raises an `IndexError` if the stack is em...
Here's a Python implementation of a stack using a list, along with the required operations and a demonstration of the specified sequence of operations: ```python class Stack: def __init__(self): self.items = [] def is_empty(self): return len(self.items) == 0 def push(self, item): ...
algorithmic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets all specified requirements by implementing the Stack class with push, pop, peek, and is_empty methods, and demonstrates their usage."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and optimally ...
["\nassert Stack().is_empty() == True\n", "\nassert Stack().peek() == None\n", "\nassert Stack().pop() == None\n", "\ns = Stack(); s.push(5); assert s.peek() == 5\n", "\ns = Stack(); s.push(5); s.push(10); assert s.pop() == 10\n", "\ns = Stack(); s.push(5); s.push(10); s.pop(); assert s.is_empty() == False\n", "\ns = S...
["pass", "fail", "fail", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
0.8
02f20332c4356c08c0772176670d8b43
You are given two dates, `birth_date` and `current_date`, represented as instances of Python's `datetime.date` class. Your task is to implement a function `calculate_age` that computes the age of a person born on `birth_date` as of `current_date`. The age should be calculated in years, rounded down to the nearest whole...
To solve this problem, we need to: 1. **Calculate the age in years** as of `current_date`, **rounded down** (i.e., floor division). 2. **Determine the number of days** since the most recent birthday (i.e., the days between the last birthday and `current_date`). Here's how you can implement the `calculate_age` functio...
generic
evol-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets all specified requirements. It calculates the age in years and the number of days past the most recent birthday, returning them as a tuple."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and con...
["\nassert calculate_age(date(1990, 1, 1), date(2022, 1, 1)) == (32, 0)\n", "\nassert calculate_age(date(1990, 1, 1), date(2022, 1, 2)) == (32, 1)\n", "\nassert calculate_age(date(1990, 12, 31), date(2023, 1, 1)) == (32, 1)\n", "\nassert calculate_age(date(1990, 12, 31), date(1991, 1, 1)) == (0, 1)\n", "\nassert calcul...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
27baf12f69ac98550b47342fb2a6edc5
You are tasked with implementing a `Deck` class that simulates a standard deck of 52 playing cards. The class should support the following operations: - `shuffle()`: Randomly shuffles the deck of cards. - `deal()`: Deals a single card from the deck and returns it. If the deck is empty, return `None`. Your implementat...
Here's a complete implementation of the `Deck` class that fulfills the requirements: ```python import random class Deck: def __init__(self): # Create a standard deck of 52 playing cards suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10',...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The class Deck meets all the specified requirements. It includes the shuffle() method to shuffle the deck and the deal() method to deal a single card, returning None if the deck is empty."}, "logical_correctness": {"score": 5, "justification": "The logic is com...
["\nassert len(Deck().cards) == 52\n", "\nassert Deck().deal() == 'Ace of Spades'\n", "\ndeck = Deck()\ndeck.shuffle()\nassert len(deck.cards) == 52\n", "\ndeck = Deck()\ndeck.shuffle()\nfirst_card = deck.deal()\nassert first_card in ['2 of Hearts', '3 of Hearts', '4 of Hearts', '5 of Hearts', '6 of Hearts', '7 of Hear...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
81e1c1bc4c228277339fab339096c4fb
You are tasked with implementing a `Book` class and a `Library` class in Python. The `Book` class should store information about a book, including its title, author, and ISBN. The `Library` class should manage a collection of books and provide methods to add, remove, and list books. Your implementation should be tested...
Here's a complete implementation of the `Book` and `Library` classes in Python, along with the required functionality and sample test cases. --- ### ✅ **Implementation** ```python class Book: def __init__(self, title, author, isbn): self.title = title self.author = author self.isbn = isbn...
algorithmic
self-instruct
{"requirement_conformance": {"score": 4, "justification": "The solution meets the basic requirements by implementing a Book class and a Library class with methods to add, remove, and list books. However, it does not include additional features or functionalities that might be expected in a more comprehensive library sy...
["\nassert my_library.list_books() == [Book(title='1984', author='George Orwell', isbn='1234567890'), Book(title='To Kill a Mockingbird', author='Harper Lee', isbn='0123456789')]\n", "\nassert my_library.list_books() != [Book(title='1984', author='George Orwell', isbn='1234567890')]\n", "\nassert my_library.list_books(...
["fail", "pass", "fail", "pass", "fail", "pass", "pass", "fail", "pass", "fail"]
0.5
f8a0c400b0601e63424aa42104fd525a
You are given a string `s` consisting of alphanumeric characters, spaces, and punctuation. Your task is to determine if the string is a palindrome, ignoring spaces, punctuation, and capitalization. A string is considered a palindrome if it reads the same forwards and backwards. **Input:** - A single string `s` (1 ≤ |s...
To determine if a string is a **palindrome**, we need to: 1. **Normalize** the string: - Remove all **non-alphanumeric characters** (e.g., punctuation, spaces). - Convert all characters to **lowercase** (to ignore capitalization). 2. **Check if the normalized string reads the same forwards and backwards**. Her...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets all the specified requirements by ignoring spaces, punctuation, and capitalization, and correctly determining if the string is a palindrome."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and op...
["\nassert is_palindrome(\"A man, a plan, a canal, Panama\") == True\n", "\nassert is_palindrome(\"racecar\") == True\n", "\nassert is_palindrome(\"No lemon, no melon\") == True\n", "\nassert is_palindrome(\"Was it a car or a cat I saw?\") == True\n", "\nassert is_palindrome(\"Not a palindrome\") == False\n", "\nassert...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
9a307feb4ba6c3c6889793b242fb43b6
You are given an HTML document as a string. Your task is to write a Python function that parses the HTML and extracts all unique email addresses present in the document. The function should return a list of these unique email addresses. The HTML document may contain email addresses in plain text or within `mailto:` lin...
To extract all **unique email addresses** from an HTML document, we need to: 1. Parse the HTML document. 2. Search for email addresses in: - **Plain text** (e.g., `contact@example.com`) - **`mailto:` links** in anchor tags (e.g., `<a href='mailto:info@example.com'>...`) We can use the `BeautifulSoup` library fr...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirements by parsing an HTML document and extracting all unique email addresses from it, including those found in text and href attributes of anchor tags."}, "logical_correctness": {"score": 5, "justification": "The logic is comp...
["\nassert extract_unique_emails(\"<html><body><p>Email: test@example.com</p></body></html>\") == [\"test@example.com\"]\n", "\nassert extract_unique_emails(\"<html><body><a href='mailto:info@sample.org'>Contact us</a></body></html>\") == [\"info@sample.org\"]\n", "\nassert extract_unique_emails(\"<html><body><p>Reach ...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
1f06f5a301c49a32a1dc83c1357aafde
You are given a list of integers. Your task is to find the longest increasing subsequence in this list. An increasing subsequence is defined as a sequence where each element is greater than the previous one. The subsequence does not need to be contiguous. If there are multiple subsequences of the same maximum length, r...
To solve the problem of finding the **longest increasing subsequence (LIS)** in a list of integers, we can use **Dynamic Programming** with **O(n²)** time complexity. However, for large inputs (like up to 1000 elements), we can also use a more efficient **O(n log n)** approach using **binary search** and a list to keep...
algorithmic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution correctly implements the logic to find the longest increasing subsequence and meets all the specified requirements."}, "logical_correctness": {"score": 4, "justification": "The logic is correct and the solution works as intended. However, the use o...
["\nassert longest_increasing_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80]) == [10, 22, 33, 50, 60, 80]\n", "\nassert longest_increasing_subsequence([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]\n", "\nassert longest_increasing_subsequence([5, 4, 3, 2, 1]) == [5]\n", "\nassert longest_increasing_subsequence([1, 3, 5, 4, 7]) =...
["pass", "pass", "pass", "pass", "fail", "pass", "pass", "pass", "pass", "pass"]
0.9
f199bfb5c1efeeb6741f6e9065455b4a
You are given an integer `n` in decimal form. Your task is to write a program that outputs the same integer `n` without using any built-in conversion functions or libraries. **Input:** - A single integer `n` (0 ≤ n ≤ 10^9). **Output:** - Print the integer `n` as it is. **Sample Input:** ``` 123 ``` **Sample Output...
Since the task is to **output the same integer `n` as it is**, and the input is already in decimal form, **you don't need to do anything** — just print the input directly. Here's a simple Python program that does exactly that: ```python n = int(input()) print(n) ``` ### Explanation: - `input()` reads the input as a ...
algorithmic
evol-instruct
{"requirement_conformance": {"score": 3, "justification": "The solution meets the basic requirement of taking an integer input and outputting it. However, it does not perform any conversion as the task specifies, which is a key part of the requirement."}, "logical_correctness": {"score": 3, "justification": "The logic ...
["\nassert decimal_to_decimal(0) == 0\n", "\nassert decimal_to_decimal(123) == 123\n", "\nassert decimal_to_decimal(-456) == -456\n", "\nassert decimal_to_decimal(1000) == 1000\n", "\nassert decimal_to_decimal(-1) == -1\n", "\nassert decimal_to_decimal(9999) == 9999\n", "\nassert decimal_to_decimal(10) == 10\n", "\nass...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
b89862353edb8d21f7f08d7f841af77d
You are given a list of angles in degrees. Your task is to write a function `calculate_sine_sum` that computes the sum of the sine values of these angles after converting them to radians. The function should handle any potential errors gracefully, such as non-numeric inputs or math domain errors. **Input:** - A list ...
Here's a Python function `calculate_sine_sum` that computes the sum of the sine values of a list of angles (in degrees) after converting them to radians. It handles potential errors such as non-numeric inputs and math domain errors gracefully. ### ✅ Function Implementation: ```python import math def calculate_sine_s...
generic
evol-instruct
{"requirement_conformance": {"score": 4, "justification": "The function meets the basic requirements by calculating the sum of sine values after converting degrees to radians. However, it does not fully meet the original instruction as it does not specify the conversion from degrees to radians in the question."}, "logi...
["\nassert calculate_sine_sum([0, 30, 45, 60, 90, 180, 360]) == 2.0\n", "\nassert calculate_sine_sum([0, 90, 180, 270, 360]) == 1.0\n", "\nassert calculate_sine_sum([45, 135, 225, 315]) == 0.0\n", "\nassert calculate_sine_sum([60, 120, 240, 300]) == 0.0\n", "\nassert calculate_sine_sum([180, 360, 540, 720]) == 0.0\n", ...
["fail", "fail", "fail", "fail", "fail", "pass", "pass", "pass", "fail", "fail"]
0.3
4fece3a2ba04c4ba02353ccfbb20f746
You are given a task to write a Python function that processes a JSON file and extracts all unique keys from the JSON data. Your function should handle various error scenarios, such as the file not existing or the file containing invalid JSON. Your function should return a list of unique keys found in the JSON file. *...
Here's a Python function that processes a JSON file, extracts all **unique keys** (including keys from nested objects and arrays), and handles common error scenarios like file not found or invalid JSON: ```python import json import os def extract_unique_keys(json_file_path): """ Extracts all unique keys from ...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets the requirements by reading a JSON file, extracting unique keys, and handling errors such as invalid JSON files or missing files."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and optimally str...
["\nassert get_unique_json_keys(\"non_existent_file.json\") == []\n", "\nassert get_unique_json_keys(\"invalid_json_file.json\") == []\n", "\nassert get_unique_json_keys(\"empty_file.json\") == []\n", "\nassert get_unique_json_keys(\"single_key.json\") == [\"name\"]\n", "\nassert get_unique_json_keys(\"nested_keys.json...
["pass", "pass", "pass", "fail", "fail", "fail", "fail", "fail", "fail", "pass"]
0.4
368f8d8b9cc574e9d1c463bbd45ba961
You are tasked with implementing a `BankAccount` class that simulates basic banking operations. The class should support the following functionalities: - Initialize the account with an optional initial balance. - Deposit a specified amount into the account, ensuring the deposit amount is positive. - Withdraw a specifie...
Here's a complete implementation of the `BankAccount` class that fulfills all the specified requirements: ```python class BankAccount: def __init__(self, initial_balance=0): if initial_balance < 0: raise ValueError("Initial balance cannot be negative.") self._balance = initial_balance ...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets all specified requirements. It includes a private attribute _balance, a read-only property balance, and methods deposit and withdraw that ensure the balance never goes negative."}, "logical_correctness": {"score": 5, "justification": "T...
["\nassert BankAccount().balance == 0\n", "\nassert BankAccount(100).balance == 100\n", "\naccount = BankAccount(100); account.deposit(50); assert account.balance == 150\n", "\naccount = BankAccount(100); account.withdraw(50); assert account.balance == 50\n", "\naccount = BankAccount(100); try: account.deposit(-50); as...
["pass", "pass", "pass", "pass", "fail", "fail", "fail", "pass", "pass", "pass"]
0.7
5c57f9c78d8a10476b2ccf7048160446
Design a simple REST API using Flask. The API should expose an endpoint `/api/data` that, when accessed, returns a JSON object. The JSON object must contain the following key-value pairs: - `id`: 1 - `name`: "Sample Data" - `description`: "This is a sample data object for testing." **Sample Input:** Accessing the endp...
Here's a simple REST API using **Flask** that exposes the endpoint `/api/data` as described. --- ### ✅ Step-by-step Instructions: 1. **Install Flask** (if not already installed): ```bash pip install flask ``` 2. **Create a Python file**, for example: `app.py` 3. **Write the Flask application** as shown be...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the specified requirements by creating a REST API with Flask that exposes the /api/data endpoint and returns the correct JSON object."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and the code ...
["\nassert get_data().json == {\"id\": 1, \"name\": \"Sample Data\", \"description\": \"This is a sample data object for testing.\"}\n", "\nassert get_data().status_code == 200\n", "\nassert get_data().content_type == 'application/json'\n", "\nassert get_data().json['id'] == 1\n", "\nassert get_data().json['name'] == \...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
c9b416a2d6cb7cf8c722a8839b8fcb76
You are tasked with implementing a `Rectangle` class in Python. The class should be initialized with a width and height. It must provide methods to compute the area, perimeter, and diagonal length of the rectangle. Additionally, it should include a method to scale the rectangle by a given factor, adjusting the width an...
Here's a complete implementation of the `Rectangle` class in Python that satisfies all the requirements: ```python import math class Rectangle: def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height def perimeter...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets all specified requirements by implementing the initializer, area, perimeter, diagonal, and scale methods as described in the question."}, "logical_correctness": {"score": 5, "justification": "The logic implemented in the methods is comp...
["\nassert Rectangle(3, 4).area() == 12\n", "\nassert Rectangle(5, 5).perimeter() == 20\n", "\nassert Rectangle(3, 4).diagonal() == 5.0\n", "\nassert Rectangle(1, 1).area() == 1\n", "\nassert Rectangle(0, 0).perimeter() == 0\n", "\nassert Rectangle(6, 8).diagonal() == 10.0\n", "\nrect = Rectangle(2, 3); rect.scale(3); ...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
487b98f8f0537501173ed1f6aeb00593
You are tasked with implementing a simple banking system in Python. The system should support the following operations: 1. **Create Account**: Create a new bank account for a customer. Each account should have a unique account number, customer name, and initial balance. The initial balance must be non-negative. 2. **D...
Here's a Python implementation of the simple banking system as per your requirements: ```python class BankAccount: def __init__(self, account_number, customer_name, initial_balance): self.account_number = account_number self.customer_name = customer_name self.balance = initial_balance ...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets all specified requirements, including creating bank accounts, depositing and withdrawing funds, displaying account information, and handling errors for invalid operations. It also provides a simple command-line interface for interacting...
["\nassert BankAccount(\"Alice\", 100).balance == 100\n", "\nassert BankAccount(\"Bob\", 0).balance == 0\n", "\nassert BankAccount(\"Charlie\", 50).account_number == 1001\n", "\naccount = BankAccount(\"David\", 200); account.deposit(50); assert account.balance == 250\n", "\naccount = BankAccount(\"Eve\", 300); account....
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
4920271a8514e3d7ba1dba23f24f69fe
You are given a string `s` consisting of characters `(`, `)`, `[`, `]`, `{`, and `}`. Your task is to determine if the string is valid. A string is considered valid if: - Every opening bracket has a corresponding closing bracket of the same type. - Opening brackets are closed in the correct order. For example, the str...
To determine if a string of brackets is valid, we can use a **stack** data structure. The idea is to push opening brackets onto the stack and pop them when we encounter a closing bracket, checking if it matches the most recent opening bracket. Here's the implementation of the `is_valid` function: ```python def is_val...
generic
self-instruct
{"requirement_conformance": {"score": 4, "justification": "The solution addresses the main requirements of checking if the brackets are closed by the same type and in the correct order. However, it incorrectly returns False for any non-bracket characters, which is not specified in the requirements."}, "logical_correctn...
["\nassert is_valid(\"([{}])\") == True\n", "\nassert is_valid(\"([])\") == True\n", "\nassert is_valid(\"{[()]}\") == True\n", "\nassert is_valid(\"([)]\") == False\n", "\nassert is_valid(\"((])\") == False\n", "\nassert is_valid(\"()[]{}\") == True\n", "\nassert is_valid(\"\") == True\n", "\nassert is_valid(\"([}\") ...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
e4da1dd91738ed7df85f13f2b0877170
You are given a list of integers. Your task is to find the longest subsequence in which the absolute difference between any two consecutive elements is exactly 1. If there are multiple subsequences of the same maximum length, return any one of them. **Input:** - A list of integers `nums` (1 ≤ len(nums) ≤ 10^3), where ...
To solve this problem, we need to find the **longest subsequence** in which the **absolute difference between any two consecutive elements is exactly 1**. ### Key Points: - A **subsequence** does not require elements to be contiguous. - We are looking for the **longest such subsequence**. - If multiple such subsequenc...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function correctly implements the logic to find the longest subsequence where the difference between consecutive elements is exactly 1 and handles the case of multiple subsequences with the same maximum length by returning any one of them."}, "logical_corre...
["\nassert longest_subsequence_with_diff_1([1, 2, 3]) == [1, 2, 3]\n", "\nassert longest_subsequence_with_diff_1([1, 3, 5, 4, 3, 2, 1]) in [[5, 4, 3, 2, 1], [1, 2, 3]]\n", "\nassert longest_subsequence_with_diff_1([1, 4, 3, 2, 3, 4, 5]) in [[2, 3, 4, 5], [3, 4, 5]]\n", "\nassert longest_subsequence_with_diff_1([1, 1, 1...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
fa3596d237bac3257d100e1ba6542fc7
You are tasked with implementing a `Book` class in Python to manage a library's inventory. The class should support the following functionalities: - Initialize a book with its title, author, ISBN, published year, and the number of available copies. - Check if the book is available for borrowing. - Borrow a book if ava...
Here's a complete implementation of the `Book` class in Python that fulfills the requirements you've specified: ```python class Book: def __init__(self, title, author, isbn, published_year, available_copies): self.title = title self.author = author self.isbn = isbn self.published_ye...
generic
self-instruct
{"requirement_conformance": {"score": 4, "justification": "The class Book meets the basic requirements by defining the necessary attributes and methods. However, it does not specify the types of the attributes or include any docstrings for the methods or class."}, "logical_correctness": {"score": 4, "justification": "T...
["\nassert Book(\"1984\", \"George Orwell\", \"1234567890\", 1949, 3).title == \"1984\"\n", "\nassert Book(\"1984\", \"George Orwell\", \"1234567890\", 1949, 3).author == \"George Orwell\"\n", "\nassert Book(\"1984\", \"George Orwell\", \"1234567890\", 1949, 3).isbn == \"1234567890\"\n", "\nassert Book(\"1984\", \"Geor...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
18eaeed48742afbe9cf80b17c2442871
You are given two non-decreasing singly linked lists `l1` and `l2`. Your task is to merge these two lists into one sorted linked list. The new list should be constructed by splicing together the nodes of the first two lists in sorted order. Return the head of the merged linked list. **Input:** - Two non-decreasing sin...
To solve the problem of merging two **non-decreasing** singly linked lists into one sorted linked list, we can use a **two-pointer approach**. This is similar to the **merge step** in the **merge sort** algorithm. ### ✅ Steps: 1. Initialize two pointers, `p1` and `p2`, to the heads of `l1` and `l2`, respectively. 2. C...
algorithmic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirement of merging two sorted linked lists into a single sorted linked list by splicing together the nodes."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and optimally structured. It ef...
["\nassert mergeTwoLists(ListNode(1, ListNode(2, ListNode(4))), ListNode(1, ListNode(3, ListNode(4)))) == ListNode(1, ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(4))))))\n", "\nassert mergeTwoLists(ListNode(1, ListNode(3, ListNode(5))), ListNode(2, ListNode(4, ListNode(6)))) == ListNode(1, ListNode(2, List...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "pass", "fail", "fail"]
0.1
938fb01469396ee10a4dc1eeb88a2e13
You are given an array of integers `arr` and an integer `pivot_index`. Rearrange the elements in the array such that all elements less than the pivot value are moved to the left of the pivot position, and all elements greater than the pivot value are moved to the right of the pivot position. The pivot value itself shou...
To solve this problem, we need to rearrange the array such that: - All elements **less than** the pivot value are moved to the **left** of the pivot. - All elements **greater than** the pivot value are moved to the **right** of the pivot. - The **pivot value** (i.e., `arr[pivot_index]`) is placed in its **final sorted...
generic
evol-instruct
{"requirement_conformance": {"score": 3, "justification": "The solution attempts to rearrange the elements based on the pivot value but does not maintain the relative order of equal elements. It also incorrectly shifts elements smaller than the pivot to the beginning, which is not required."}, "logical_correctness": {"...
["\nassert three_way_partition([4, 5, 3, 2, 4, 8, 9, 4], 3) == [2, 3, 4, 4, 4, 8, 9, 5]\n", "\nassert three_way_partition([1, 2, 3, 4, 5], 2) == [1, 2, 3, 4, 5]\n", "\nassert three_way_partition([5, 4, 3, 2, 1], 2) == [2, 1, 3, 4, 5]\n", "\nassert three_way_partition([1, 1, 1, 1, 1], 2) == [1, 1, 1, 1, 1]\n", "\nassert...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
939ed97b821abd2b2ed86b975f041cb0
You are tasked with writing a Python program that computes the factorial of a non-negative integer using recursion. Your program should handle invalid inputs gracefully by raising a `ValueError` with an appropriate message if a negative integer is provided. **Input:** - A single integer `n` (0 ≤ n ≤ 20). **Output:**...
Here's a Python program that computes the factorial of a non-negative integer using recursion. It also handles invalid inputs (negative integers) by raising a `ValueError` with an appropriate message. ```python def factorial(n): if n < 0: raise ValueError("Factorial is not defined for negative numbers.") ...
algorithmic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirements by providing a recursive function to calculate the factorial and includes error handling for negative inputs."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct, with a proper base ...
["\nassert factorial(0) == 1\n", "\nassert factorial(1) == 1\n", "\nassert factorial(5) == 120\n", "\nassert factorial(7) == 5040\n", "\nassert factorial(10) == 3628800\n", "\nassert factorial(3) == 6\n", "\nassert factorial(15) == 1307674368000\n", "\ntry: factorial(-1); assert False except ValueError: assert True\n",...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
65ebf80ded38e6808f24a78bb84f43b1
You are given a string `s`. Your task is to implement a function `count_vowels` that returns the number of vowels (a, e, i, o, u) present in the string. The function should be case-insensitive. **Input:** - A single string `s` (1 ≤ |s| ≤ 10^5), consisting of alphabetic characters. **Output:** - An integer representi...
Here's a Python function `count_vowels` that counts the number of vowels in a given string `s`, and it's case-insensitive: ```python def count_vowels(s): vowels = set("aeiou") return sum(1 for char in s.lower() if char in vowels) ``` ### Explanation: - `s.lower()` converts the string to lowercase to make the ...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets the requirement by counting vowels in a case-insensitive manner."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and efficiently counts the vowels in the input string."}, "edge_case_consideration...
["\nassert count_vowels(\"hello\") == 2\n", "\nassert count_vowels(\"HELLO\") == 2\n", "\nassert count_vowels(\"Python Programming\") == 4\n", "\nassert count_vowels(\"AEIOU\") == 5\n", "\nassert count_vowels(\"bcdfg\") == 0\n", "\nassert count_vowels(\"\") == 0\n", "\nassert count_vowels(\"abcdefghijklmnopqrstuvwxyz\"...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
5c3f7436f4504d98a010e77bc114fc7b
You are given a list of strings. Your task is to write a function that sorts the list first by the length of the strings in ascending order, and then alphabetically for strings of the same length. **Input:** - A list of strings, `strings`, where each string consists of lowercase English letters. **Output:** - A list...
You can achieve the desired sorting by using Python's built-in `sorted()` function with a custom key. Here's the function that sorts the list of strings first by length (ascending) and then alphabetically: ```python def sort_strings(strings): return sorted(strings, key=lambda x: (len(x), x)) ``` ### Explanation: ...
algorithmic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets the requirement by sorting the list of strings first by their length and then by alphabetical order if the lengths are the same."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and optimally stru...
["\nassert sort_strings_by_length_and_alphabet([\"banana\", \"apple\", \"cherry\", \"date\", \"fig\", \"grape\"]) == [\"fig\", \"date\", \"apple\", \"grape\", \"banana\", \"cherry\"]\n", "\nassert sort_strings_by_length_and_alphabet([\"a\", \"bb\", \"ccc\", \"dddd\"]) == [\"a\", \"bb\", \"ccc\", \"dddd\"]\n", "\nassert...
["pass", "pass", "pass", "pass", "pass", "fail", "fail", "pass", "pass", "pass"]
0.8
1d8ef06967c8e03d59ec4e52533d84e8
You are given a list of dictionaries. Your task is to write a Python function that constructs a new list of dictionaries. Each dictionary in the new list should contain only the keys that are present in all dictionaries from the input list. The values associated with these keys in the new list should be the values from...
To solve this problem, we need to find the **intersection of keys** across all dictionaries in the input list. Then, for each dictionary in the input list, we construct a new dictionary that only includes those keys that are common to **all** dictionaries. ### Steps: 1. Find the common keys across all dictionaries. 2....
generic
self-instruct
{"requirement_conformance": {"score": 4, "justification": "The function meets the basic requirements by returning a new list of dictionaries with only the keys present in all dictionaries. However, it does not handle the case where the input list contains only one dictionary, which should return the same dictionary."},...
["\nassert common_keys_dicts([{\"a\": 1, \"b\": 2}, {\"a\": 3, \"b\": 4}, {\"a\": 5, \"b\": 6}]) == [{\"a\": 1, \"b\": 2}, {\"a\": 3, \"b\": 4}, {\"a\": 5, \"b\": 6}]\n", "\nassert common_keys_dicts([{\"a\": 1, \"b\": 2}, {\"a\": 3, \"c\": 4}, {\"a\": 5, \"d\": 6}]) == [{\"a\": 1}, {\"a\": 3}, {\"a\": 5}]\n", "\nassert...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
1e5d10e1fb114c83e86456f27833e5ba
You are given a list of temperatures in Fahrenheit. Your task is to write a Python function `convert_to_celsius` that converts each temperature to Celsius and returns a new list with the converted values. The function should handle edge cases where the input list is empty or contains invalid data types (non-numeric val...
Here's a Python function `convert_to_celsius` that meets your requirements: ```python def convert_to_celsius(temps): if not isinstance(temps, list): raise ValueError("Input must be a list.") celsius_temps = [] for temp in temps: if not isinstance(temp, (int, float)): raise ...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets the requirements by converting a list of temperatures from Fahrenheit to Celsius and handling edge cases where the input list is empty or contains invalid data types."}, "logical_correctness": {"score": 5, "justification": "The logic fo...
["\nassert convert_to_celsius([32, 212, 98.6]) == [0.0, 100.0, 37.0]\n", "\nassert convert_to_celsius([0, 100]) == [-17.77777777777778, 37.77777777777778]\n", "\nassert convert_to_celsius([-40, 122]) == [-40.0, 50.0]\n", "\nassert convert_to_celsius([]) == []\n", "\nassert convert_to_celsius([32.0]) == [0.0]\n", "\nass...
["pass", "pass", "pass", "pass", "pass", "pass", "fail", "fail", "fail", "fail"]
0.6
fd67b5acfb0801fedefe5bab3e29bcb7
You are given two lists, `x_values` and `y_values`, representing the x and y coordinates of a set of data points, respectively. Your task is to implement a function `calculate_polynomial_error` that takes a polynomial function `p` and these two lists as input. The function should compute and return the sum of the squar...
To solve this problem, we need to compute the **sum of squared errors** (SSE) between the actual `y_values` and the predicted `y_values` using a polynomial function `p`. Here's a clear and efficient implementation of the `calculate_polynomial_error` function: ```python def calculate_polynomial_error(p, x_values, y_va...
generic
evol-instruct
{"requirement_conformance": {"score": 4, "justification": "The function meets the basic requirements by calculating the sum of squared differences between the predicted and actual y-values. However, it does not explicitly handle the efficiency requirement for up to 100,000 data points, although the current implementati...
["\nassert calculate_polynomial_error(lambda x: x, [0, 1, 2], [0, 1, 2]) == 0.0\n", "\nassert calculate_polynomial_error(lambda x: x + 1, [0, 1, 2], [0, 1, 2]) == 3.0\n", "\nassert calculate_polynomial_error(lambda x: 2 * x + 3, [1, 2, 3], [5, 7, 9]) == 0.0\n", "\nassert calculate_polynomial_error(lambda x: x**2, [1, 2...
["pass", "pass", "pass", "pass", "pass", "pass", "fail", "pass", "pass", "fail"]
0.8
991788da824eb10eb67df18d14c86593
You are given a list of vaccine batches, each with a specific midichlorians count, and a list of infected patients, each with a specific midichlorians count. Each vaccine can only be used once and can only cure one patient. A patient is cured if the midichlorians count of the vaccine is strictly greater than the midich...
To solve this problem, we need to **maximize the total midichlorians count left in the vaccines** after curing all patients. Here's the strategy: --- ### **Key Points:** 1. **Each vaccine can be used once** and can cure **only one patient**. 2. A patient is cured if the **vaccine's midichlorians count is strictly gr...
algorithmic
evol-instruct
{"requirement_conformance": {"score": 4, "justification": "The solution addresses the main requirements of sorting the vaccine strengths and patient midichlorians counts, and then comparing them to determine if all patients can be cured. However, it does not explicitly maximize the midichlorians count left in the vacci...
["\nassert can_cure_all_patients([5, 3, 4], [1, 2, 3]) == 3\n", "\nassert can_cure_all_patients([1, 2, 3], [3, 2, 1]) == -1\n", "\nassert can_cure_all_patients([10, 20, 30], [1, 2, 3]) == 54\n", "\nassert can_cure_all_patients([100, 200, 300], [50, 150, 250]) == 150\n", "\nassert can_cure_all_patients([10, 20, 30], [10...
["fail", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "fail"]
0.8
47f952c00c6456e2945dba484c9df80d
You are given a string `s` consisting of words separated by spaces. Your task is to write a Python function that converts the string into a list of words and counts the frequency of each word. The function should return a dictionary where each key is a word and its corresponding value is the frequency of that word in t...
Here's a Python function that meets your requirements. It processes the input string without using `split()` or `Counter()`, and returns a dictionary with word frequencies. ### ✅ Function: ```python def word_frequency(s): # Initialize an empty dictionary to store word frequencies freq = {} # Initialize a...
algorithmic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets all the specified requirements. It converts a given string into a list of words and counts the frequency of each word without using built-in functions like split() or Counter()."}, "logical_correctness": {"score": 5, "justification": "T...
["\nassert word_frequency(\"hello world hello everyone\") == {'hello': 2, 'world': 1, 'everyone': 1}\n", "\nassert word_frequency(\"Python is great and python is fun\") == {'python': 2, 'is': 2, 'great': 1, 'and': 1, 'fun': 1}\n", "\nassert word_frequency(\"Test test TEST\") == {'test': 3}\n", "\nassert word_frequency(...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
f9b2f3ee63b8a6e567066b72334d42d6
You are given two integers, `numerator` and `denominator`, representing a fraction. Your task is to convert this fraction into its decimal representation as a string. If the decimal part is repeating, enclose the repeating part in parentheses. However, if the repeating part is longer than 5 digits, truncate it to the f...
To solve this problem, we need to convert a fraction (given as two integers: numerator and denominator) into its decimal representation. If the decimal is repeating, we enclose the repeating part in parentheses. However, if the repeating part is longer than 5 digits, we truncate it to the first 5 digits. ### Key Conce...
algorithmic
evol-instruct
{"requirement_conformance": {"score": 4, "justification": "The solution addresses the main requirements of converting a fraction to a string format and handling repeating decimals. However, it does not limit the length of the repeating part to 5 digits correctly; it limits the entire repeating sequence to 5 characters ...
["\nassert fraction_to_decimal(1, 3) == \"0.(3)\"\n", "\nassert fraction_to_decimal(2, 1) == \"2\"\n", "\nassert fraction_to_decimal(4, 333) == \"0.(012)\"\n", "\nassert fraction_to_decimal(1, 2) == \"0.5\"\n", "\nassert fraction_to_decimal(22, 7) == \"3.(14285)\"\n", "\nassert fraction_to_decimal(0, 5) == \"0\"\n", "\...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
901cc51ca9a56e6df800e90c09d6d9a7
You are given a positive integer `n`. Your task is to determine whether `n` is a perfect number. A perfect number is defined as a positive integer that is equal to the sum of its proper divisors, excluding the number itself. For example, 6 is a perfect number because its proper divisors are 1, 2, and 3, and 1 + 2 + 3 =...
To determine if a number `n` is a **perfect number**, we need to check if the **sum of its proper divisors** (excluding `n` itself) is equal to `n`. ### Steps: 1. **Find all proper divisors** of `n` (excluding `n` itself). 2. **Sum** those divisors. 3. If the **sum equals `n`**, then it is a perfect number. ### Effic...
algorithmic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirements by implementing a function `is_perfect` that checks if a number is a perfect number and tests it with the number 28."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct. The function...
["\nassert is_perfect(6) == True\n", "\nassert is_perfect(28) == True\n", "\nassert is_perfect(496) == True\n", "\nassert is_perfect(8128) == True\n", "\nassert is_perfect(33550336) == True\n", "\nassert is_perfect(12) == False\n", "\nassert is_perfect(1) == False\n", "\nassert is_perfect(0) == False\n", "\nassert is_p...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
983188704dad1f05a49f3cacb3155c86
You are given a sorted array of integers and a target integer. Implement a function to find the index of the target in the array using the binary search algorithm. If the target is not present in the array, return -1. **Input:** - The first line contains an integer `n` (1 ≤ n ≤ 10^5), the number of elements in the ar...
Here's a Python implementation of the **binary search** algorithm to find the index of a target in a sorted array. If the target is not found, it returns `-1`. ### ✅ Code: ```python def binary_search(arr, target): left = 0 right = len(arr) - 1 while left <= right: mid = (left + right) // 2 ...
algorithmic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirements by implementing the binary search algorithm in Python and explaining its time complexity."}, "logical_correctness": {"score": 5, "justification": "The binary search algorithm is implemented correctly with no logical err...
["\nassert binary_search([1, 3, 5, 7, 9, 11, 13, 15, 17, 19], 11) == 5\n", "\nassert binary_search([1, 3, 5, 7, 9, 11, 13, 15, 17, 19], 1) == 0\n", "\nassert binary_search([1, 3, 5, 7, 9, 11, 13, 15, 17, 19], 19) == 9\n", "\nassert binary_search([1, 3, 5, 7, 9, 11, 13, 15, 17, 19], 20) == -1\n", "\nassert binary_search...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
63e854ca4ba41ad015035a042df01841
You are given an integer `n`. Your task is to write a function `prime_factors` that returns a list of its prime factors, with each factor appearing as many times as it divides `n`. **Input:** - An integer `n` (1 ≤ n ≤ 10^6) **Output:** - A list of integers representing the prime factors of `n`, in non-decreasing orde...
Sure! Here's a Python function `prime_factors` that returns the list of prime factors of a given integer `n`, in non-decreasing order, with each factor appearing as many times as it divides `n`. ### ✅ Approach: 1. Start with the smallest prime number, which is `2`. 2. Divide `n` by `2` as long as it is divisible. 3. M...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets the requirement by returning a list of prime factors with each factor appearing as many times as it divides the input integer."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and optimally struct...
["\nassert prime_factors(84) == [2, 2, 3, 7]\n", "\nassert prime_factors(28) == [2, 2, 7]\n", "\nassert prime_factors(29) == [29]\n", "\nassert prime_factors(1) == []\n", "\nassert prime_factors(100) == [2, 2, 5, 5]\n", "\nassert prime_factors(49) == [7, 7]\n", "\nassert prime_factors(2) == [2]\n", "\nassert prime_fact...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
751656b4ae1a563d1e9674b76bfd4fb1
You are given a list of integers. Your task is to write a function that returns the second highest unique number in the list. If the list contains fewer than two unique numbers, the function should return `None`. **Input:** - A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^5), where each integer is in the range [-...
You can solve this problem efficiently by first extracting the unique numbers from the list and then finding the second highest one. Here's a Python function that does this: ```python def second_highest_unique(numbers): # Convert the list to a set to get unique numbers unique_numbers = set(numbers) # ...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets the requirements by returning the second highest number or None if there are fewer than two unique numbers."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct. The function uses a set to remove dupl...
["\nassert find_second_highest([10, 20, 20, 30, 40, 50]) == 40\n", "\nassert find_second_highest([5, 5, 5, 5, 5]) == None\n", "\nassert find_second_highest([100]) == None\n", "\nassert find_second_highest([1, 2]) == 1\n", "\nassert find_second_highest([10, 10, 20]) == 10\n", "\nassert find_second_highest([3, 1, 4, 1, 5...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
42d4c1f855f46a067c39e8c2bb2c7cff
You are tasked with implementing a `Rectangle` class in Python. The class should have the following functionalities: 1. An initializer method that takes two parameters: `width` and `height`. 2. A method `get_area` that returns the area of the rectangle. 3. A method `get_perimeter` that returns the perimeter of the rec...
Here's the implementation of the `Rectangle` class in Python that meets all the specified requirements: ```python class Rectangle: def __init__(self, width, height): self.width = width self.height = height def get_area(self): return self.width * self.height def get_perimeter(self)...
generic
self-instruct
{"requirement_conformance": {"score": 3, "justification": "The solution meets basic requirements by defining a Rectangle class with methods to calculate area and perimeter, and a string representation. However, it does not include additional features or properties that might be expected, such as setters or validation f...
["\nassert Rectangle(3, 4).get_area() == 12\n", "\nassert Rectangle(5, 5).get_area() == 25\n", "\nassert Rectangle(0, 10).get_area() == 0\n", "\nassert Rectangle(7, 3).get_perimeter() == 20\n", "\nassert Rectangle(1, 1).get_perimeter() == 4\n", "\nassert Rectangle(10, 0).get_perimeter() == 20\n", "\nassert str(Rectangl...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
f4b85c49f5f1a369628b20232279051e
You are developing a financial analysis module for a software application. Your task is to implement a function `calculate_compound_interest` that computes the total amount of money accumulated after a specified period, including interest, using the compound interest formula. The function should accept four parameters:...
Here's the implementation of the `calculate_compound_interest` function in Python, which computes the total amount using the compound interest formula: ```python def calculate_compound_interest(principal, rate, time, compounded): """ Calculate the total amount after compound interest. Parameters: prin...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function correctly implements all the specified requirements by taking in the four parameters (principal, rate, time, and compounded) and using them to calculate the total amount of money after the specified period of time using the compound interest formul...
["\nassert calculate_compound_interest(1000, 0.05, 1, 1) == 1050.0\n", "\nassert calculate_compound_interest(1500, 0.043, 6, 4) == 1938.842000777603\n", "\nassert calculate_compound_interest(2000, 0.06, 5, 12) == 2697.714735320319\n", "\nassert calculate_compound_interest(500, 0.03, 10, 2) == 674.4271247461903\n", "\na...
["pass", "fail", "fail", "fail", "fail", "fail", "fail", "pass", "pass", "pass"]
0.4
0040f96fddfef7e93ce6cc08a3ebb2f0
You are given a string `text`. Your task is to implement a function `count_words(text)` that returns a dictionary with the frequency of each unique word in the text, ignoring case and common English stop words. The function should handle punctuation and special characters appropriately. **Input:** - A single string `t...
To solve this problem, we need to implement a function `count_words(text)` that: 1. **Converts the text to lowercase** to ignore case. 2. **Removes punctuation and special characters**. 3. **Splits the text into words**. 4. **Excludes common English stop words** (e.g., "is", "a", "the", etc.). 5. **Counts the frequenc...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets all specified requirements: it is case-insensitive, ignores common English stop words, and returns a dictionary with word counts. A simple test case is also provided."}, "logical_correctness": {"score": 5, "justification": "The logic is...
["\nassert count_words(\"The quick brown fox jumps over the lazy dog.\") == {'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1}\n", "\nassert count_words(\"Python is great and Python is fun.\") == {'python': 2, 'great': 1, 'fun': 1}\n", "\nassert count_words(\"Hello world! Hello everyone.\") ...
["fail", "pass", "pass", "fail", "pass", "fail", "pass", "fail", "pass", "pass"]
0.6
7ccd5a38bfad17714ef7e40a565d579c
You are given a dataset of movie ratings represented as a 2D NumPy array, where each row corresponds to a user and each column corresponds to a movie. The value at each cell indicates the rating given by the user to the movie. Implement a function `svd_recommend_movies` that applies Singular Value Decomposition (SVD) t...
To solve this problem, we'll implement the `svd_recommend_movies` function using **Singular Value Decomposition (SVD)** to predict missing ratings. SVD is a matrix factorization technique that approximates the original matrix by decomposing it into three matrices: `U`, `Σ`, and `V^T`. ### Steps: 1. **Perform SVD** on ...
algorithmic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirements by implementing SVD on the input ratings matrix and recommending movies to a user by predicting their ratings for unseen movies."}, "logical_correctness": {"score": 4, "justification": "The logic is largely correct and ...
["\nassert svd_recommend_movies(0, np.array([[5, 3, 0, 1], [4, 0, 0, 1], [1, 1, 0, 5], [1, 0, 0, 4], [0, 1, 5, 4]])) == (2, 3.0)\n", "\nassert svd_recommend_movies(1, np.array([[5, 3, 0, 1], [4, 0, 0, 1], [1, 1, 0, 5], [1, 0, 0, 4], [0, 1, 5, 4]])) == (2, 3.0)\n", "\nassert svd_recommend_movies(2, np.array([[5, 3, 0, 1...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
766b79a9f0a6ddc649248ea79ca2b02a
You are tasked with implementing a function `calculate_discount(price, discount_rate)` for a shopping application. The function should compute the final price of a product after applying a discount. The discount rate is provided as a percentage. If the discount rate exceeds 100%, the function should return the string "...
Here's a Python implementation of the `calculate_discount(price, discount_rate)` function that adheres to the requirements and handles all the specified cases: ```python def calculate_discount(price, discount_rate): # Check if both inputs are numbers if not isinstance(price, (int, float)) or not isinstance(dis...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets all specified requirements, including handling invalid discount rates, negative discount rates, and invalid input types."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and consistently handles a...
["\nassert calculate_discount(100, 20) == 80.0\n", "\nassert calculate_discount(100, -10) == 110.0\n", "\nassert calculate_discount(100, 101) == \"Invalid discount rate\"\n", "\nassert calculate_discount(-100, 20) == \"Invalid price: Price cannot be negative.\"\n", "\nassert calculate_discount(\"100\", 20) == \"Invalid...
["fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0
94b3e95b8f0d5fc8e9b13a3fcc0de139
You are given a list of integers. Your task is to implement a function `remove_duplicates` that returns a new list containing only the unique elements from the original list, preserving the order of their first appearance. **Input:** - A list of integers `input_list` (1 ≤ len(input_list) ≤ 10^5), where each integer i...
You can implement the `remove_duplicates` function efficiently using a **set** to track seen elements and a **list** to preserve the order of first occurrences. Here's the implementation: ```python def remove_duplicates(input_list): seen = set() result = [] for num in input_list: if num not in seen...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets the requirement by removing duplicates and maintaining the original order of the first occurrence of each element."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and optimally structured. It use...
["\nassert remove_duplicates([1, 2, 3, 2, 1]) == [1, 2, 3]\n", "\nassert remove_duplicates([10, 20, 20, 10, 30]) == [10, 20, 30]\n", "\nassert remove_duplicates([5, 5, 5, 5, 5]) == [5]\n", "\nassert remove_duplicates([]) == []\n", "\nassert remove_duplicates([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]\n", "\nassert remove_dupl...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
33e3724c731081d3dca9121c285db0a5
You are given a nested list of integers with arbitrary depth. Your task is to flatten this list and then form `n`-length tuples from the resulting list. Write a function `process_nested_list` that takes a nested list and an integer `n` as input and returns a list of `n`-length tuples. **Input:** - A nested list of int...
To solve this problem, we need to: 1. **Flatten the nested list** into a single-level list. 2. **Group the elements** into `n`-length tuples. 3. **Return the list of tuples**. ### Steps: - Use recursion to flatten the nested list. - Once flattened, use a loop to create tuples of size `n`. ### Python Code: ```python...
generic
evol-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirements by handling nested lists of arbitrary depth and forming n-length tuples from the flattened list."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and optimally structured. The `fl...
["\nassert process_nested_list([1, [2, 3], 4, [5, 6]], 2) == [(1, 2), (3, 4), (5, 6)]\n", "\nassert process_nested_list([1, [2, [3, [4, 5]]]], 2) == [(1, 2), (3, 4), (5,)]\n", "\nassert process_nested_list([1, 2, 3, 4, 5, 6, 7], 3) == [(1, 2, 3), (4, 5, 6), (7,)]\n", "\nassert process_nested_list([[1, 2, [3, 4]], [5, 6...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
98289beeb6fb16983381060e84fc4100
You are given a string `s`. Your task is to implement a function `find_unique_characters` that returns a set of lowercase alphabetic characters that appear exactly once in the string, ignoring case sensitivity. **Input:** - A single string `s` (1 ≤ |s| ≤ 10^5), which may contain alphabetic characters, digits, and spe...
To solve this problem, we need to: 1. **Normalize the input string** by converting all characters to lowercase. 2. **Count the frequency** of each alphabetic character. 3. **Filter out** characters that appear exactly once. 4. **Return** the result as a set of lowercase alphabetic characters. Here's the implementatio...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The function fully meets all specified requirements: it takes a string as input, returns a set of unique characters, ignores case sensitivity, and returns only lowercase characters."}, "logical_correctness": {"score": 5, "justification": "The logic is completel...
["\nassert find_unique_characters(\"Python Programming\") == {'h', 't', 'r', 'g', 'm'}\n", "\nassert find_unique_characters(\"Hello World\") == {'h', 'e', 'w', 'r', 'd'}\n", "\nassert find_unique_characters(\"AaBbCc\") == set()\n", "\nassert find_unique_characters(\"12345\") == set()\n", "\nassert find_unique_character...
["fail", "pass", "pass", "pass", "fail", "fail", "pass", "fail", "pass", "pass"]
0.6
e64846fca45771b976cdeb5c12ea8040
You are tasked with implementing a class `Employee` that manages employee details and department transfers. The class should support the following operations: 1. **Initialization**: Create an `Employee` object with a name, ID, and department. 2. **Transfer**: Change the department of an employee. 3. **Display Informat...
Here's the implementation of the `Employee` class that meets all the specified requirements: ```python class Employee: def __init__(self, name, employee_id, department): self.name = name self.employee_id = employee_id self.department = department def transfer(self, new_department): ...
generic
self-instruct
{"requirement_conformance": {"score": 3, "justification": "The solution meets basic requirements by defining the Employee class with the specified attributes and methods. However, it does not include additional functionalities or details that might be expected, such as validation or more complex operations."}, "logical...
["\nassert Employee(\"John Doe\", 123, \"HR\").display_info() == \"Employee Name: John Doe, ID: 123, Department: HR\"\n", "\nassert Employee(\"Jane Smith\", 456, \"Engineering\").display_info() == \"Employee Name: Jane Smith, ID: 456, Department: Engineering\"\n", "\nassert Employee(\"Alice Johnson\", 789, \"Marketing\...
["pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
1
0ee1a639d459e50c1b41132fe91de0dc
Implement a Python class named `BankAccount` with the following functionalities: - **Constructor (`__init__`)**: Initialize the bank account with an optional `initial_deposit` parameter. If no initial deposit is provided, the balance should start at 0. If an initial deposit is provided, it should be added to the balan...
Here's the implementation of the `BankAccount` class in Python with the required functionalities: ```python class BankAccount: def __init__(self, initial_deposit=0): self.balance = initial_deposit def deposit(self, amount): if amount <= 0: raise ValueError("Deposit amount must be p...
algorithmic
self-instruct
{"requirement_conformance": {"score": 4, "justification": "The solution meets the basic requirements of creating a BankAccount class with deposit, withdraw, and get_balance methods. However, it does not explicitly state that the balance should be initialized to the value of initial_deposit if provided, which is a minor...
["\nassert BankAccount().get_balance() == 0\n", "\nassert BankAccount(100).get_balance() == 100\n", "\nassert BankAccount(50).deposit(50) == None and BankAccount(50).get_balance() == 100\n", "\nassert BankAccount(100).withdraw(50) == None and BankAccount(100).get_balance() == 50\n", "\nassert BankAccount(100).withdraw(...
["pass", "pass", "fail", "fail", "fail", "fail", "fail", "fail", "fail", "fail"]
0.2
51cefcbba357262acd731bd0c30cc844
You are tasked with implementing an efficient caching mechanism using a dictionary to store key-value pairs. The cache has a fixed capacity, and when it reaches its maximum size, the least recently used (LRU) item should be evicted to make space for new items. Your implementation should support two operations: `get` an...
To implement an **LRU Cache** efficiently, we can use a **dictionary** (hash map) to store the key-value pairs and an **ordered data structure** like an **ordered dictionary** or a **linked list** to maintain the **usage order** of keys. However, in Python, the standard `dict` does not support ordering, so we can use ...
generic
self-instruct
{"requirement_conformance": {"score": 5, "justification": "The solution fully meets the requirements by implementing a caching mechanism with a fixed size and LRU eviction policy using OrderedDict."}, "logical_correctness": {"score": 5, "justification": "The logic is completely correct and optimally structured. The use...
["\nassert Cache(2).get(1) == None\n", "\nassert Cache(2).get(2) == None\n", "\ncache = Cache(2)\ncache.put(1, 1)\ncache.put(2, 2)\nassert cache.get(1) == 1\n", "\ncache = Cache(2)\ncache.put(1, 1)\ncache.put(2, 2)\ncache.put(3, 3)\nassert cache.get(2) == None\n", "\ncache = Cache(2)\ncache.put(1, 1)\ncache.put(2, 2)\n...
["fail", "fail", "pass", "fail", "fail", "fail", "pass", "fail", "fail", "pass"]
0.3
3fd7a16c71ea522d033da11dd1a59d49
You are given two integers, `settings` and `constants`, each representing a set of bits. Your task is to determine if every bit that is set to 1 in `constants` is also set to 1 in `settings`. Implement a function `check_bits(settings, constants)` that returns `True` if this condition is met, and `False` otherwise. You ...
To solve this problem without using bitwise operators or converting numbers to binary strings, we can use the following logic: We need to check whether **all the bits that are set in `constants` are also set in `settings`**. This is equivalent to checking whether `(settings & constants) == constants`. However, since ...
generic
evol-instruct
{"requirement_conformance": {"score": 5, "justification": "The function correctly implements the logic to check if all bits set to 1 in `constants` are also set to 1 in `settings` without using bitwise operators or converting numbers to binary strings."}, "logical_correctness": {"score": 5, "justification": "The logic ...
["\nassert check_bits(13, 9) == False\n", "\nassert check_bits(15, 9) == True\n", "\nassert check_bits(0, 0) == True\n", "\nassert check_bits(1, 1) == True\n", "\nassert check_bits(2, 1) == False\n", "\nassert check_bits(3, 3) == True\n", "\nassert check_bits(8, 8) == True\n", "\nassert check_bits(8, 12) == False\n", "...
["fail", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass", "pass"]
0.9