instruction stringlengths 201 5.6k | input stringclasses 1
value | output stringlengths 85 7.07k | source stringclasses 1
value | domain stringclasses 2
values | generation_algorithm stringclasses 2
values | test_score stringclasses 1
value | llm_score float64 1 5 |
|---|---|---|---|---|---|---|---|
You are tasked with implementing a function to analyze a chemical compound represented by a class `ChemicalCompound`. Each compound consists of a list of atoms, where each atom is described by a dictionary containing the following keys: `{'id': int, 'element': str, 'charge': int, 'isotope': str}`.
Your goal is to writ... | ```python
class ChemicalCompound:
def __init__(self, atoms):
self.atoms = atoms
def get_atom_ids_by_element_and_isotope(compound, element, isotope):
"""
Returns a list of atom ids from the given compound that match the specified element and isotope.
:param compound: ChemicalCompound object con... | opencodeinstruct | generic | evol-instruct | 1 | 4.333 | |
You are tasked with implementing a function to compute the n-th Fibonacci number efficiently. 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. Your solution should utilize dynamic programming to handle large values of n efficiently.
**Input:**
- An integer `n` (0 ... | ```python
def fibonacci(n):
"""
Calculate the n-th Fibonacci number using dynamic programming.
:param n: An integer representing the position in the Fibonacci sequence.
:return: The n-th Fibonacci number.
"""
if n <= 0:
return 0
elif n == 1:
return 1
fib = [0] *... | opencodeinstruct | algorithmic | self-instruct | 1 | 5 | |
You are tasked with implementing a Python class named `Employee` to manage employee data. The class should support the following functionalities:
- **Attributes:**
- `first_name`: A string representing the employee's first name.
- `last_name`: A string representing the employee's last name.
- `position`: A strin... | ```python
class Employee:
def __init__(self, first_name, last_name, position, salary):
"""
Initializes the Employee object with the given attributes.
:param first_name: str, the first name of the employee
:param last_name: str, the last name of the employee
:param position: ... | opencodeinstruct | generic | self-instruct | 1 | 4 | |
You are tasked with implementing a Python generator function named `prime_numbers(n)` that yields the first `n` prime numbers. Your function should efficiently determine the primality of numbers and yield them in ascending order.
**Input:**
- An integer `n` (1 ≤ n ≤ 100), representing the number of prime numbers to yi... | ```python
def prime_numbers(n):
"""
Generator function to yield the first n prime numbers.
Parameters:
n (int): The number of prime numbers to yield.
Yields:
int: The next prime number in the sequence.
"""
def is_prime(num):
if num <= 1:
return False
if num ... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are given a list of integers, `numbers`. Implement a function `sort_numbers` that sorts this list using the QuickSort algorithm. The list may contain duplicate numbers, and you must ensure that the relative order of duplicate numbers is preserved. Additionally, all even numbers must appear before any odd numbers in... | ```python
def sort_numbers(numbers):
"""
Sorts a list of integers using the QuickSort algorithm with a twist:
all even numbers must appear before any odd numbers, and the relative
order of duplicate numbers must be preserved.
:param numbers: List of integers to be sorted.
:return: Sorted list o... | opencodeinstruct | generic | evol-instruct | 1 | 2.667 | |
You are tasked with implementing a function that generates the Fibonacci sequence up to the nth number. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. Your function should return a list containing the Fibonacci sequence up to the nth ... | ```python
def generate_fibonacci(n):
"""
Generate a list containing the Fibonacci sequence up to the nth number.
Parameters:
n (int): The number of terms in the Fibonacci sequence to generate.
Returns:
list: A list of integers representing the Fibonacci sequence up to the nth term.
"""
... | opencodeinstruct | algorithmic | self-instruct | 1 | 4.667 | |
You are given a function `is_capital_city` that accepts two string parameters: `city` and `country`. Your task is to determine whether the provided `city` is the capital of the specified `country`. The function should return `True` if the `city` is the capital of the `country`, and `False` otherwise. The comparison sho... | ```python
def is_capital_city(city, country):
"""
Determines if the given city is the capital of the specified country.
Parameters:
city (str): The name of the city in uppercase.
country (str): The name of the country.
Returns:
bool: True if the city is the capital of the country, ... | opencodeinstruct | generic | evol-instruct | 1 | 4.667 | |
You are tasked with implementing a RESTful API endpoint `/time` that responds with the current server time in JSON format. The time should be represented as a string in the ISO 8601 format (e.g., "2023-04-30T12:34:56Z"). Your implementation should handle any unexpected errors gracefully by returning a JSON response wit... | ```python
from flask import Flask, jsonify
from datetime import datetime, timezone
from pytz import utc
app = Flask(__name__)
@app.route('/time', methods=['GET'])
def get_server_time():
"""
Returns the current server time in ISO 8601 format.
Returns:
A JSON response containing the current ser... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are tasked with implementing a Python class named `Employee` to manage employee details. The class should have the following attributes and methods:
- **Attributes:**
- `name`: A string representing the employee's name.
- `position`: A string representing the employee's job position.
- `salary`: A float repr... | ```python
class Employee:
def __init__(self, name, position, salary):
"""
Initializes an Employee object with the given name, position, and salary.
:param name: str, the name of the employee
:param position: str, the job position of the employee
:param salary: float, the sal... | opencodeinstruct | algorithmic | self-instruct | 1 | 3.667 | |
You are tasked with implementing a `Book` class that manages information about books. The class should support the following functionalities:
1. Initialization of a book with a title, author, and publication year.
2. Displaying the book's information in a formatted manner.
3. Updating the publication year of the book.... | ```python
class Book:
def __init__(self, title, author, publication_year):
"""
Initialize a new Book instance.
:param title: The title of the book.
:param author: The author of the book.
:param publication_year: The year the book was published.
"""
self.title... | opencodeinstruct | generic | self-instruct | 1 | 4 | |
You are given a list of integers. Your task is to implement a function `find_first_repeated_number` that identifies the first integer that appears more than once in the list. If all integers are unique, the function should return `None`.
**Input:**
- A list of integers `nums` (1 ≤ len(nums) ≤ 10^5), where each integer... | ```python
def find_first_repeated_number(nums):
"""
Finds the first repeated number in a list of integers.
Parameters:
nums (list): A list of integers.
Returns:
int or None: The first repeated integer, or None if no repetition is found.
"""
seen = set()
for num in nums:
... | opencodeinstruct | generic | self-instruct | 1 | 5 | |
You are tasked with implementing a function that generates a histogram from a given list of integers. The histogram should be printed to the console using asterisks (`*`). Each element in the list represents the height of a bar in the histogram.
**Input:**
- A list of integers, where each integer is between 1 and 100,... | ```python
def print_histogram(numbers):
"""
Prints a histogram to the console using asterisks based on the given list of numbers.
:param numbers: List of integers representing the height of each bar in the histogram.
"""
for number in numbers:
print('*' * number)
# Example usage:
numbe... | opencodeinstruct | algorithmic | self-instruct | 1 | 4 | |
You are given a list of strings. Your task is to write a function that returns a list of unique strings sorted by their frequency in descending order. If two strings have the same frequency, they should be sorted lexicographically in ascending order.
**Input:**
- A list of strings `strings` (1 ≤ len(strings) ≤ 10^4), ... | ```python
from collections import Counter
def sort_strings_by_frequency(strings):
"""
Sorts a list of strings by their frequency in descending order.
If two strings have the same frequency, they are sorted lexicographically in ascending order.
:param strings: List of strings to be sorted.
:ret... | opencodeinstruct | algorithmic | self-instruct | 1 | 3.667 | |
You are tasked with implementing a function `fibonacci_sequence` that generates the Fibonacci sequence up to a specified number of terms. The Fibonacci sequence begins with 0 and 1, with each subsequent term being the sum of the two preceding terms. Your function should return a list containing the sequence.
**Input:*... | ```python
def fibonacci_sequence(n_terms):
"""
Generate a list containing the Fibonacci sequence up to a specified number of terms.
Parameters:
n_terms (int): The number of terms in the Fibonacci sequence to generate.
Returns:
list: A list of integers representing the Fibonacci sequenc... | opencodeinstruct | generic | self-instruct | 1 | 4 | |
Implement a class `Car` with the following specifications:
- The class should have an initializer that accepts three parameters: `make`, `model`, and `year`.
- Implement a method `get_description` that returns a string formatted as `"year make model"`.
- Implement a method `start_engine` that prints a message in the fo... | ```python
class Car:
def __init__(self, make, model, year):
"""
Initializes a new instance of the Car class.
:param make: The make of the car.
:param model: The model of the car.
:param year: The year of the car.
"""
self.make = make
self.model = mode... | opencodeinstruct | generic | self-instruct | 1 | 4 | |
You are tasked with implementing a `Book` class in Python to manage book information. The class should include the following attributes: `title`, `author`, `year`, and `ISBN`. Implement a method `display_info()` that prints the book's details in the specified format. Additionally, create a function `find_books_by_autho... | ```python
class Book:
def __init__(self, title, author, year, isbn):
self.title = title
self.author = author
self.year = year
self.isbn = isbn
def display_info(self):
"""Prints the book's information in a formatted string."""
print(f"Title: {self.title}")
... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are given a dictionary `person` containing details about an individual. The dictionary includes the keys `first_name`, `last_name`, `age`, `city`, `state`, `country`, and `timestamp`. Your task is to implement a function `create_profile` that constructs a formatted string based on the provided information. The stri... | ```python
from datetime import datetime
def create_profile(person):
"""
Constructs a formatted string based on the person's details and the time of day indicated by the timestamp.
Parameters:
person (dict): A dictionary containing the person's details including first_name, last_name, age, city, st... | opencodeinstruct | generic | evol-instruct | 1 | 3.667 | |
You are given a text file and two words: a target word and a replacement word. Your task is to write a Python function that reads the file, replaces all occurrences of the target word with the replacement word, and writes the modified content back to the file. The function should take three parameters: the filename, th... | ```python
def replace_word_in_file(filename, word_to_replace, replacement_word):
"""
Replaces all occurrences of a specified word in a file with another word.
Parameters:
filename (str): The name of the file to be modified.
word_to_replace (str): The word to be replaced in the file.
replacement... | opencodeinstruct | generic | self-instruct | 1 | 3.667 | |
Given a list of integers `numbers`, your task is to implement a function `find_second_largest(numbers)` that returns the second largest distinct integer in the list. If the list contains fewer than two distinct integers, the function should return `None`.
**Input:**
- A list of integers `numbers` (1 ≤ len(numbers) ≤ 1... | ```python
def find_second_largest(numbers):
"""
Finds the second largest distinct integer in a list of integers.
Parameters:
numbers (list): A list of integers.
Returns:
int or None: The second largest distinct integer, or None if there are fewer than two distinct integers.
"""
... | opencodeinstruct | generic | self-instruct | 1 | 5 | |
You are tasked with implementing a function to validate email addresses for a web application. An email address is considered valid if it meets the following criteria:
- It contains exactly one "@" symbol.
- The domain part (after the "@") contains at least one dot ".".
- Neither the local part (before the "@") nor the... | ```python
def validate_email(email):
"""
Validates an email address based on specific rules:
- Must contain exactly one "@" symbol.
- Domain part must contain at least one dot ".".
- Neither the local part nor the domain part can start or end with a dot ".".
- Must not contain consecutive dots "... | opencodeinstruct | generic | self-instruct | 1 | 5 | |
You are tasked with implementing a function `convert_to_json` that takes a Python dictionary as input and returns a JSON string. The JSON string should be formatted with an indentation of 4 spaces, and any `None` values in the dictionary should be converted to `null` in the JSON output. Your function should handle any ... | ```python
import json
def convert_to_json(data):
"""
Convert a Python dictionary into a properly formatted JSON string with an indentation of 4 spaces.
Parameters:
data (dict): A Python dictionary to be converted to JSON.
Returns:
str: A JSON string with proper indentation and format.... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are tasked with implementing a function `validate_input` that processes an input `s`. The function should return `True` if `s` is either `None` or an empty string. Additionally, if `s` is a string that does not contain any alphanumeric characters, the function should also return `True`. For all other cases, includi... | ```python
def validate_input(s) -> bool:
"""
Validates the input string s.
Returns True if s is None, an empty string, or a string without any alphanumeric characters.
Returns False otherwise.
"""
if s is None or s == "":
return True
if not isinstance(s, str):
return Fal... | opencodeinstruct | generic | evol-instruct | 1 | 5 | |
You are given a string `text` that may contain various Unicode space characters. Your task is to write a function `remove_extra_spaces` that processes this string by removing all extra spaces, ensuring that only a single space remains between words. The function should also trim any leading or trailing spaces.
**Input... | ```python
import re
def remove_extra_spaces(text):
"""
Removes all extra spaces from the input string, maintaining a single space between words
and trimming leading and trailing spaces. Handles various Unicode space characters.
:param text: A string containing words separated by various space characte... | opencodeinstruct | generic | evol-instruct | 1 | 5 | |
You are given a sequence of one or more numbers, which may include integers, floats, and strings representing numbers. Your task is to implement a function `find_range(data)` that returns a tuple of two numbers representing the smallest and largest values in the sequence after converting all strings to their numerical ... | ```python
def find_range(data):
"""
Returns a tuple of the smallest and largest numbers in the given sequence.
Parameters:
data (sequence): A sequence of numbers, which can be integers, floats, or strings representing numbers.
Returns:
tuple: A tuple containing the smallest and largest... | opencodeinstruct | generic | evol-instruct | 1 | 3.667 | |
You are given a sorted array of integers `nums` and an integer `target`. Your task is to implement a function `find_target(nums, target)` that performs a binary search to locate the `target` value within the array. If the `target` is found, return its index; otherwise, return `-1`.
**Constraints:**
- `1 <= len(nums) <... | ```python
def find_target(nums, target):
"""
Perform binary search to find the target in a sorted array.
:param nums: List[int] - A sorted list of integers.
:param target: int - The target integer to search for.
:return: int - The index of the target if found, otherwise -1.
"""
left, ri... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are given an integer `n`. Your task is to write a function `prime_factors` that returns a list of prime factors of `n` in ascending order. The prime factors should be listed with their respective multiplicities.
**Input:**
- An integer `n` (1 ≤ n ≤ 10^6)
**Output:**
- A list of integers representing the prime fac... | ```python
def prime_factors(n):
"""
Returns a list of prime factors of the given integer n in ascending order.
Parameters:
n (int): The integer to factorize.
Returns:
list: A list of prime factors of n.
"""
factors = []
divisor = 2
while n >= 2:
while n % diviso... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are given a nested dictionary `data` and a string `path`. The `path` string consists of keys separated by periods (`.`), indicating a sequence of keys to traverse within the nested dictionary. Your task is to implement the function `get_nested_value(data, path)` that returns the value located at the specified path.... | ```python
def get_nested_value(data, path):
"""
Returns the value at the specified path in a nested dictionary.
:param data: A nested dictionary.
:param path: A string representing the path to the desired value, with keys separated by periods.
:return: The value at the specified path, or None i... | opencodeinstruct | generic | evol-instruct | 1 | 4.667 | |
You are given a list of integers. Your task is to implement a function `calculate_median` that computes the median of the list. The function should handle both even and odd-length lists and return the median as a float. The original list should not be modified.
**Input:**
- A list of integers `numbers` (1 ≤ len(number... | ```python
def calculate_median(numbers):
"""
Calculate the median of a list of numbers.
:param numbers: List of integers
:return: Median as a float
"""
sorted_numbers = sorted(numbers)
n = len(sorted_numbers)
if n % 2 == 1:
return float(sorted_numbers[n // 2])
else:... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are given a string `s` consisting of characters '(', ')', '[', ']', '{', and '}'. Your task is to determine if the string is balanced. A string is considered balanced if every opening symbol has a corresponding closing symbol in the correct order. Implement a function `is_balanced` that returns `True` if the string... | ```python
def is_balanced(s: str) -> bool:
"""
Determines if a string of parentheses, brackets, and braces is balanced.
Args:
s (str): The input string containing only '(', ')', '[', ']', '{', and '}'.
Returns:
bool: True if the string is balanced, False otherwise.
"""
matching... | opencodeinstruct | algorithmic | self-instruct | 1 | 5 | |
You are given a list of integers. Your task is to implement a function that returns a new list with the elements shuffled in a random order using the Fisher-Yates shuffle algorithm. The original list should remain unchanged.
**Input:**
- A list of integers `input_list` (1 ≤ len(input_list) ≤ 10^5), where each integer ... | ```python
import random
def shuffle_list(input_list):
"""
Returns a new list with the elements of the input list shuffled in a random order
using the Fisher-Yates shuffle algorithm.
:param input_list: List of integers to be shuffled.
:return: A new list with shuffled elements.
"""
list... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are given a task to modify a Python function to compute the magnitude of a complex number. The function should now be able to handle both real and complex numbers. The magnitude of a complex number \( a + bi \) is defined as \( \sqrt{a^2 + b^2} \). Write a function `magnitude` that takes a single argument, which ca... | ```python
def magnitude(x):
"""
Computes the magnitude of a given number, which can be either real or complex.
Parameters:
x (int, float, complex): The number whose magnitude is to be computed.
Returns:
float: The magnitude of the number.
"""
return abs(x)
``` | opencodeinstruct | algorithmic | self-instruct | 1 | 4.333 | |
You are given an integer `number`. Your task is to determine if `number` is a palindrome. A number is considered a palindrome if it reads the same backward as forward.
**Input:**
- The first line contains an integer `number` (0 ≤ number ≤ 10^9).
**Output:**
- Print `True` if `number` is a palindrome, otherwise print... | ```python
def is_palindrome(number):
"""
Determines if the given integer is a palindrome.
Args:
number (int): The integer to check.
Returns:
bool: True if the number is a palindrome, False otherwise.
"""
num_str = str(number)
return num_str == num_str[::-1]
# Examples
print(is_pal... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are tasked with implementing a function `create_user_profile` that constructs a user profile based on the provided username and age. The function should return a dictionary with keys `username`, `age`, and `birth_year`. The `birth_year` should be calculated using the current year and the provided age. If the age is... | ```python
from datetime import datetime
def create_user_profile(username, age=18):
"""
Creates a user profile dictionary with username, age, and birth_year.
Parameters:
- username (str): The username of the user.
- age (int, optional): The age of the user. Defaults to 18 if not provided.
... | opencodeinstruct | generic | evol-instruct | 1 | 4.667 | |
You are tasked with implementing a `Circle` class in Python. The class should have a constructor that accepts the radius of the circle as a parameter. Implement two methods within the class: `area` and `circumference`. The `area` method should return the area of the circle using the formula \( \pi r^2 \), and the `circ... | ```python
import math
class Circle:
def __init__(self, radius):
"""
Initializes a new Circle instance with the given radius.
:param radius: The radius of the circle.
"""
self.radius = radius
def area(self):
"""
Calculates the area of the circle.
... | opencodeinstruct | algorithmic | self-instruct | 1 | 4 | |
You are tasked with implementing a simple hash table in Python. The hash table should support the following operations:
- `put(key, value)`: Inserts a (key, value) pair into the hash table. If the key already exists, update the value.
- `get(key)`: Returns the value associated with the key. If the key does not exist, ... | ```python
class HashTable:
def __init__(self, size=10):
self.size = size
self.table = [[] for _ in range(size)]
def _hash_function(self, key):
return hash(key) % self.size
def put(self, key, value):
"""
Inserts a (key, value) pair into the hash table. If the key alr... | opencodeinstruct | generic | self-instruct | 1 | 3.667 | |
You are given a list of bounding boxes, where each bounding box is represented as a list of five integers: `[xmin, ymin, xmax, ymax, score]`. Here, `xmin` and `xmax` denote the horizontal coordinates of the left and right edges of the bounding box, respectively, while `ymin` and `ymax` denote the vertical coordinates o... | ```python
def shift_bounding_boxes(bounding_boxes, offset):
"""
Shifts bounding boxes with a score greater than 0.7 by the specified offset along the horizontal axis.
Parameters:
bounding_boxes (list of lists): A list where each element is a list of five integers representing a bounding box.
of... | opencodeinstruct | generic | evol-instruct | 1 | 4.667 | |
You are tasked with implementing a Python class `Car` that encapsulates the properties of a car: `make`, `model`, `year`, `mileage`, and `price`. Your goal is to define the `__str__` method for the `Car` class to return a formatted string representation of the car in the following format: "{make} {model} ({year}), Mile... | ```python
class Car:
def __init__(self, make, model, year, mileage, price):
"""
Initializes a new Car instance with the given attributes.
:param make: The make of the car.
:param model: The model of the car.
:param year: The year the car was manufactured.
:param mile... | opencodeinstruct | generic | self-instruct | 1 | 4.333 | |
You are participating in a coding competition and are given the task to compute the greatest common divisor (GCD) of two large integers using the Euclidean algorithm. Implement a Python function `gcd(a, b)` that takes two integers `a` and `b` as input and returns their GCD. You are not allowed to use any built-in funct... | ```python
def gcd(a, b):
"""
Computes the greatest common divisor (GCD) of two integers using the Euclidean algorithm.
Parameters:
a (int): First integer
b (int): Second integer
Returns:
int: The greatest common divisor of a and b
"""
a = abs(a)
b = abs(b)
whil... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
In a simplified version of the "battleship" game, you are playing on a hexagonal grid where each cell is identified by axial coordinates (q, r). Your objective is to determine the minimum number of shots required to sink all ships on the grid. Each ship occupies a straight line of cells in one of the six possible direc... | ```python
def shots_needed_to_sink_all_ships(ships):
"""
Calculate the total number of shots needed to sink all ships on a hexagonal grid.
:param ships: A list of tuples, where each tuple contains two integers:
the first integer is the size of the ship,
the second in... | opencodeinstruct | algorithmic | evol-instruct | 1 | 1.667 | |
You are given a list of sentences, where each sentence is represented as a list of words. Your task is to construct a trigram frequency dictionary. Each key in the dictionary should be a tuple consisting of three consecutive words from the sentences, and the corresponding value should be the frequency of that trigram. ... | ```python
from collections import defaultdict
def build_trigram_frequency(sentences):
"""
Constructs a trigram frequency dictionary from a list of sentences.
Parameters:
sentences (list of list of str): A list of sentences, where each sentence is a list of words.
Returns:
dict: A dict... | opencodeinstruct | generic | evol-instruct | 1 | 5 | |
You are given a dictionary where each key is a string and each value is a list of integers. Your task is to write a function that computes a new dictionary with the same keys, but the values are the sum of the integers in the corresponding lists.
**Input:**
- A dictionary `input_dict` where keys are strings and value... | ```python
def sum_values_in_dict(input_dict):
"""
Computes a new dictionary with the same keys as the input dictionary,
but the values are the sum of the integers in each list.
:param input_dict: dict {str: list of int}
:return: dict {str: int}
"""
return {key: sum(value_list) for key, valu... | opencodeinstruct | generic | self-instruct | 1 | 4.333 | |
You are given a string `s` consisting of words separated by single spaces. Your task is to write a function `reverse_words` that reverses the order of the words in the string. The function should return the modified string with the words in reverse order.
**Input:**
- A single string `s` (1 ≤ len(s) ≤ 1000) containing... | ```python
def reverse_words(s):
"""
Reverses the order of words in the given string.
Parameters:
s (str): A string with words separated by single spaces.
Returns:
str: A string with the words in reverse order.
"""
return ' '.join(s.split()[::-1])
# Example usage:
print(reverse_words("... | opencodeinstruct | generic | self-instruct | 1 | 4.333 | |
You are given a list of integers `nums`. Your task is to find the length of the longest increasing subsequence in the list. An increasing subsequence is defined as a sequence where each element is greater than the previous one. If the list is empty, the function should return 0.
**Input:**
- A list of integers `nums` ... | ```python
def longest_increasing_subsequence(nums):
"""
Finds the length of the longest increasing subsequence in the given list of integers.
:param nums: List of integers
:return: Length of the longest increasing subsequence
"""
if not nums:
return 0
dp = [1] * len(nums)
for ... | opencodeinstruct | generic | self-instruct | 1 | 5 | |
You are given a CSV string where the first row contains the column headers and each subsequent row contains the values for each column. Your task is to implement a function `parse_csv` that parses this CSV string and returns a list of dictionaries, where each dictionary represents a row in the CSV data. Assume that the... | ```python
def parse_csv(csv_string):
"""
Parses a CSV string and returns a list of dictionaries, where each dictionary
represents a row in the CSV data. The first row of the CSV string contains
the column headers.
:param csv_string: A string representing the CSV data.
:return: A list of diction... | opencodeinstruct | generic | self-instruct | 1 | 4.333 | |
You are given a modified series defined as follows: the series starts with two integers `a` and `b`. Each subsequent term is the sum of the two preceding terms. However, if this sum is even, it is divided by the greatest common divisor (GCD) of the last two terms before being added to the series. Your task is to write ... | ```python
from math import gcd
def sum_series_modified(n, a=0, b=1):
"""
Returns the nth term of a modified series where each even sum is divided by the GCD of the last two elements.
Parameters:
n (int): The term number to find.
a (int): The first term of the series (default is 0).
b (int)... | opencodeinstruct | generic | evol-instruct | 1 | 4.667 | |
You are given an array of integers, `arr`, where some elements may repeat. Your task is to write a function that counts the frequency of each element in the array and returns a dictionary with elements as keys and their frequencies as values.
**Input:**
- An array of integers, `arr` (1 ≤ len(arr) ≤ 10^5), where each e... | ```python
def count_frequencies(arr):
"""
Counts the frequency of each element in the given array and returns a dictionary
with elements as keys and their frequencies as values.
:param arr: List[int] - The input array of integers.
:return: Dict[int, int] - A dictionary with elements as keys and the... | opencodeinstruct | algorithmic | self-instruct | 1 | 4.667 | |
You are given a list of sentences and a target string. Your task is to implement a function `find_occurrences` that counts the number of times the target string appears in the list of sentences. The comparison should be case-sensitive.
**Input:**
- A list of strings `sentences` (1 ≤ len(sentences) ≤ 100), where each ... | ```python
def find_occurrences(sentences, target):
"""
Counts the number of times the target string appears in the list of sentences.
:param sentences: List of strings, where each string is a sentence.
:param target: String, the target word to count in the sentences.
:return: Integer, the count... | opencodeinstruct | generic | self-instruct | 1 | 3.667 | |
You are given a list of `n` integers and a positive integer `k`. Your task is to implement a function that returns a list of the `k` smallest integers from the input list. You are not allowed to use any built-in sorting functions. Instead, you must implement your own sorting algorithm to solve this problem.
**Input:**... | ```python
def k_smallest(arr, k):
"""
Returns a list of the k smallest integers from the input list using selection sort.
:param arr: List of integers
:param k: Number of smallest integers to return
:return: List of k smallest integers
"""
n = len(arr)
for i in range(min(k, n)):
... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are given a list of integers `numbers` representing the outcomes of a degenerate distribution. Your task is to implement a function `modified_expval(numbers)` that computes the expected value of this distribution. Before calculating the expected value, sort the list in ascending order and remove any duplicate value... | ```python
def modified_expval(numbers):
"""
Computes the expected value of a degenerate distribution after sorting the list
and removing duplicates. Returns 0 if the resulting list is empty.
:param numbers: List of integers representing the outcomes of a distribution.
:return: Float representin... | opencodeinstruct | generic | evol-instruct | 1 | 4.667 | |
You are given a sorted array `arr` of `n` unique integers and a target integer `target`. Your task is to implement a function that uses binary search to find the index of the `target` in the array. If the `target` is not present in the array, return `-1`. The function should be optimized to handle large arrays efficien... | ```python
def binary_search(arr, target):
"""
Perform binary search on a sorted array to find the index of the target value.
Parameters:
arr (list of int): A sorted list of unique integers.
target (int): The integer value to search for in the array.
Returns:
int: The index of the t... | opencodeinstruct | algorithmic | self-instruct | 1 | 4.667 | |
You are given a list of integers. Your task is to write an optimized function that calculates the sum of all unique elements in the list. The function should be efficient in terms of both time and space complexity.
**Sample Input:**
```
[1, 2, 2, 3, 4, 4, 5]
```
**Sample Output:**
```
15
``` | ```python
def sum_of_unique_elements(lst):
"""
Calculate the sum of all unique elements in the given list of integers.
:param lst: List of integers
:return: Sum of unique integers
"""
unique_elements = set(lst) # Convert list to set to remove duplicates
return sum(unique_elements) # Sum t... | opencodeinstruct | algorithmic | self-instruct | 1 | 4.667 | |
You are tasked with managing network configurations for multiple nodes and interfaces. Given a list of tuples, where each tuple consists of a node identifier and an interface name, your function should return a list of dictionaries. Each dictionary should represent the configuration of the corresponding interface. If a... | ```python
# Assuming node_interface_configurations stores configurations for nodes and interfaces
node_interface_configurations = {
'Node1': {
'eth0': {'ip': '192.168.1.1', 'netmask': '255.255.255.0'},
'eth1': {'ip': '192.168.2.1', 'netmask': '255.255.255.0'},
},
'Node2': {
'eth0': {... | opencodeinstruct | generic | evol-instruct | 1 | 5 | |
You are tasked with implementing a method within the `Employee` class that processes salary data. The `Employee` class has the following attributes: `name`, `position`, `salary`, and `hire_date`. The `salary` attribute is a string formatted as 'XYZ ABC', where 'XYZ' denotes the salary in thousands of dollars and 'ABC' ... | ```python
class Employee:
def __init__(self, name, position, salary, hire_date):
self.name = name
self.position = position
self.salary = salary
self.hire_date = hire_date
def get_formatted_salary(self):
"""
Returns the salary as a float representing the total sal... | opencodeinstruct | generic | self-instruct | 1 | 3.667 | |
You are given two dictionaries, `dict1` and `dict2`. Your task is to implement a function `find_common_keys(dict1, dict2)` that returns a list of keys that are present in both dictionaries. The keys in the resulting list should appear in the same order as they do in `dict1`.
**Input:**
- Two dictionaries, `dict1` and ... | ```python
def find_common_keys(dict1, dict2):
"""
Returns a list of keys that are common to both input dictionaries.
The order of keys in the output list matches their order in dict1.
:param dict1: First dictionary
:param dict2: Second dictionary
:return: List of common keys
"""
return ... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are given the root of a binary tree. Your task is to determine whether the tree is a valid binary search tree (BST). A binary tree is a valid BST if for every node, all nodes in its left subtree have values less than the node's value, and all nodes in its right subtree have values greater than the node's value. Ret... | ```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_valid_bst(root):
"""
Determines if a binary tree is a valid binary search tree (BST).
:param root: TreeNode, the root of the binary tree
... | opencodeinstruct | algorithmic | self-instruct | 1 | 4.333 | |
You are tasked with implementing a `Book` class that adheres to the following specifications:
- **Constructor**: The constructor should accept three parameters: `title` (a string), `author` (a string), and `year_published` (an integer).
- **Method `get_info`**: This method should return a string formatted as "Title: {... | ```python
class Book:
def __init__(self, title, author, year_published):
"""
Initializes a new Book instance.
:param title: The title of the book (string).
:param author: The author of the book (string).
:param year_published: The year the book was published (integer).
... | opencodeinstruct | generic | self-instruct | 1 | 4.333 | |
You are tasked with implementing a function `validate_input(user_input)` that determines whether a given string represents a valid integer. The input string may contain leading and trailing whitespace characters, which should be ignored. However, the string should not contain any spaces between digits. Your function sh... | ```python
def validate_input(user_input):
"""
Determines if the given string represents a valid integer after removing leading and trailing whitespace.
Parameters:
user_input (str): The input string to validate.
Returns:
bool: True if the input string is a valid integer, False otherwis... | opencodeinstruct | generic | evol-instruct | 1 | 3.667 | |
Implement a `SimpleCalculator` class that supports four basic arithmetic operations: addition, subtraction, multiplication, and division. The class should include methods `add`, `subtract`, `multiply`, and `divide`. Each method should accept two numerical parameters and return the result of the operation. If the divisi... | ```python
class SimpleCalculator:
def add(self, a, b):
"""Return the sum of a and b."""
return a + b
def subtract(self, a, b):
"""Return the difference of a and b."""
return a - b
def multiply(self, a, b):
"""Return the product of a and b."""
return a * b
... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are given two numbers `a` and `b` encoded in a non-standard base-3 numeral system. In this system, '0' is represented by '@', '1' is represented by '#', and '2' is represented by '$'. Your task is to convert these numbers into the base-10 numeral system and compare them. Output a message indicating whether `a` is g... | ```python
def encode_to_base10(encoded_str):
"""
Convert a string encoded in a non-standard base-3 numeral system to a base-10 integer.
Parameters:
encoded_str (str): The encoded string using '@', '#', and '$' for '0', '1', and '2' respectively.
Returns:
int: The base-10 integer repres... | opencodeinstruct | algorithmic | evol-instruct | 1 | 4.333 | |
You are given a dictionary where keys are strings and values are integers. Your task is to write a Python function that sorts this dictionary by its values in descending order and returns a list of tuples representing the sorted items.
**Input:**
- A dictionary `d` with string keys and integer values.
**Output:**
- ... | ```python
def sort_dict_by_values_desc(d):
"""
Sorts a dictionary by its values in descending order and returns a list of tuples.
Parameters:
d (dict): A dictionary with string keys and integer values.
Returns:
list: A list of tuples sorted by the dictionary's values in descending order.
"... | opencodeinstruct | generic | self-instruct | 1 | 4.333 | |
You are tasked with implementing a function `is_valid_season_number(season_number: int) -> bool` for a fictional interstellar race. A valid season number is defined as a prime number within the range of 1 to 20, inclusive. Your function should return `True` if the provided `season_number` is valid, and `False` otherwis... | ```python
def is_valid_season_number(season_number: int) -> bool:
"""
Checks if the given season number is a valid prime number between 1 and 20, inclusive.
Parameters:
season_number (int): The season number to validate.
Returns:
bool: True if the season number is valid, False otherwis... | opencodeinstruct | generic | evol-instruct | 1 | 5 | |
You are given a dictionary `products` where the keys are product names (strings) and the values are their respective prices (floats). Your task is to implement a function `generate_markdown_table` that constructs a markdown table as a string. The table must have three columns: "Product Name", "Price", and "Discounted P... | ```python
def generate_markdown_table(products):
"""
Generates a markdown table from a dictionary of products and their prices.
Parameters:
products (dict): A dictionary where keys are product names and values are prices.
Returns:
str: A string representing the markdown table with colu... | opencodeinstruct | generic | self-instruct | 1 | 4.333 | |
You are given a nested dictionary `d`. Your task is to write a recursive function `flatten_dict` that transforms this dictionary into a flattened dictionary. In the flattened dictionary, each key should represent the path to the corresponding value in the original dictionary, with path components joined by underscores ... | ```python
def flatten_dict(d, parent_key='', sep='_'):
"""
Recursively flattens a nested dictionary.
Parameters:
d (dict): The dictionary to flatten.
parent_key (str): The base key string for recursion (used internally).
sep (str): The separator to use between keys.
Returns:
dict: A fl... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are given a list of names and a target name. Your task is to write a Python function that returns the number of times the target name appears in the list, ignoring case differences. For instance, "Alice", "alice", and "ALICE" should all be considered the same name.
**Input:**
- A list of strings `names` (1 ≤ len(n... | ```python
def count_name_occurrences(names, target_name):
"""
Counts the number of occurrences of target_name in the list names, ignoring case differences.
:param names: List of names (strings) to search within.
:param target_name: The target name (string) to count occurrences of.
:return: Integer ... | opencodeinstruct | generic | self-instruct | 1 | 5 | |
You are tasked with implementing a `Book` class that encapsulates the details of a book. The class should have the following attributes:
- `title`: a non-empty string representing the book's title.
- `author`: a non-empty string representing the book's author.
- `isbn`: a non-empty string representing the book's ISBN.
... | ```python
class Book:
def __init__(self, title, author, isbn, pages):
"""
Initializes a new Book instance with the given title, author, ISBN, and number of pages.
:param title: A non-empty string representing the book's title.
:param author: A non-empty string representing t... | opencodeinstruct | generic | self-instruct | 1 | 5 | |
You are tasked with implementing a Python decorator named `log_execution_time` that measures and logs the execution time of any function it decorates. The decorator should output the function's name and the time taken to execute in seconds. Utilize the `time` module for timing purposes. Your implementation should be te... | ```python
import time
import functools
def log_execution_time(func):
"""
Decorator that logs the execution time of a function.
Args:
func (callable): The function to be decorated.
Returns:
callable: The wrapped function that logs its execution time.
"""
@functools.wrap... | opencodeinstruct | algorithmic | self-instruct | 1 | 4.333 | |
Greg has received a grid with `n` rows and `m` columns. Each cell `(i, j)` in the grid contains the integer `(i + j)^2`. Greg aims to select a subset of cells such that any two selected cells have numbers that are co-prime. Determine the maximum number of cells Greg can select.
**Input:**
- The first line contains two... | ```python
def max_coprime_cells(n, m):
"""
Determine the maximum number of cells that can be selected such that
the numbers in the selected cells are co-prime.
:param n: Number of rows in the grid
:param m: Number of columns in the grid
:return: Maximum number of co-prime cells that can be sele... | opencodeinstruct | algorithmic | evol-instruct | 1 | 2 | |
You are tasked with developing a web server using the Flask framework. Your server must handle a single route `/greet`. Upon receiving a GET request at this route, the server should respond with a JSON object containing a greeting message. The server should be configured to listen on port 5000.
**Sample Input:**
A GET... | ```python
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/greet', methods=['GET'])
def greet():
"""
Handles GET requests to the /greet route.
Returns:
A JSON response with a greeting message.
"""
return jsonify(message="Hello, welcome to the server!")
if __name__ ... | opencodeinstruct | generic | self-instruct | 1 | 4 | |
You are tasked with implementing a `Book` class in Python. The class should have the following functionalities:
1. An initializer (`__init__`) that takes three parameters: `title`, `author`, and `year`. These parameters should be stored as instance variables.
2. A string representation method (`__str__`) that returns ... | ```python
class Book:
def __init__(self, title, author, year):
"""
Initializes a new Book instance.
:param title: The title of the book.
:param author: The author of the book.
:param year: The year the book was published.
"""
self.title = title
self.a... | opencodeinstruct | generic | self-instruct | 1 | 3.333 | |
You are tasked with implementing a function to compute the nth term of the Tribonacci sequence. The Tribonacci sequence is defined as follows: the first term is 0, the second and third terms are 1, and each subsequent term is the sum of the preceding three terms. Your function should efficiently compute the nth term fo... | ```python
def tribonacci(n):
"""
Computes the nth term of the Tribonacci sequence.
Parameters:
n (int): The term of the Tribonacci sequence to compute (0 ≤ n ≤ 35).
Returns:
int: The nth term of the Tribonacci sequence.
"""
# Base cases
if n == 0:
return 0
elif ... | opencodeinstruct | algorithmic | self-instruct | 1 | 4.667 | |
You are given two lists of integers. Your task is to determine whether these two lists share at least one common element. Write a function `have_common_element` that takes two lists as input and returns `True` if there is at least one common element, and `False` otherwise.
**Sample Input:**
```python
list1 = [1, 2, 3,... | ```python
def have_common_element(list1, list2):
"""
Determines if two lists have at least one common element.
Parameters:
list1 (list): The first list of integers.
list2 (list): The second list of integers.
Returns:
bool: True if there is at least one common element, False otherwise.
... | opencodeinstruct | algorithmic | self-instruct | 1 | 5 | |
You are given a string `text`. Your task is to implement a function `analyze_text` that processes this string and returns a dictionary with the frequency of each word. The function should be case-insensitive and should ignore punctuation. Use the `re` module to handle punctuation.
**Input:**
- A single string `text` ... | ```python
import re
from collections import defaultdict
def analyze_text(text):
"""
Analyzes the input text and returns a dictionary with the frequency of each word.
Parameters:
text (str): The input string to analyze.
Returns:
dict: A dictionary with words as keys and their frequenci... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are given a positive integer `n`. Your task is to write a function `find_prime_factors(n)` that returns a list of all prime factors of `n`, with each factor appearing as many times as it divides `n`. The prime factors should be listed in ascending order.
**Input:**
- A single integer `n` (1 ≤ n ≤ 10^6)
**Output:*... | ```python
def find_prime_factors(n):
"""
Returns a list of all prime factors of the given integer n, with each factor
appearing as many times as it divides n. The prime factors are listed in ascending order.
:param n: Integer, the number to factorize
:return: List of integers, the prime factors... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are tasked with implementing a function `calculate_days_in_month(month, year)` that determines the number of days in a given month and year. The function should manually calculate leap years and return the correct number of days for February in leap years. The function should handle invalid month inputs by returnin... | ```python
def calculate_days_in_month(month, year):
"""
Calculate the number of days in a given month and year.
Parameters:
month (int): The month (1-12).
year (int): The year (1-10^4).
Returns:
int: The number of days in the specified month and year, or 0 if the month is invalid.
... | opencodeinstruct | generic | evol-instruct | 1 | 5 | |
You are given a string `s` representing a Roman numeral. Your task is to convert this Roman numeral into its corresponding integer value. The input string `s` is guaranteed to be a valid Roman numeral within the range of 1 to 3999.
**Sample Input:**
```
MCMXCIV
```
**Sample Output:**
```
1994
``` | ```python
def roman_to_integer(s: str) -> int:
"""
Convert a Roman numeral string to an integer.
:param s: A string representing a Roman numeral (1 <= len(s) <= 15)
:return: The integer value corresponding to the Roman numeral
"""
roman_to_int_map = {
'I': 1, 'V': 5, 'X': 10, 'L': 5... | opencodeinstruct | algorithmic | self-instruct | 1 | 4.667 | |
You are given a list of integers. Your task is to implement a function `find_max_index` that returns the index of the element with the maximum absolute value in the list. If the list is empty, the function should raise a `ValueError` with the message "Input list must not be empty". If there are multiple elements with t... | ```python
def find_max_index(numbers):
"""
Returns the index of the element with the maximum absolute value in the list.
Raises ValueError if the list is empty.
:param numbers: List of integers
:return: Index of the element with the maximum absolute value
"""
if not numbers:
rai... | opencodeinstruct | generic | evol-instruct | 1 | 5 | |
You are given a string `s` representing a Roman numeral. Your task is to write a function that converts this Roman numeral into its corresponding integer value. The Roman numeral string will consist of the characters 'I', 'V', 'X', 'L', 'C', 'D', and 'M', which represent the values 1, 5, 10, 50, 100, 500, and 1000, res... | ```python
def roman_to_integer(s: str) -> int:
"""
Convert a Roman numeral string to an integer.
:param s: A string representing a Roman numeral.
:return: The integer value corresponding to the Roman numeral.
"""
roman_to_int = {
'I': 1,
'V': 5,
'X': 10,
'L':... | opencodeinstruct | algorithmic | self-instruct | 1 | 4.667 | |
In a virtual world represented as a 2D grid with varying cell sizes, you need to implement a function to center a camera on a moving object. The camera has a fixed viewport size and should always be centered on the object, ensuring the object remains visible even when near the edges of the world.
The function `center_... | ```python
def center_camera(object_x, object_y, world_width, world_height, viewport_width, viewport_height, cell_widths, cell_heights):
"""
Calculate the displacement values needed to center the camera on a moving object in a virtual world with varying cell sizes.
Parameters:
object_x (int): The x-coor... | opencodeinstruct | generic | evol-instruct | 1 | 5 | |
You are given a string `a`. Your task is to determine if `a` is a palindrome. A string is considered a palindrome if it reads the same backward as forward. Your solution should be efficient and handle the maximum possible input size within the given constraints.
**Constraints:**
- The length of the string `a` is betwe... | ```python
def is_palindrome(a: str) -> bool:
"""
Determines if the given string `a` is a palindrome.
:param a: The input string to check.
:return: True if `a` is a palindrome, False otherwise.
"""
return a == a[::-1]
# Example usage:
# print(is_palindrome("racecar")) # Output: True
# prin... | opencodeinstruct | algorithmic | evol-instruct | 1 | 3.667 | |
You are given a function `f(x)` that takes an integer `x` as input and returns a boolean value. This function is used to filter a list of integers, keeping only those elements for which `f(x)` returns `True`.
Your task is to implement the function `invert_filter(f)` that takes the filter function `f` as input and retu... | ```python
def invert_filter(f):
"""
Returns a new filter function that inverts the boolean result of the given function f.
Parameters:
f (function): A function that takes an integer and returns a boolean.
Returns:
function: A new function that returns the logical negation of f(x).
... | opencodeinstruct | generic | evol-instruct | 1 | 5 | |
You are tasked with designing a RESTful API using Flask that supports CRUD operations on a collection of books. Each book must have an `id`, `title`, and `author`. Your API should include the following endpoints:
- `GET /books`: Retrieve a list of all books.
- `GET /books/<int:book_id>`: Retrieve a specific book by it... | ```python
from flask import Flask, jsonify, request, abort
app = Flask(__name__)
# Sample data (in-memory database for simplicity)
books = [
{"id": 1, "title": "To Kill a Mockingbird", "author": "Harper Lee"},
{"id": 2, "title": "1984", "author": "George Orwell"},
{"id": 3, "title": "The Great Gatsby", "a... | opencodeinstruct | algorithmic | self-instruct | 1 | 4.333 | |
In a programming competition, you are given a nested dictionary `variables` representing a hierarchical structure of variables and their values. Each key in the dictionary can map to either another dictionary or a direct value. You are also given a string `name` which represents the path to a variable in this hierarchy... | ```python
def find_variable_value(variables, name):
"""
Retrieves the value of a variable from a nested dictionary using a dot-separated path.
Parameters:
variables (dict): A nested dictionary representing the hierarchy of variables.
name (str): A string representing the path to the variable, w... | opencodeinstruct | generic | evol-instruct | 1 | 3 | |
You are given a string `s` consisting of alphanumeric characters and special characters. Your task is to determine if all characters in the string are identical, taking into account case sensitivity. The function should return `True` if all characters are the same, and `False` otherwise. An empty string should be consi... | ```python
def are_all_chars_same(s):
"""
Determines if all characters in the string are identical, considering case sensitivity.
:param s: The input string.
:return: True if all characters are the same, False otherwise.
"""
if len(s) == 0:
return True
first_char = s[0]
... | opencodeinstruct | algorithmic | evol-instruct | 1 | 5 | |
You are given a list of integers. Your task is to construct a binary search tree (BST) from the list and return the elements of the BST in in-order traversal format.
**Input:**
- A list of integers `lst` where `1 <= len(lst) <= 1000` and `-1000 <= lst[i] <= 1000`.
**Output:**
- A list of integers representing the in-... | ```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insertIntoBST(root, val):
"""
Inserts a value into the BST.
:param root: TreeNode, the root of the BST.
:param val: int, the value to be in... | opencodeinstruct | algorithmic | self-instruct | 1 | 4.333 | |
You are tasked with analyzing seismic data from a specific region. The dataset consists of records of earthquakes, each with the following attributes: 'Time' (in seconds), 'Magnitude', and 'Location'. Additionally, each earthquake has a recorded 'Depth' (in meters).
Your goal is to implement a function `getEarthquakeT... | ```python
def getEarthquakeTimesForLocation(location_id, earthquake_times, earthquake_locations, earthquake_depths, min_depth):
"""
Returns a list of earthquake times for a given location and minimum depth.
:param location_id: int, The ID of the location for which to retrieve earthquake times.
:param e... | opencodeinstruct | generic | evol-instruct | 1 | 4.333 | |
You are tasked with implementing a function named `process_data` that processes a mix of positional and keyword arguments. The function should handle both individual strings and lists of strings. For each string encountered, it should convert the string to uppercase and add it to a result list. If a list of strings is ... | ```python
from typing import List, Any
def process_data(*args, **kwargs) -> List[str]:
"""
Processes a mix of positional and keyword arguments, converting strings to uppercase.
Args:
*args: Variable length argument list, can include strings or lists of strings.
**kwargs: Arbitrary keyw... | opencodeinstruct | generic | evol-instruct | 1 | 3.333 | |
You are tasked with implementing a function `normalize_input(value)` that processes various types of input and returns a list according to the following rules:
- If the input is `None`, return an empty list.
- If the input is already a list, return the list as is.
- If the input is a dictionary, convert it into a list... | ```python
def normalize_input(value):
"""
Normalize the input value to a list according to specific rules:
- None -> []
- list -> list
- dict -> list of (key, value) tuples
- set -> sorted list
- other -> [value]
"""
if value is None:
return []
elif isinstance(value, list... | opencodeinstruct | generic | evol-instruct | 1 | 5 | |
You are given an array of integers `nums` and a positive integer `k`. Your task is to write a function `find_k_largest` that returns the `k` largest elements from the array `nums` in ascending order. The function should be optimized for performance, especially for large input sizes.
**Constraints:**
- `1 <= len(nums) ... | ```python
import heapq
def find_k_largest(nums, k):
"""
Returns the k largest elements from the list nums in ascending order.
:param nums: List[int] - The list of integers.
:param k: int - The number of largest elements to return.
:return: List[int] - The k largest elements in ascending order.
... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are given a list of integers, which may include negative numbers and zero. Your task is to implement a function `sum_even_numbers` that calculates and returns the sum of all even numbers in the list.
**Input:**
- A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^3), where each integer `num` satisfies -10^3 ≤ nu... | ```python
def sum_even_numbers(numbers):
"""
Calculate the sum of all even numbers in a given list of integers.
:param numbers: List of integers, which may include negative numbers and zero.
:return: Sum of all even numbers in the list.
"""
return sum(num for num in numbers if num % 2 == 0)
# ... | opencodeinstruct | generic | self-instruct | 1 | 3.667 | |
You are given a string `json_str` representing a JSON document. Implement a function `parse_json(json_str)` that parses the JSON string and returns the corresponding Python dictionary. If the JSON string is malformed, the function should print an error message and return `None`.
**Input:**
- A single string `json_str`... | ```python
import json
def parse_json(json_str):
"""
Parses a JSON string and returns the corresponding Python dictionary.
If the JSON string is malformed, prints an error message and returns None.
:param json_str: A string representing a JSON document.
:return: A Python dictionary if the JSON stri... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are given a string `s`. Your task is to implement a function `unique_characters(s)` that returns a new string consisting of only the unique characters from `s`, preserving the order of their first appearance.
**Input:**
- A single string `s` (1 ≤ |s| ≤ 10^5), where |s| denotes the length of the string. The string ... | ```python
def unique_characters(s):
"""
Returns a new string containing only the unique characters from the input string,
in the order they first appear.
:param s: Input string consisting of lowercase English letters and spaces.
:return: String with unique characters in the order of their first app... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are tasked with implementing a `Student` class in Python to manage student information in a school system. The class should include the following functionalities:
- **Constructor**: Initialize the student's name, age, and grades.
- **Getters and Setters**: Provide getter and setter methods for the name, age, and g... | ```python
class Student:
def __init__(self, name, age, grades):
"""
Initialize a new Student instance.
:param name: str, the name of the student
:param age: int, the age of the student
:param grades: list of int, the grades of the student
"""
self._name = nam... | opencodeinstruct | generic | self-instruct | 1 | 5 | |
You are given two lists of integers, `list_a` and `list_b`. Your task is to implement a function `find_common_elements(list_a, list_b)` that returns a new list containing only the elements that appear in both `list_a` and `list_b`. The order of elements in the resulting list should be the same as they appear in `list_b... | ```python
def find_common_elements(list_a, list_b):
"""
Returns a list of elements that are common to both list_a and list_b,
maintaining the order as they appear in list_b.
:param list_a: List of integers.
:param list_b: List of integers.
:return: List of integers that are common to both i... | opencodeinstruct | generic | evol-instruct | 1 | 5 | |
You are tasked with implementing a function to determine if a given string is a palindrome. A string is considered a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Your function should be named `is_palind... | ```python
def is_palindrome(s: str) -> bool:
"""
Determines if the given string is a palindrome, considering only
alphanumeric characters and ignoring cases.
:param s: The string to be checked.
:return: True if the string is a palindrome, False otherwise.
"""
filtered_chars = [char.lower() ... | opencodeinstruct | generic | self-instruct | 1 | 4.667 | |
You are given a nested list `obj` consisting of integers and other nested lists. Your task is to compute the product of all integers present in the nested list structure. The nested list can be arbitrarily deep. Write a function `nested_product` that performs this task without using recursion.
**Input:**
- A nested li... | ```python
def nested_product(obj):
"""
Computes the product of all integers in a nested list structure without using recursion.
:param obj: A nested list containing integers and other nested lists.
:return: The product of all integers in the nested list.
"""
stack = [obj]
product = 1
wh... | opencodeinstruct | generic | evol-instruct | 1 | 4.667 | |
You are given a dataset of genetic variants, where each variant is represented as an object with the following attributes:
- `p_value`: A float representing the p-value of the variant.
- `effect_size`: A float representing the effect size of the variant.
- `confidence_interval`: A tuple of two floats representing the c... | ```python
class Variant:
def __init__(self, p_value, effect_size, confidence_interval, sample_size):
self.p_value = p_value
self.effect_size = effect_size
self.confidence_interval = confidence_interval
self.sample_size = sample_size
def is_significant_variant(variant):
"""
D... | opencodeinstruct | generic | evol-instruct | 1 | 5 | |
You are given an iterable of integers. Your task is to implement a function `prime_generator(iterable)` that returns a set of prime numbers present in the iterable. Use the Sundaram sieve algorithm to efficiently find prime numbers, ensuring that your solution can handle large input ranges without exceeding memory limi... | ```python
def prime_generator(iterable):
"""
Returns a set of prime numbers present in the given iterable using the Sundaram sieve algorithm.
:param iterable: An iterable of integers.
:return: A set of prime numbers found in the iterable.
"""
if not iterable:
return set()
max_num =... | opencodeinstruct | generic | evol-instruct | 1 | 5 | |
Implement a Python function that generates an infinite sequence of prime numbers using a generator. Your function should yield prime numbers one by one when called repeatedly. The function should be efficient and capable of generating large prime numbers.
**Sample Input/Output:**
- The function does not take any input... | ```python
def prime_generator():
"""
Generator function to yield an infinite sequence of prime numbers.
Yields:
int: The next prime number in the sequence.
"""
D = {} # Dictionary to store composite numbers and their smallest prime factors
q = 2 # First prime number
while Tr... | opencodeinstruct | generic | self-instruct | 1 | 5 | |
You are given a list of `items` and a `preferred_order` list. Each item in the `items` list is a dictionary with a `'title'` key. Your task is to reorder the `items` list based on the `preferred_order` list. If an item's title is present in the `preferred_order` list, it should be placed in the output list in the order... | ```python
def reorder_items(items, preferred_order):
"""
Reorders the items list based on the preferred_order list.
Parameters:
items (list of dict): List of items where each item is a dictionary with a 'title' key.
preferred_order (list of str): List of titles indicating the preferred order.
... | opencodeinstruct | generic | evol-instruct | 1 | 3 | |
You are given a list of strings. Your task is to group these strings into anagrams and return the grouped lists. Two strings are anagrams if they can be rearranged to form each other. For example, given the input `['eat', 'tea', 'tan', 'ate', 'nat', 'bat']`, the output should be `[['eat', 'tea', 'ate'], ['tan', 'nat'],... | ```python
def group_anagrams(strs):
"""
Groups a list of strings into anagrams.
:param strs: List of strings to be grouped.
:return: A list of lists, where each sublist contains anagrams.
"""
from collections import defaultdict
anagrams = defaultdict(list)
for s in strs:
s... | opencodeinstruct | algorithmic | self-instruct | 1 | 4.667 |
End of preview. Expand in Data Studio
No dataset card yet
- Downloads last month
- -