id stringlengths 32 32 | input stringlengths 181 3.45k | output stringlengths 70 36.6k | 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 a Python implementation of a **custom sorting algorithm** using **Selection Sort**, as requested. The function is named `custom_sort` and returns the sorted list in ascending order.
```python
def custom_sort(arr):
# Traverse through all array elements
for i in range(len(arr)):
# Find the minimum... | 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** that **maximizes the total profit minus the total cost**.
### Key Observations:
- **Profit of a node** is added when you visit the node.
- **Cost of an edge** is subtracted when you use the edge.
- We want to **maximize (sum of profits) - (sum of ... | 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 the tree structure as described. It uses a **Depth-First Search (DFS)** approach to traverse the tree and prints each node with the appropriate indentation:
```python
def print_tree(tree, root, indent=0):
# Print the current node
print(' ' * indent + root)
# If th... | 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 on a **logarithmic spiral**, we need to:
---
### 🌌 **Logarithmic Spiral Overview**
The spiral is defined by the polar equation:
$$
r = a \cdot e^{b \cdot \theta}
$$
Where:
- `r` is the distance from the origin.
- `θ` is the angle in radians.
- `a` and `b` are constants to be... | 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 fulfills the requirements:
### ✅ **Function Description:**
- **Input:** A string `s` (can contain any characters).
- **Output:** A dictionary with the counts of vowels and consonants.
- **Vowels:** `'a', 'e', 'i', 'o', 'u'` (case-insensitive).
- **Consonants:** All other alphabetic charac... | 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** in a **hypergraph** using a given centrality function `func`, we need to **project the hypergraph** into a **standard graph** (where each edge is a pair of nodes), and then apply the centrality function to the resulting graph.
---
### ✅ **Steps to Solve the Problem:**
1. **Read Input:... | 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... | Here's a Python function `sum_of_even_elements` that fulfills the described behavior:
### **Function Explanation:**
1. **Input**: A sequence of integers (list, tuple, or range).
2. **Process**:
- Extract even numbers from the sequence.
- If the sequence is a **list or tuple** and contains **more than 5 even numb... | 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... | You can achieve this by using Python's built-in `itertools.combinations` function, which efficiently generates all possible combinations of a given length from an iterable. Here's how you can implement the `generate_combinations` function:
```python
import itertools
def generate_combinations(elements, n):
"""
... | 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:
```python
class Matrix:
def __init__(self, data):
"""
Initialize a matrix from a list of lists.
"""
if not all(len(row) == len(data[0]) for row in data):
raise Val... | 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 ... | You can implement the `rotate_numbers` function as follows, using **tuple unpacking** in Python to rotate the values **without using any additional variables** for swapping:
```python
def rotate_numbers(a, b, c):
return (c, a, b)
```
### Explanation:
- The function takes three integers `a`, `b`, and `c`.
- It ret... | 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 how you can implement the `is_palindrome` function in Python **without using regular expressions or built-in string methods** that directly remove non-alphanumeric characters:
### ✅ **Approach:**
1. **Filter valid characters** manually: iterate through the string and only keep alphanumeric characters (i.e., `'a... | 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 while excluding the specified stop words (case-insensitively), and prints the result in descending order of frequency.
### ✅ Python Code:
```python
import re
from collections import Counter
# Define the stop words
stop_words = ... | 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, based on your 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, amount):
... | 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 computing the **total overlap between all pairs of intervals**, we need to:
1. **Sort the intervals** by their `start` points.
2. **Iterate through all pairs** of intervals and calculate the overlap for each pair.
3. **Sum up all the overlaps**.
---
### Step-by-step Explanation:
#### 1. Sort... | 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 compute the **Least Common Multiple (LCM)** of two integers `N` and `M`, which represents the smallest amount that both Chef and Chefu can pay using only their respective coins.
The LCM of two numbers is related to their **Greatest Common Divisor (GCD)** by the formula:
$$
\text{LCM}... | 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 meets your requirements. It reads a JSON file, retrieves the value associated with a specified key, and handles the specified error conditions.
```python
import json
import os
def main():
# Prompt user for filename and key
filename = input("Enter the filename: ")
key = input("... | 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 ... | To implement the `extract_keywords` function, we need to:
1. **Normalize the text**: Convert all characters to lowercase to ensure case-insensitive comparison.
2. **Remove punctuation**: Filter out non-alphanumeric characters to extract only words.
3. **Tokenize the text**: Split the text into individual words.
4. **C... | 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... | Here's a Python implementation of a **Genetic Algorithm** to minimize the function `f(x1, x2, ..., xn) = x1^2 + x2^2 + ... + xn^2` where each `xi` is an integer between 1 and 10 inclusive.
We use:
- Random initialization of the population.
- Selection via tournament selection.
- Crossover via single-point crossover.
-... | 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:
1. **Iterate over each tuple** in the list `T`.
2. **Remove the first word** from each tuple.
3. **Find the next word in `W`** in a circular manner (i.e., wrap around to the start if needed) that is **not already in the tuple**.
4. **Append that new word** to the tuple.
5. **Store th... | 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 a 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:
- The function iterates over each key in `di... | 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 count the number of **non-intersecting diagonal triangulations** of a convex polygon with `N` sides.
### Key Concept:
The number of ways to triangulate a convex polygon with `N` sides (i.e., drawing non-intersecting diagonals to divide it into `N-2` triangles) is given by the **(N-2)t... | 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... | Here's a Python implementation of the `extract_emails` function using **regular expressions** to identify and extract all valid email addresses from a given text. The regex is designed to handle:
- Local parts with letters, digits, dots, underscores, and hyphens.
- Domains with subdomains and multiple levels (e.g., `m... | 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. Here's a step-by-step breakdown of the process:
---
### **Encryption Summary (Modified Vigenère Cipher):**
1. For each character in the key:
- Calculate the ASCII value of the character.
- Apply a random offset (between -5 and 5).
- Use the o... | 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 for a To-Do List** using **Flask** in Python. This API supports all the required operations:
---
### ✅ **Features Implemented**
- GET `/tasks`: Retrieve all tasks.
- POST `/tasks`: Create a new task.
- GET `/tasks/<task_id>`: Retrieve a specific task.
- PUT `/tasks/... | 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 as described in your problem:
### ✅ Features:
- Handles empty list (raises `ValueError`)
- Handles single-element list
- Handles both **odd** and **even** length lists correctly
- Efficient for large lists (up to 100,000 elements)
---
### ✅ ... | 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 solve this problem using **recursion** or **itertools**, but since you're asking for a function that generates all combinations, I'll provide a clean and efficient implementation using **itertools**.
### ✅ Solution using `itertools`
```python
import itertools
def generate_combinations(items):
combination... | 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 computing its SHA-1 hash and comparing it to a provided hash. The program handles case sensitivity and special characters in filenames and works across different operating systems (Windows, macOS, Linux).
### ✅ Features:
- Accepts a filename and expected... | 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 meets your requirements. It uses **NLTK** for tokenization, part-of-speech tagging, and filtering out stopwords and punctuation. The function then returns the top `n` most frequent keywords based on the specified parts of speech: **nouns**, **adjectives**, **verbs**, and... | 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... | Certainly! You can refactor the function `filter_even_numbers` to use a **list comprehension** for a more concise and Pythonic implementation.
### ✅ **List Comprehension Version**
```python
def filter_even_numbers(numbers):
return [num for num in numbers if num % 2 == 0]
```
### 🔍 **Explanation:**
- The list co... | 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... | Here's a Python function that computes the $ n $-th Fibonacci number using **memoization**. Memoization is used to store previously computed Fibonacci numbers to avoid redundant calculations and improve performance.
### ✅ Python Code:
```python
def fibonacci(n, memo={}):
if n in memo:
return memo[n]
if... | 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 the implementation of the `parse_log_entry(entry)` function in Python. It uses string splitting and validation to extract the `timestamp`, `log_level`, and `message` from a log entry string in the format `"[timestamp] [log_level] message"`:
```python
def parse_log_entry(entry):
parts = entry.strip().split('... | 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 according to your specifications:
```python
class Car:
def __init__(self, make: str, model: str, year: int, mileage: int):
self.make = make
self.model = model
self.year = year
self.mileage = mileage
def drive(self, distance... | 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... | We can solve the problem of finding the **length of the longest increasing subsequence (LIS)** using **dynamic programming** with a time complexity of **O(n log n)**, which is efficient for the given input size (up to 2500 elements).
### Approach:
We maintain a list `sub` where each element represents the smallest pos... | 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 performs the task as described:
### ✅ Features:
- Reads from `input.txt`
- Ignores **case** (e.g., "Hello" and "hello" are treated as the same word)
- Strips **punctuation** (e.g., "Hello," becomes "hello")
- Counts word occurrences
- Writes results to `output.txt`, sorted **alphabetically*... | 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 function to check if a number is prime and uses it to build a list of the first `N` primes.
```python
def is_prime(num):
"""Check if a number is prime."""
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1... | 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.
2. For each node, check if it has **two children** (left and right).
3. For each such node, compute the **GCD** of its children's values.
4. Check if the **sum of the children's values is a prime number**.
5. Track the **maximum GCD** among all nodes that... | 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 a CSV file (`data.csv`), calculates the average of each numerical column, and prints the results in a formatted table. It handles non-numeric values by skipping them and outputs `"N/A"` for columns with no valid numeric data.
### ✅ Python Code:
```python
import csv
import os
def ca... | 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... | Here's a Python function `read_big_endian_integers` that reads the binary file `data.bin` and decodes the integers according to the specified rules:
### **Rules Recap:**
- If the first byte is **`0x80` or higher**, the integer is **4 bytes** long.
- Otherwise, it's **2 bytes** long.
- All integers are **big-endian** e... | 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 the implementation of the `fibonacci_series` function in Python that generates a Fibonacci sequence up to, but not including, a given integer `n`:
```python
def fibonacci_series(n):
if n <= 1:
return []
result = [0, 1]
while result[-1] + result[-2] < n:
result.append(result[-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 symbolic representations of mathematical constants and allows us to evaluate them numerically with high precision.
### Key Points:
- If `approx` is `True`, we evaluate the constant to 15 decimal places.
- If `approx` ... | 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 based on 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... | 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 based on:
- The total **width** and **height** of the grid.
- A **fixed ratio** of `106.25 / 500`.
- A **scaling factor** for each segment.
---
### **Step-by-step Explanation:**
1. **Determine the base tile size:**
- The f... | 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 ... | Here's a Python function that reverses a list **without using any built-in reverse functions** (like `.reverse()` or `reversed()` or slicing `[::-1]`):
```python
def reverse_list(input_list):
reversed_list = []
for i in range(len(input_list) - 1, -1, -1):
reversed_list.append(input_list[i])
return ... | 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... | Here's a Python program to compute the **nth Fibonacci number** using an **iterative approach**, which is efficient and works well for `n` up to 50:
```python
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
r... | 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 an implementation of the `factorial_iterative` function in Python that meets 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(2, n + 1):
result *= i
return result
``... | 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 **recursion**. The idea is to iterate through each element in the list, and if the element is a list, recursively flatten it. If it's an integer, simply append it to the result.
Here's the Python function to do that:
```python
def flatten_list(nested_list):
result = []
for ite... | 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 Python implementation of the `Library` class that supports the required operations. The code processes a series of commands and produces the expected output.
### ✅ Python Code
```python
class Library:
def __init__(self):
self.books = {}
def add_book(self, title, quantity):
if title i... | 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 combat process with specific constraints on which monsters can attack and defend. The goal is to **minimize the final health** of the last remaining monster.
---
### **Step-by-step Plan**
#### **1. Precompute required sets of numbers:**
- **Valid attackers**: Numbers tha... | 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... | Here's the implementation of the `create_spiral_matrix` function in Python:
```python
def create_spiral_matrix(num_rows, num_cols):
# Initialize the matrix with zeros
matrix = [[0 for _ in range(num_cols)] for _ in range(num_rows)]
# Define directions: right, down, left, up
directions = [(0, 1), (... | 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 solve the problem of finding the **longest palindromic substring** in a given string `s`, we can use an **efficient algorithm** known as **Expand Around Center**.
---
### ✅ Key Concepts:
- A **palindrome** is a string that reads the same forward and backward.
- For each character in the string, we can treat it as ... | 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. **Extract only alphabetic characters** from the string (i.e., ignore digits and special characters).
2. **Check if the resulting string is in alphabetical order**.
### Steps:
- Use a list comprehension to filter only lowercase English letters (`c.isalpha()`).
- Join the filtered ... | 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` ... | Here's a Python solution that uses **recursive backtracking with memoization** to compute the number of ways to form each sum from `2` to `2K` using **exactly `M` distinct integers**, each between `1` and `K` (inclusive).
### ✅ Key Concepts:
- We use **recursion** to explore all combinations of `M` distinct integers f... | 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, you need to write a function `sort_numbers` that **modifies a list of integers in place**, sorting it in **ascending order**. The function should **not return anything**.
You also mentioned that the provided code snippet contains **syntax and logical errors**, so I'll first show you the **correc... | 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 using `pickle` for serialization and `zlib` for compression, as required:
```python
import zlib
import pickle
class Graph:
def __init__(self):
self._compressed_data = None # Internal storage for compressed user data
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 nested dictionary and builds the flattened keys using a dot (`.`) separator. Here's a clean and efficient way to do it in Python:
```python
def flatten_dict(d, parent_key='', sep='.'):
items = {}
for k, v in d.items():
new_key = f"... | 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 efficiently return a list of **unique strings** while **preserving the order of their first appearance**, you can use a combination of a `set` for fast lookups and a `list` to maintain the order.
### ✅ Optimized Approach:
- Use a `set` to track which strings have already been seen.
- Iterate through the input list,... | 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... | Here's how you can implement the `calculate_age` function in Python using the `datetime.date` class:
### Key Steps:
1. Calculate the person's age in years by subtracting the birth year from the current year, adjusting for whether the birthday has already occurred this year.
2. Calculate the most recent birthday by che... | 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 in Python, using the `random` module to support the `shuffle()` and `deal()` operations as described:
```python
import random
class Deck:
def __init__(self):
# Define the ranks and suits
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J'... | 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 Python implementation of the `Book` and `Library` classes based on your requirements. This includes the ability to add, remove, and list books, along with a test using the sample input and output you provided.
---
### ✅ **Implementation:**
```python
class Book:
def __init__(self, title, author,... | 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** while **ignoring spaces, punctuation, and capitalization**, we can follow these steps:
### Steps:
1. **Normalize the string**:
- Convert all characters to **lowercase**.
- Remove all **non-alphanumeric characters** (i.e., keep only letters and digits).
2. **Check if t... | 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... | You can achieve this by using Python's `re` (regular expressions) module to find email addresses in the HTML string, and the `BeautifulSoup` library from `bs4` to extract text and links from the HTML.
Here's a Python function that does this:
### ✅ **Requirements:**
Make sure you have `beautifulsoup4` installed:
```ba... | 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**. Here's a step-by-step breakdown of the approach:
---
### ✅ **Approach:**
1. **Dynamic Programming Table (`dp`)**:
- `dp[i]` stores the length of the LIS ending at index `i`.
-... | 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... | Sure! The task is to **read an integer from input and print it back**, but **without using any built-in conversion functions** like `int()`, `str()`, or any libraries.
However, the **input is already provided as a string**, and the **output is expected as a string**, so the challenge is **more about simulating the beh... | 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 does the following:
- Converts each angle in the input list from **degrees to radians**.
- Computes the **sine** of each angle using the `math` module.
- **Sums** the sine values.
- Handles **non-numeric inputs** and **math domain errors** gracefully.
### ✅ Function ... | 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 meets your requirements. It reads a JSON file from the given path, extracts all **unique keys**, and handles common errors such as:
- File not found
- Invalid JSON content
---
### ✅ **Function Features:**
- Uses recursion to extract keys from nested dictionaries and lists.
- Ensures ke... | 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 Python implementation of the `BankAccount` class based on your 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
def deposit(self... | 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 **Flask** application that sets up a **REST API** with the required endpoint `/api/data`. This endpoint will return a JSON object as specified when accessed via a `GET` request.
---
### ✅ Requirements
Make sure you have **Flask** installed. You can install it using pip:
```bash
pip install flask
```... | 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 and well-documented implementation of the `Rectangle` class in Python, fulfilling all the requirements:
```python
import math
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
"""Returns the area of the rectan... | 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 based on your requirements:
```python
class BankAccount:
def __init__(self, account_number, customer_name, balance):
self.account_number = account_number
self.customer_name = customer_name
self.balance = balance
def deposit(se... | 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... | You can solve this problem using a **stack** data structure. The idea is to push opening brackets onto the stack and pop them when a corresponding closing bracket is encountered. If the popped bracket doesn't match the closing bracket, the string is invalid.
Here's the Python function `is_valid` that implements this l... | 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 can use **Dynamic Programming** to find the longest subsequence where the absolute difference between any two consecutive elements is exactly 1.
### Key Idea:
We maintain a `dp` dictionary where `dp[x]` represents the length of the longest subsequence ending with the value `x`.
We also maint... | 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 satisfies the requirements and matches the sample input/output:
```python
class Book:
def __init__(self, title, author, isbn, published_year, available_copies):
self.title = title
self.author = author
self.isbn = isbn
... | 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 merge two **non-decreasing** (i.e., sorted in ascending order) singly linked lists into one sorted linked list by **splicing nodes**, we can use the **two-pointer technique**.
---
### 🔧 **Approach:**
1. Create a **dummy node** to serve as the starting point of the merged list.
2. Use a **current pointer** to bui... | 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** come **before** the pivot.
- All elements **greater than the pivot value** come **after** the pivot.
- The **relative order** of elements **equal to the pivot** is preserved.
- The **pivot value** is place... | 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 numbers) by raising a `ValueError` with a descriptive 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, case-insensitively:
```python
def count_vowels(s):
vowels = {'a', 'e', 'i', 'o', 'u'}
return sum(1 for char in s.lower() if char in vowels)
```
### Explanation:
- `s.lower()` converts the string to lowercase to make th... | 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 behavior in Python by using the built-in `sorted()` function with a custom sort key. The key will be a tuple where the first element is the length of the string and the second is the string itself. This ensures that the list is sorted first by length and then alphabetically for strin... | 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:
1. **Find the intersection of keys** that are common to all dictionaries in the input list.
2. **Construct a new list of dictionaries**, where each dictionary only includes the keys that are common to all input dictionaries.
Here's the Python function that does this:
```python
def ... | 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:
### ✅ **Requirements Recap:**
- Converts a list of Fahrenheit temperatures to Celsius.
- Handles empty lists and invalid data types.
- Raises `ValueError` if the input is not a list or contains non-numeric values.
---
### ✅ **Formula:**
$$
°... | 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... | Here's an efficient implementation of the `calculate_polynomial_error` function in Python, with **O(n)** time complexity, suitable for handling up to 100,000 data points:
```python
def calculate_polynomial_error(p, x_values, y_values):
"""
Computes the sum of squared differences between predicted y-values
... | 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 **match vaccines to patients** such that:
1. **Each vaccine is used only once**.
2. **A vaccine can only cure a patient if its midichlorians count is strictly greater** than the patient's.
3. **We want to maximize the total midichlorians count of the unused vaccines**.
4. **If we cann... | 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:
- Splits the input string into words **without using `split()`**.
- Counts the frequency of each word **without using `Counter()`**.
- Returns a dictionary of word frequencies.
### ✅ Key Points:
- It handles word separation by iterating through the string and... | 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... | Here's a Python solution that converts a fraction into its decimal representation as a string, handling both **terminating** and **repeating decimals**, and truncating the repeating part if it's longer than 5 digits:
```python
def fraction_to_decimal(numerator: int, denominator: int) -> str:
if denominator == 0:
... | 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 =... | Here's a Python solution to determine whether a given number `n` is a **perfect number**:
### ✅ Explanation:
- A **perfect number** is a positive integer that is equal to the **sum of its proper divisors**, excluding itself.
- Proper divisors of a number `n` are all positive integers less than `n` that divide `n` even... | 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:
```python
def binary_search(arr, target):
left = 0
right = len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
el... | 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... | Here's a Python function `prime_factors` that returns the list of prime factors of a given integer `n`, with each factor appearing as many times as it divides `n`:
```python
def prime_factors(n):
factors = []
divisor = 2
while n > 1:
while n % divisor == 0:
factors.append(divisor)
... | 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 [-... | Here's a Python function that solves the problem efficiently:
### ✅ **Approach:**
1. Use a set to get **unique numbers**.
2. Convert the set to a sorted list in **descending order**.
3. If there are fewer than two unique numbers, return `None`.
4. Otherwise, return the **second element** (i.e., the second highest).
#... | 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 with the required functionalities:
```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:
```python
def calculate_compound_interest(principal, rate, time, compounded):
"""
Calculates the total amount after compound interest.
Parameters:
- principal (float): Initial investment amount.
- rate (float): Annu... | 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'll implement the `count_words(text)` function that:
1. **Normalizes the text**: Convert everything to lowercase.
2. **Removes punctuation and special characters**: We'll remove non-alphanumeric characters from the text.
3. **Splits the text into words**.
4. **Filters out common English stop w... | 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... | Here's the implementation of the `svd_recommend_movies` function using **Singular Value Decomposition (SVD)** from `scikit-learn` to predict unrated movie ratings and recommend the best one.
---
### ✅ Key Steps:
1. **Apply SVD** to the ratings matrix to reduce dimensionality and capture latent features.
2. **Predict ... | 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 the implementation of the `calculate_discount` function in Python that meets all the requirements:
```python
def calculate_discount(price, discount_rate):
# Check if both inputs are numeric
if not (isinstance(price, (int, float)) and isinstance(discount_rate, (int, float))):
return "Invalid inpu... | 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... | Here's a Python function `remove_duplicates` that efficiently removes duplicates from a list while preserving the order of the **first occurrence** of each element:
### ✅ **Approach:**
- Use a `set` to track seen elements for O(1) average lookup time.
- Iterate through the list and append elements to the result list o... | 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 perform two main steps:
1. **Flatten the nested list** of integers into a single-level list.
2. **Group the flattened list** into `n`-length tuples.
Here's how you can do it step by step:
### Step 1: Flatten the Nested List
We can use a recursive function to flatten the list. If an ... | 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. **Ignore case**: Convert the entire string to lowercase.
2. **Count occurrences** of each alphabetic character.
3. **Filter** characters that appear **exactly once**.
4. **Return** the result as a **set** of lowercase characters.
Here's how you can implement the function `find_un... | 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 in Python based on your 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 all the required functionalities:
```python
class BankAccount:
def __init__(self, initial_deposit=0):
if initial_deposit < 0:
raise ValueError("Initial deposit cannot be negative.")
self.balance = initial_deposit
d... | 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 solve this problem efficiently, we need to implement an **LRU (Least Recently Used) Cache**. The key requirements are:
- Support `get` and `put` operations.
- Maintain a fixed capacity.
- Evict the least recently used item when the cache is full.
- Mark accessed/inserted items as recently used.
### Efficient Appro... | 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 **simulate the bitwise AND operation using arithmetic and logical operations**.
### Objective:
We want to check whether **every bit that is set to 1 in `constants` is also set to 1 in `settings`**. In other words, we ... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.