Dataset Viewer
Auto-converted to Parquet Duplicate
problem_group_id
stringlengths
12
12
⌀
instruction
stringlengths
128
5.51k
⌀
code
stringlengths
54
6.42k
⌀
_source
stringclasses
3 values
afd1af571f1f
You are given a string `expression` consisting of characters including parentheses `()`, square brackets `[]`, and curly braces `{}`. Your task is to determine if the brackets in the expression are balanced. A string with balanced brackets means that each opening bracket has a corresponding closing bracket of the same ...
def is_balanced_brackets(expression): """ Checks if all the brackets in the given expression are balanced. :param expression: A string containing characters including parentheses, square brackets, and curly braces. :return: True if the brackets are balanced, False otherwise. """ stack = [] ...
JetBrains-Research/OpenCodeInstruct-Clean
4fbdb7c9a8b8
You are given a list of integers `numbers`. Your task is to implement a function `find_mode` that determines the mode of the list, which is the element that appears most frequently. In the event of a tie, where multiple elements share the highest frequency, return the smallest of these elements. If the list is empty, t...
def find_mode(numbers): """ Returns the mode of the list of integers. If there is a tie, returns the smallest element among them. Returns None if the list is empty. :param numbers: List of integers :return: Integer or None """ if not numbers: return None frequency = {} ...
JetBrains-Research/OpenCodeInstruct-Clean
9271ff007eb7
You are tasked with implementing a function named `factorial` that calculates the factorial of a non-negative integer `n`. The factorial of a non-negative integer `n` is the product of all positive integers less than or equal to `n`. By definition, the factorial of 0 is 1. Your function should raise a `ValueError` if a...
def factorial(n): """ Calculate the factorial of a non-negative integer n. Parameters: n (int): A non-negative integer whose factorial is to be computed. Returns: int: The factorial of the given integer n. Raises: ValueError: If n is a negative integer. """ if n < ...
JetBrains-Research/OpenCodeInstruct-Clean
af58cae75cab
You are given a list of integers. Your task is to write a Python function that returns the second largest unique integer in the list. If the list contains fewer than two unique integers, the function should return `None`. **Sample Input:** ``` [1, 2, 3, 4, 5] ``` **Sample Output:** ``` 4 ``` **Sample Input:** ``` [5...
def second_largest(numbers): """ Returns the second largest unique integer in the list. If there are fewer than two unique integers, returns None. :param numbers: List of integers :return: Second largest unique integer or None """ unique_numbers = set(numbers) if len(unique_numbers)...
JetBrains-Research/OpenCodeInstruct-Clean
a5e3c8ea5a72
You are tasked with implementing a function `generate_prime_numbers(limit)` that efficiently generates all prime numbers up to a specified limit using the Sieve of Eratosthenes algorithm. Your function should return a list of these prime numbers. **Input:** - An integer `limit` (1 ≤ limit ≤ 10^6), representing the upp...
def generate_prime_numbers(limit): """ Generate a list of prime numbers up to a given limit using the Sieve of Eratosthenes algorithm. :param limit: An integer representing the upper bound up to which prime numbers should be generated. :return: A list of integers, where each integer is a prime number l...
JetBrains-Research/OpenCodeInstruct-Clean
193a7fc071ec
In a graphics programming competition, you are tasked with creating a function to generate random colors for a digital art project. Implement a Python function `generate_random_color` that returns a random color in the RGB color model as a tuple of three integers, each ranging from 0 to 255. Use the `random` module to ...
import random def generate_random_color(): """ Generates a random color in the RGB color model. Returns: tuple: A tuple of three integers representing the RGB values, each ranging from 0 to 255. """ red = random.randint(0, 255) green = random.randint(0, 255) blue = random.randint(0...
JetBrains-Research/OpenCodeInstruct-Clean
4bdaceecaa85
You are given a list of integers. Your task is to implement a function that returns the top 5 largest integers from the list, sorted in descending order. If the list contains fewer than 5 integers, return the entire list sorted in descending order. **Input:** - A list of integers `numbers` (1 ≤ len(numbers) ≤ 1000), w...
def top_five_numbers(numbers): """ Returns the top 5 largest numbers from the list, sorted in descending order. If the list contains fewer than 5 numbers, returns the entire list sorted in descending order. :param numbers: List of integers :return: List of top 5 largest integers sorted in descendin...
JetBrains-Research/OpenCodeInstruct-Clean
f063799b23e2
You are given a positive integer `n`. Your task is to write a function `largest_prime_factor(n)` that returns the largest prime factor of `n`. If `n` is less than 2, the function should return `None`. The function should be optimized to handle large values of `n` efficiently. **Input:** - A single integer `n` (1 ≤ n ≤...
def largest_prime_factor(n): """ Returns the largest prime factor of the given number n. If n is less than 2, returns None. :param n: Integer, the number to find the largest prime factor of. :return: Integer, the largest prime factor of n, or None if n < 2. """ if n < 2: return ...
JetBrains-Research/OpenCodeInstruct-Clean
9271ff007eb7
You are tasked with implementing a function `factorial(n)` that computes the factorial of a given non-negative integer `n`. The factorial of a number `n`, denoted as `n!`, is the product of all positive integers less than or equal to `n`. By definition, `0!` equals `1`. Your function should raise a `ValueError` if `n` ...
def factorial(n): """ Calculate the factorial of a non-negative integer n. Parameters: n (int): A non-negative integer whose factorial is to be computed. Returns: int: The factorial of the integer n. Raises: ValueError: If n is negative. """ if n < 0: raise...
JetBrains-Research/OpenCodeInstruct-Clean
fc9a0a72cd95
You are given a list of integers. 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) ≤ 10^...
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. """ unique_nu...
JetBrains-Research/OpenCodeInstruct-Clean
ad6b82feeb62
You are given a list of integers `prices` where `prices[i]` is the price of a given stock on the `i-th` day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you c...
def max_profit(prices): """ Calculate the maximum profit from a single buy and sell transaction. :param prices: List of integers representing stock prices on consecutive days. :return: Maximum profit that can be achieved. """ if not prices: return 0 min_price = prices[0] max_pr...
JetBrains-Research/OpenCodeInstruct-Clean
59d4d377d7f5
You are tasked with implementing a function `format_duration(seconds)` that takes an integer `seconds` as input and returns a string representing the duration in a human-readable format. The output should be formatted as "X hours, Y minutes, and Z seconds", omitting any part of the duration that is zero. For example, g...
def format_duration(seconds): """ Converts a given number of seconds into a human-readable format. Parameters: seconds (int): The total number of seconds to be converted. Returns: str: A string representing the duration in the format "X hours, Y minutes, and Z seconds", omitti...
JetBrains-Research/OpenCodeInstruct-Clean
6f5d4d308e1a
You are tasked with implementing a function `calculate_discount` that computes the final price of an item after applying a given discount percentage. The function should handle edge cases where the discount percentage is negative (indicating a price increase) or exceeds 100 (indicating the item is free). The final pric...
def calculate_discount(original_price, discount_percentage): """ Calculate the final price of an item after applying a discount percentage. Parameters: original_price (float): The original price of the item. discount_percentage (float): The discount percentage to be applied. Returns: ...
JetBrains-Research/OpenCodeInstruct-Clean
aea1fdc9a945
You are given a dictionary where each key is unique. Your task is to write a function that returns a new dictionary with keys and values swapped. If the original dictionary contains duplicate values, the function should raise a `ValueError` with the message "Duplicate values found in the dictionary". **Input:** - A d...
def reverse_dict(input_dict): """ Reverses the keys and values of the input dictionary. Args: input_dict (dict): A dictionary with unique keys but potentially duplicate values. Returns: dict: A new dictionary with keys and values swapped. Raises: ValueError: If the input d...
JetBrains-Research/OpenCodeInstruct-Clean
570723e5a2ce
You are given two integers, `a` and `b`. Your task is to write a function `compute_gcd` that computes the greatest common divisor (GCD) of these two integers using the Euclidean algorithm. The function should handle negative inputs by considering their absolute values. **Input:** - Two integers `a` and `b` (-10^9 ≤ a...
def compute_gcd(a, b): """Calculate the greatest common divisor of two integers using the Euclidean algorithm. Args: a (int): First integer. b (int): Second integer. Returns: int: The greatest common divisor of a and b. """ a = abs(a) b = abs(b) whi...
JetBrains-Research/OpenCodeInstruct-Clean
6a99a7ae8213
You are tasked with implementing a function to compute the factorial of a given non-negative integer `n`. The factorial of a non-negative integer `n` is the product of all positive integers less than or equal to `n`. By definition, the factorial of 0 is 1. Your implementation should not use any built-in factorial funct...
def calculate_factorial(n): """ Calculate the factorial of a non-negative integer n. Parameters: n (int): A non-negative integer whose factorial is to be computed. Returns: int: The factorial of the given integer n. """ if n == 0: return 1 result = 1 for i ...
JetBrains-Research/OpenCodeInstruct-Clean
1e2d0e1c414e
You are given two lists: `words` and `distances`. Each element in `words` is a string, and each element in `distances` is an integer representing the distance between consecutive words in `words`. Your task is to compute the average distance between all pairs of consecutive words in `words`. If `words` contains fewer t...
def average_distance(words, distances): """ Calculate the average distance between consecutive words in the list. :param words: List of strings representing words. :param distances: List of integers representing distances between consecutive words. :return: Float representing the average distan...
JetBrains-Research/OpenCodeInstruct-Clean
9607a423a054
You are given a list of integers. Your task is to implement a function `filter_even_numbers` that processes this list and returns a new list containing only the even integers from the original list. The function should be able to handle any list of integers, including empty lists and lists with no even numbers. **Inpu...
def filter_even_numbers(numbers): """ Filters even numbers from a given list of integers. Parameters: numbers (list of int): The list of integers to filter. Returns: list of int: A list containing only the even integers from the input list. """ return [num for num in numbers if num % 2...
JetBrains-Research/OpenCodeInstruct-Clean
db6cc6e22537
You are given two sets of integers, `set1` and `set2`. Your task is to implement a function `find_common_elements` that returns a new set containing all elements that are present in both `set1` and `set2`. The function should be able to handle any pair of sets, including empty sets and sets with no common elements. **...
def find_common_elements(set1, set2): """ Returns a set containing the common elements between two input sets. Parameters: set1 (set): The first set of integers. set2 (set): The second set of integers. Returns: set: A set containing the common elements between set1 and set2. """ re...
JetBrains-Research/OpenCodeInstruct-Clean
afd1af571f1f
You are given a string `s` consisting of only the characters '(' and ')'. Your task is to determine if the parentheses in the string are balanced. A string of parentheses is considered balanced if every opening parenthesis '(' has a corresponding closing parenthesis ')', and the pairs are properly nested. **Input:** -...
def is_balanced_parentheses(s): """ Determines if the parentheses in the string are balanced. Args: s (str): A string consisting of '(' and ')'. Returns: bool: True if the string contains balanced parentheses, False otherwise. """ stack = [] for char in s: if char =...
JetBrains-Research/OpenCodeInstruct-Clean
a24c08e776bd
You are given two sentences as strings. Your task is to implement a function `find_common_words(sentence1, sentence2)` that identifies and returns a list of words that appear in both sentences. The comparison should be case-insensitive and punctuation should be ignored. The resulting list of common words must be sorted...
from typing import List import string def find_common_words(sentence1: str, sentence2: str) -> List[str]: """ Finds and returns a sorted list of common words between two sentences, ignoring case and punctuation. :param sentence1: A string representing the first sentence. :param sentence2: A st...
JetBrains-Research/OpenCodeInstruct-Clean
f06531de893b
You are given a list of integers. Your task is to write a Python function that determines the second largest unique number in the list. If the list contains fewer than two unique numbers, the function should return the string "No second largest number". **Input:** - A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^...
def find_second_largest(numbers): """ Finds the second largest unique number in a list of integers. Parameters: numbers (list): A list of integers. Returns: int or str: The second largest unique number, or "No second largest number" if there are fewer than two unique numbers. """ ...
JetBrains-Research/OpenCodeInstruct-Clean
02fce65bcdec
You are given a list of dictionaries, where each dictionary contains information about a person with keys "name" and "age". Your task is to implement a function `average_age(people)` that computes the average age of all individuals in the list. If the list is empty, the function should return `0`. **Input:** - A list ...
def average_age(people): """ Calculate the average age of individuals in a list of dictionaries. :param people: List of dictionaries, each containing 'name' and 'age' keys. :return: Float representing the average age, or 0 if the list is empty. """ if not people: return 0 total_age ...
JetBrains-Research/OpenCodeInstruct-Clean
65eb12046be4
You are given a list of file paths. Your task is to write a Python function `merge_files` that reads the contents of these files and writes them into a single output file in the order they appear in the list. If a file does not exist, your function should print an error message and continue with the next file. Your fun...
def merge_files(file_paths, output_path): """ Merges the contents of multiple files into a single output file. Parameters: file_paths (list of str): List of file paths to be merged. output_path (str): Path to the output file where the merged content will be written. """ try: wit...
JetBrains-Research/OpenCodeInstruct-Clean
fca9000f75bf
You are given a task to implement a simple banking system in Python. The system should support three operations: deposit, withdraw, and check balance. The initial balance is 0. For each operation, you should record a transaction in the format specified below. Implement a function `banking_system` that takes a list of t...
def banking_system(transactions): """ Simulates a simple banking system with deposit, withdraw, and check balance operations. Parameters: transactions (list of tuples): A list where each tuple contains an operation and an amount. Returns: list of str: A list of transaction history stri...
JetBrains-Research/OpenCodeInstruct-Clean
bf63b057faf2
You are given an unsorted list of integers `nums`. Your task is to find the smallest positive integer that does not appear in the list. The solution should be efficient and ideally run in O(n) time complexity with O(1) additional space complexity. **Input:** - A list of integers `nums` (1 ≤ len(nums) ≤ 10^5), where ea...
def find_smallest_missing_positive(nums): """ Finds the smallest missing positive integer in the given list of integers. :param nums: List[int] - A list of integers. :return: int - The smallest missing positive integer. """ n = len(nums) for i in range(n): while 1 <= nums[i...
JetBrains-Research/OpenCodeInstruct-Clean
ac8cf8ddbcf1
You are given an array `arr` of integers. Your task is to implement a function `find_min_max` that returns a tuple `(min, max)` where `min` is the smallest element in the array and `max` is the largest element in the array. The function should handle edge cases such as an empty array or an array with a single element. ...
def find_min_max(arr): """ Finds the minimum and maximum elements in an array of integers. Parameters: arr (list of int): The array of integers. Returns: tuple: A tuple containing the minimum and maximum elements of the array. Returns (None, None) if the array is empty. ...
JetBrains-Research/OpenCodeInstruct-Clean
6840038466f1
You are given a binary search tree (BST) represented as a nested list. Each node in the tree is a list of the form `[value, left_subtree, right_subtree]`, where `value` is an integer, and `left_subtree` and `right_subtree` are either nested lists representing the left and right subtrees, respectively, or `None` if the ...
def find_min(bst): """ Finds and returns the smallest value in a binary search tree (BST) represented as a nested list. :param bst: A nested list representing the BST. :return: The smallest value in the BST, or None if the BST is empty. """ if bst is None: return None left_...
JetBrains-Research/OpenCodeInstruct-Clean
ad3d036e87f8
You are given a list of integers. Your task is to write a Python function that returns a new list with all duplicate elements removed, preserving the original order of the elements. The function should handle edge cases, such as when the input list is empty or contains only one element. **Sample Input:** ``` [1, 2, 3,...
def remove_duplicates(input_list): """ Removes duplicates from the input list while maintaining the original order of elements. Parameters: input_list (list): A list of integers. Returns: list: A new list with duplicates removed. """ seen = set() result = [] for item in input_l...
JetBrains-Research/OpenCodeInstruct-Clean
afd1af571f1f
You are given a string `s` consisting of characters '(', ')', '{', '}', '[' and ']'. Your task is to determine if the string is valid. A string is valid if all opening brackets are closed by the same type of brackets in the correct order. An empty string is considered valid. **Input:** - A single string `s` (0 ≤ |s| ≤...
def is_valid_parentheses(s: str) -> bool: """ Determines if the input string s containing only the characters '(', ')', '{', '}', '[' and ']' is valid. A string is valid if all opening brackets are closed by the same type of brackets in the correct order. An empty string is considered valid. :p...
JetBrains-Research/OpenCodeInstruct-Clean
ebc826ddddb0
You are given an integer `n`. Your task is to write a function `find_prime_factors` that returns a list of all prime factors of `n`. A prime factor is a factor that is a prime number. For example, the prime factors of 28 are 2 and 7, since 28 = 2^2 * 7. Your function should have a time complexity of O(sqrt(n)). **Inpu...
def find_prime_factors(n): """ Returns a list of all prime factors of the given integer n. :param n: Integer to find prime factors for. :return: List of prime factors of n. """ prime_factors = [] while n % 2 == 0: prime_factors.append(2) n //= 2 for i in range(3, i...
JetBrains-Research/OpenCodeInstruct-Clean
342809406f8f
You are tasked with implementing a function `generate_fibonacci_sequence(n)` that generates the first `n` numbers of the Fibonacci sequence. The Fibonacci sequence is defined as follows: F(0) = 0, F(1) = 1, and F(n) = F(n-1) + F(n-2) for n >= 2. Your function should be optimized for large values of `n` and should use a...
def generate_fibonacci_sequence(n): """Generate a list containing the first `n` numbers of the Fibonacci sequence. This function uses an iterative approach to efficiently generate the Fibonacci sequence, suitable for large values of `n`. :param n: Integer, the number of Fibonacci numbers to ge...
JetBrains-Research/OpenCodeInstruct-Clean
80204abc6d76
You are tasked with implementing a function `find_all_primes(n)` that identifies all prime numbers less than or equal to a given integer `n`. Your solution should utilize the Sieve of Eratosthenes algorithm for efficiency. The algorithm iteratively marks the multiples of each prime number starting from 2. **Input:** -...
def find_all_primes(n): """ Returns a list of all prime numbers less than or equal to n using the Sieve of Eratosthenes algorithm. :param n: An integer representing the upper limit. :return: A list of prime numbers less than or equal to n. """ if n < 2: return [] is_prime = [Tr...
JetBrains-Research/OpenCodeInstruct-Clean
40143515745b
You are tasked with implementing an efficient algorithm to compute the power of a number using the exponentiation by squaring method. Your function should handle both positive and negative exponents. The function should take two parameters: the base `x` and the exponent `n`, and return `x` raised to the power of `n`. ...
def power_by_squaring(x, n): """ Calculate x raised to the power of n using the exponentiation by squaring method. Parameters: x (float): The base number. n (int): The exponent. Returns: float: The result of x raised to the power of n. """ if n == 0: return 1 el...
JetBrains-Research/OpenCodeInstruct-Clean
ec1c515d4cb3
You are given a string `s` consisting of words separated by commas. Your task is to write a function that splits the string into a list of non-empty substrings. Each substring should represent a word from the original string. For example, given the input string `"apple,banana,,cherry,,date,"`, your function should retu...
def convert_to_substrings(s): """ Splits the input string by commas and returns a list of non-empty substrings. :param s: A string containing words separated by commas. :return: A list of non-empty substrings. """ return [substring for substring in s.split(',') if substring] # Example usage: s...
JetBrains-Research/OpenCodeInstruct-Clean
d63477aad744
You are given two sorted lists of integers, `list1` and `list2`. Your task is to write a function `merge_sorted_lists(list1, list2)` that merges these two lists into a single sorted list. The function should have a time complexity of O(n + m), where n and m are the lengths of `list1` and `list2`, respectively. **Sampl...
def merge_sorted_lists(list1, list2): """ Merges two sorted lists into a single sorted list. Parameters: list1 (List[int]): The first sorted list. list2 (List[int]): The second sorted list. Returns: List[int]: A merged sorted list containing all elements from both input lists. ...
JetBrains-Research/OpenCodeInstruct-Clean
3c9493ba9759
You are given a CSV file with a header row. Your task is to write a Python function that reads this file and computes the average of the numerical values in the third column. If the file does not exist, your function should print an error message and terminate gracefully. Assume that the third column may contain non-nu...
import csv def calculate_average_of_third_column(csv_file_path): """ Reads a CSV file and calculates the average of the numerical values in the third column. Parameters: csv_file_path (str): The path to the CSV file. Returns: None: Prints the average of the third column or an error me...
JetBrains-Research/OpenCodeInstruct-Clean
2b31ceb77514
You are given a string `text`. Your task is to implement a function `count_vowels(text)` that returns the number of vowels in the string. The function should be case-insensitive and consider the vowels 'a', 'e', 'i', 'o', 'u'. **Input:** - A single string `text` (1 ≤ |text| ≤ 10^5), which may contain letters, digits,...
def count_vowels(text): """ Counts the number of vowels in the given string. Parameters: text (str): The input string to analyze. Returns: int: The number of vowels in the string. """ vowels = set('aeiouAEIOU') return sum(1 for char in text if char in vowels)
JetBrains-Research/OpenCodeInstruct-Clean
2b31ceb77514
You are given a string `text`. Your task is to implement a function `count_vowels` that returns the number of vowels in the string. The function should be case-insensitive, meaning it should count both uppercase and lowercase vowels ('a', 'e', 'i', 'o', 'u'). **Input:** - A single string `text` (1 ≤ |text| ≤ 10^5), co...
def count_vowels(text: str) -> int: """ Counts the number of vowels in the given text. Parameters: text (str): The input string to count vowels in. Returns: int: The number of vowels in the input string. """ vowels = set("aeiouAEIOU") return sum(1 for char in text if char i...
JetBrains-Research/OpenCodeInstruct-Clean
c782c0f8bf74
You are given a list of integers. Your task is to implement a function `find_min_max` that returns a tuple containing the minimum and maximum values from the list. If the list is empty, the function should return `None`. Your solution should be optimized to minimize the number of comparisons. **Sample Input:** ``` [3,...
def find_min_max(numbers): """ Returns a tuple containing the minimum and maximum values from the list. If the list is empty, returns None. :param numbers: List of integers :return: Tuple of (min, max) or None if the list is empty """ if not numbers: return None min_val...
JetBrains-Research/OpenCodeInstruct-Clean
037a8cc59a70
You are given a list of unique items and an integer representing the maximum length of combinations. Your task is to implement a function `generate_combinations` that generates all possible combinations of the items, including the empty set and the set containing all items, up to the specified maximum length. The funct...
from itertools import combinations def generate_combinations(items, max_combination_length): """ Generate all possible combinations of the given items up to the specified maximum length. :param items: List of unique items. :param max_combination_length: Maximum length of the combinations. :ret...
JetBrains-Research/OpenCodeInstruct-Clean
bcb79bfc4e77
You are given a list of integers `numbers` and an integer `k`. Your task is to find the kth smallest unique element in the list. If `k` is larger than the number of unique elements in the list, return `None`. The list may be empty or contain duplicate elements. Return the kth smallest unique element as an integer or `N...
def kth_smallest_element(numbers, k): """ Finds the kth smallest unique element in the list. Parameters: numbers (list of int): The list of integers. k (int): The kth position to find the smallest unique element. Returns: int or None: The kth smallest unique element, or None if k i...
JetBrains-Research/OpenCodeInstruct-Clean
2d0f97e25d6c
You are given a singly linked list where each node contains an integer value and a reference to the next node. Your task is to determine if the linked list is a palindrome, meaning it reads the same forwards and backwards. Implement the function `is_palindrome(head: ListNode) -> bool` that returns `True` if the linked ...
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def is_palindrome(head: ListNode) -> bool: """ Determines if a given singly linked list is a palindrome. :param head: The head node of the linked list. :return: True if the linked list is a pa...
JetBrains-Research/OpenCodeInstruct-Clean
6a99a7ae8213
You are tasked with implementing a recursive function in Python to compute the factorial of a given non-negative integer. Your function should handle invalid inputs gracefully by returning an appropriate error message. Specifically, your function should return an error message if the input is not an integer or if it is...
def factorial(n): """ Computes the factorial of a given non-negative integer n using recursion. Handles invalid inputs by returning an appropriate error message. :param n: A non-negative integer :return: Factorial of integer n or an error message """ if not isinstance(n, int): retur...
JetBrains-Research/OpenCodeInstruct-Clean
f0b6c23d6077
You are given a positive integer `n`. Your task is to determine whether `n` is a prime number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Your solution should be efficient and capable of handling large values of `n`. The function should run in O(sqrt(n)) tim...
def is_prime(n): """ Check if a number is a prime number. Parameters: n (int): The number to check for primality. Returns: bool: True if n is a prime number, False otherwise. """ if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0:...
JetBrains-Research/OpenCodeInstruct-Clean
c2188bacfc2c
You are given a list of integers `weights` representing the weights of objects. Your task is to implement a function `find_min_max_indices` that returns a tuple containing the indices of the first occurrences of the minimum and maximum weights in the list, respectively. If the list is empty, the function should return ...
def find_min_max_indices(weights): """ Returns a tuple containing the indices of the first occurrences of the minimum and maximum weights in the list. If the list is empty, returns (-1, -1). :param weights: List of integers representing the weights of objects. :return: Tuple of two integers (mi...
JetBrains-Research/OpenCodeInstruct-Clean
3c35d6f5f347
You are given a string `s`. Your task is to determine if `s` is a palindrome, considering only alphanumeric characters and ignoring cases. A string is a palindrome if it reads the same backward as forward. **Input:** - A single string `s` (1 ≤ |s| ≤ 10^5), where `s` consists of ASCII characters. **Output:** - Return...
def is_palindrome(s: str) -> bool: """ Determines if the given string is a palindrome, considering only alphanumeric characters and ignoring cases. :param s: The input string. :return: True if the string is a palindrome, False otherwise. """ filtered_chars = [char.lower() for char in s if c...
JetBrains-Research/OpenCodeInstruct-Clean
a4aefc93ebb1
You are given a list of integers `numbers` and an integer `target`. Your task is to implement a function `find_indices` that returns a list of all indices in `numbers` where the value is equal to `target`. The function must utilize a list comprehension. If the `target` is not present in the list, the function should re...
def find_indices(numbers, target): """ Returns a list of all indices in `numbers` where the value is equal to `target`. :param numbers: List of integers. :param target: Integer to find in the list. :return: List of indices where the target is found. """ return [index for index, value in...
JetBrains-Research/OpenCodeInstruct-Clean
afd1af571f1f
You are given a string `s` consisting of characters '(', ')', '{', '}', '[' and ']'. Your task is to determine if the input string is valid. A string is considered valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. Write a function `is_balance...
def is_balanced(s: str) -> bool: """ Determines if the input string s, consisting of '(', ')', '{', '}', '[' and ']', is a valid sequence of brackets. :param s: A string containing only the characters '(', ')', '{', '}', '[' and ']'. :return: True if the string is valid, False otherwise. """ ...
JetBrains-Research/OpenCodeInstruct-Clean
26b8bc381492
You are given an integer `n`. Your task is to write a function `find_smallest_prime_factor` that returns the smallest prime factor of `n`. If `n` is less than or equal to 1, the function should return `None`. **Input:** - An integer `n` (1 ≤ n ≤ 10^9) **Output:** - Return the smallest prime factor of `n` as an intege...
def find_smallest_prime_factor(n): """Return the smallest prime factor of n. Returns None if n <= 1. """ if n <= 1: return None for i in range(2, int(n**0.5) + 1): if n % i == 0: return i return n # Test the function print(find_smallest_prime_factor(1)) # Output sh...
JetBrains-Research/OpenCodeInstruct-Clean
e0ab1c50fb4e
You are given a list of numbers that may contain both integers and floats. Implement a function `calculate_average` that computes the average of these numbers and returns it as a float. The function should handle an empty list by returning 0.0. Your solution should be efficient and robust. **Sample Input/Output:** - I...
def calculate_average(numbers): """ Calculate the average of a list of numbers that may contain both integers and floats. :param numbers: List of integers and/or floats. :return: The average as a float. Returns 0.0 if the list is empty. """ if not numbers: return 0.0 return sum(...
JetBrains-Research/OpenCodeInstruct-Clean
6ccbd0464451
You are given a Cartesian coordinate system with a point defined by its x and y coordinates. Your task is to write a function `convert_to_polar` that computes and returns the polar coordinates (radius and angle in radians) of the given point. The function should accept a tuple of two integers or floats representing the...
import math def convert_to_polar(cartesian_coords): """ Convert Cartesian coordinates to polar coordinates. Parameters: cartesian_coords (tuple): A tuple of two numbers (x, y) representing the Cartesian coordinates. Returns: tuple: A tuple of two numbers (radius, angle) representing the polar...
JetBrains-Research/OpenCodeInstruct-Clean
bbea1c50ece2
You are given a list of non-empty strings `strings`. Your task is to implement a function `longest_string` that returns the longest string in the list. If there are multiple strings with the same maximum length, the function should return the first one encountered. **Input:** - A list of strings `strings` (1 ≤ len(str...
def longest_string(strings): """ Returns the longest string in the given list of strings. If there are multiple strings with the same maximum length, returns the first one. :param strings: List of non-empty strings :return: The longest string in the list """ if not strings: # Check if ...
JetBrains-Research/OpenCodeInstruct-Clean
8fcb96a76240
You are given a binary tree. Your task is to perform a level-order traversal (breadth-first traversal) of the tree and return the result as a list of lists. Each inner list should contain the values of the nodes at that level of the tree. **Input:** - The input is a binary tree represented by its root node. Each node ...
from collections import deque class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def level_order_traversal(root): """ Perform a level-order traversal of a binary tree and return the result as a list of lists. ...
JetBrains-Research/OpenCodeInstruct-Clean
3204a9caf00f
You are tasked with writing a Python script to process a CSV file named "sales_data.csv" and compute the total revenue for each product. The CSV file contains the following columns: - **Product**: The name of the product. - **Quantity**: The quantity of the product sold. - **Price**: The price per unit of the product....
import csv def calculate_total_revenue(): """ Reads a CSV file named 'sales_data.csv', calculates the total revenue for each product, and prints the results. Handles errors such as missing files or incorrect data formats. """ try: with open('sales_data.csv', 'r') as csvfile: rea...
JetBrains-Research/OpenCodeInstruct-Clean
7ab2ff5c46d8
You are given a list of integers. Your task is to implement a function `filter_prime_numbers` that filters out the prime numbers from the list. A prime number is defined as a positive integer greater than 1 that has no divisors other than 1 and itself. The function should return a new list containing only the prime num...
def filter_prime_numbers(numbers): """ Filters out the prime numbers from the input list. Parameters: numbers (list of int): A list of integers. Returns: list of int: A list containing only the prime numbers from the input list. """ def is_prime(n): if n <= 1: retur...
JetBrains-Research/OpenCodeInstruct-Clean
1d42c6f3a186
You are given a string `s` that may contain spaces, tabs, and newlines. Your task is to implement a function `remove_whitespace` that returns a new string with all whitespace characters removed. **Input:** - A single string `s` (1 ≤ |s| ≤ 10^5), where |s| denotes the length of the string. **Output:** - A string with...
def remove_whitespace(s): """ Removes all whitespace characters from the input string s. Parameters: s (str): The input string which may contain spaces, tabs, and newlines. Returns: str: A new string with all whitespace characters removed. """ return ''.join(char for char in s if not c...
JetBrains-Research/OpenCodeInstruct-Clean
9355705d22bb
You are given a string `input_string`. Your task is to write a function `remove_vowels` that removes all vowels (both uppercase and lowercase) from the string and returns the resulting string. **Input:** - A single string `input_string` (1 ≤ len(input_string) ≤ 1000). **Output:** - A string with all vowels removed. ...
def remove_vowels(input_string): """ Removes all vowels (both uppercase and lowercase) from the input string. Parameters: input_string (str): The string from which vowels will be removed. Returns: str: The string with all vowels removed. """ vowels = ["a", "e", "i", "o", "u", "A", "E",...
JetBrains-Research/OpenCodeInstruct-Clean
30fc9dfbcb1d
You are given a list of integers. Your task is to identify and return a list of all duplicate integers present in the input list. The order of elements in the output list does not matter. Optimize your solution to minimize the time complexity. **Sample Input:** ``` [1, 2, 3, 4, 5, 3, 2, 6, 7, 8, 8] ``` **Sample Outpu...
def find_duplicates(input_list): """ Returns a list of duplicate integers from the input list. :param input_list: List of integers :return: List of duplicate integers """ seen = set() duplicates = set() for item in input_list: if item in seen: duplicates.add(item...
JetBrains-Research/OpenCodeInstruct-Clean
faec46f17167
You are given a list of integers. Your task is to write a function `square_numbers` that takes this list as input and returns a new list containing the squares of the original integers. You must implement this function using a list comprehension. **Sample Input:** ```python [1, 2, 3, 4, 5] ``` **Sample Output:** ```p...
def square_numbers(numbers): """ Returns a list of squares of the given list of integers. :param numbers: List of integers :return: List of integers where each integer is the square of the corresponding integer in the input list """ return [number ** 2 for number in numbers]
JetBrains-Research/OpenCodeInstruct-Clean
09817940112b
You are tasked with implementing a Python generator function named `fibonacci_sequence` that produces an infinite sequence of Fibonacci numbers. The function should yield the next number in the sequence each time it is invoked. Your implementation should be efficient and capable of generating Fibonacci numbers indefini...
def fibonacci_sequence(): """ A generator function that yields an infinite sequence of Fibonacci numbers. Yields: int: The next number in the Fibonacci sequence. """ a, b = 0, 1 while True: yield a a, b = b, a + b
JetBrains-Research/OpenCodeInstruct-Clean
2edc7dc0f4c6
You are given a string `s` consisting of `(` and `)` characters. Your task is to determine the length of the longest valid (well-formed) parentheses substring within `s`. A valid parentheses substring is defined as a substring that is properly nested and matched. **Input:** - A single string `s` (1 ≤ |s| ≤ 30,000) con...
def longest_valid_parentheses(s: str) -> int: """ Finds the length of the longest valid (well-formed) parentheses substring in the given string `s`. :param s: A string consisting of '(' and ')' characters. :return: The length of the longest valid parentheses substring. """ max_length = 0 st...
JetBrains-Research/OpenCodeInstruct-Clean
5e4d0b120409
You are given a string `s`. Your task is to determine if `s` is a valid representation of a floating-point number. A valid floating-point number can be positive or negative, may contain a decimal point, and must have at least one digit. The string should be considered valid if it can be converted to a float without cau...
def is_valid_float(s): """ Determines if the given string is a valid representation of a floating-point number. :param s: The string to be checked. :return: True if the string is a valid floating-point number, False otherwise. """ # Strip leading/trailing whitespace s = s.strip() ...
JetBrains-Research/OpenCodeInstruct-Clean
9b3c718441ad
You are given an integer `num`. Your task is to write a function `find_prime_factors` that returns a list of its prime factors in ascending order. Each prime factor should appear in the list as many times as it divides the number. For example, if `num` is 60, the function should return `[2, 2, 3, 5]` because `60 = 2 x ...
def find_prime_factors(num): """ Given an integer num, return a list of prime factors, with each factor appearing the number of times it appears in the prime factorization. :param num: Integer to factorize :return: List of prime factors in ascending order """ prime_factors = [] # Check ...
JetBrains-Research/OpenCodeInstruct-Clean
1eff9757c0d7
You are given a list of integers `numbers` containing at least two distinct values. Your task is to implement a function `find_second_largest(numbers)` that returns the second largest integer in the list. **Input:** - A list of integers `numbers` (2 ≤ len(numbers) ≤ 10^5), where each integer is in the range [-10^9, 10...
def find_second_largest(numbers): """ Finds and returns the second largest number in a list of integers. :param numbers: List of integers with at least two distinct values. :return: The second largest integer in the list. :raises ValueError: If the list does not contain at least two distinct nu...
JetBrains-Research/OpenCodeInstruct-Clean
342809406f8f
You are tasked with implementing a function `get_fibonacci_sequence(n)` that generates the first `n` numbers of the Fibonacci sequence, starting from 0 and 1. The function should return a list containing these numbers. If `n` is less than or equal to 0, the function should return an empty list. **Sample Input and Outp...
def get_fibonacci_sequence(n): """ Generates the first n numbers of the Fibonacci sequence. Parameters: n (int): The number of Fibonacci numbers to generate. Returns: list: A list containing the first n Fibonacci numbers, or an empty list if n <= 0. """ if n <= 0: retur...
JetBrains-Research/OpenCodeInstruct-Clean
428bd143047e
You are given a JSON file and a task to update a specific field within it. Your program should read the JSON file, update the specified field with a new value, and then write the updated JSON back to the file. Your program should handle the following errors gracefully: - If the file does not exist, print "File not foun...
import json def update_json_field(file_path, field_name, new_value): """ Updates a specific field in a JSON file with a new value and saves the changes. Parameters: file_path (str): The path to the JSON file. field_name (str): The name of the field to update. new_value (any): The new value...
JetBrains-Research/OpenCodeInstruct-Clean
80204abc6d76
You are tasked with implementing a function `find_all_primes` that identifies all prime numbers up to and including a given integer `n`. Your solution must utilize the Sieve of Eratosthenes algorithm. The function should return a list of prime numbers in ascending order. **Input:** - An integer `n` (1 ≤ n ≤ 10^6) **...
def find_all_primes(n): """ Returns a list of all prime numbers less than or equal to n using the Sieve of Eratosthenes algorithm. :param n: An integer representing the upper limit. :return: A list of prime numbers up to and including n. """ if n < 2: return [] sieve = [True] *...
JetBrains-Research/OpenCodeInstruct-Clean
ad3d036e87f8
You are given a list of integers. Your task is to write a Python function that removes all duplicate elements from the list while maintaining the original order of the remaining elements. If the list is empty or contains only one element, return the list unchanged. **Input:** - A list of integers `lst` where `0 <= len...
def remove_duplicates_preserve_order(lst): """ Removes duplicates from the list while preserving the original order of elements. Parameters: lst (list): A list of integers. Returns: list: A list of integers with duplicates removed. """ if len(lst) <= 1: return lst ...
JetBrains-Research/OpenCodeInstruct-Clean
71516d1a32e1
You are given a string `s` consisting of words separated by spaces and possibly containing punctuation. Your task is to write a function `count_words` that processes this string and returns a dictionary. The dictionary should have unique words as keys (ignoring case and non-alphabetic characters) and their respective c...
import re from collections import defaultdict def count_words(input_string): """ Processes a string to count occurrences of each unique word, ignoring case and non-alphabetic characters. Parameters: input_string (str): The input string containing words. Returns: dict: A dictionary wit...
JetBrains-Research/OpenCodeInstruct-Clean
3c35d6f5f347
Given a string `s`, find the longest palindromic substring in `s`. A palindromic substring is a sequence of characters that reads the same forward and backward. If there are multiple substrings of the same maximum length, return any one of them. **Constraints:** - `1 <= len(s) <= 1000` - `s` consists of only lowercase...
def longest_palindromic_substring(s: str) -> str: """ Finds the longest palindromic substring in the given string s. :param s: Input string :return: Longest palindromic substring """ if not s: return "" n = len(s) dp = [[False] * n for _ in range(n)] start = 0 m...
JetBrains-Research/OpenCodeInstruct-Clean
20359d378c04
You are given an array `nums` of `n` distinct integers in the range `[0, n]`. Your task is to find the missing number in the array. The solution should be efficient, operating in O(n) time complexity and using O(1) additional space. **Sample Input:** ``` [3, 0, 1] ``` **Sample Output:** ``` 2 ``` **Sample Input:** `...
def find_missing_number(nums): """ Finds the missing number in an array of n distinct integers in the range [0, n]. :param nums: List[int] - A list of n distinct integers. :return: int - The missing number in the range [0, n]. """ missing = len(nums) for i, num in enumerate(nums): m...
JetBrains-Research/OpenCodeInstruct-Clean
a78e30090ae6
You are given a string `s` consisting of various characters. Your task is to implement a function `string_to_words` that processes this string and returns a list of words. A word is defined as a contiguous sequence of alphanumeric characters. Any non-alphanumeric character is treated as a separator. The function should...
import re def string_to_words(input_string): """ Converts a given string into a list of words, where a word is defined as a sequence of consecutive alphanumeric characters. Ignores leading and trailing whitespace characters and treats any non-alphanumeric character as a separator. :param input_str...
JetBrains-Research/OpenCodeInstruct-Clean
3c9493ba9759
You are given a task to process a CSV file named `employees.csv` which contains the following columns: "name", "age", "salary". Your program should read this file, compute the average salary, and print it formatted to two decimal places. If the file does not exist, is empty, or lacks the required columns, your program ...
import csv import os def calculate_average_salary(file_path): """ Reads a CSV file to calculate and print the average salary. Parameters: file_path (str): The path to the CSV file. Returns: None """ if not os.path.isfile(file_path): print(f"Error: The file '{file_path}...
JetBrains-Research/OpenCodeInstruct-Clean
b9db24ef8586
You are tasked with implementing a function `validate_email` that checks if a given email address is valid according to the specified rules. An email address is considered valid if it adheres to the format `username@domain.extension`, where: - The `username` can consist of letters (both uppercase and lowercase), digits...
import re def validate_email(email): """ Validates an email address based on specific rules. Parameters: email (str): The email address to validate. Returns: bool: True if the email address is valid, False otherwise. """ pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$' ...
JetBrains-Research/OpenCodeInstruct-Clean
80204abc6d76
You are tasked with implementing a function to generate prime numbers efficiently. Write a function `generate_prime_numbers(n)` that returns a list of the first `n` prime numbers. Prime numbers are natural numbers greater than 1 that have no positive divisors other than 1 and themselves. Your solution should be optimiz...
def generate_prime_numbers(n): """Generate the first n prime numbers. This function finds the first n prime numbers efficiently using a simple implementation of the Sieve of Eratosthenes variant. Parameters: n (int): The number of primes to generate. Returns: list: A list containing the f...
JetBrains-Research/OpenCodeInstruct-Clean
c734abc01141
You are tasked with implementing a function `calculate_grade(score)` that determines the letter grade for a student based on their score. The grading scale is as follows: - A for scores between 90 and 100 (inclusive) - B for scores between 80 and 89 (inclusive) - C for scores between 70 and 79 (inclusive) - D for score...
def calculate_grade(score): """ Determines the letter grade for a student based on their score. Parameters: score (int or float or str): The student's score, which can be an integer, float, or string representation of a number. Returns: str: The letter grade ('A', 'B', 'C', 'D', 'F') o...
JetBrains-Research/OpenCodeInstruct-Clean
3fb4acba8b60
You are given a string in `snake_case` format. Your task is to write a function `convert_to_pascal_case(snake_str)` that converts this string to `PascalCase`. The function should handle edge cases such as multiple consecutive underscores and leading/trailing underscores. **Input:** - A single string `snake_str` (1 ≤ l...
def convert_to_pascal_case(snake_str): """ Convert a snake_case string to PascalCase. Parameters: snake_str (str): The input string in snake_case format. Returns: str: The converted string in PascalCase. """ components = snake_str.split('_') components = [word for word in c...
JetBrains-Research/OpenCodeInstruct-Clean
afd1af571f1f
You are given a string `s` consisting of characters '(', ')', and other non-parenthesis characters. Your task is to determine if the parentheses in the string are balanced. A string has balanced parentheses if every opening parenthesis '(' has a corresponding closing parenthesis ')', and the pairs of parentheses are pr...
def is_balanced_parentheses(s): """ Determines if the parentheses in the string are balanced. :param s: A string containing characters '(', ')', and other non-parenthesis characters. :return: True if the parentheses are balanced, False otherwise. """ stack = [] for char in s: if cha...
JetBrains-Research/OpenCodeInstruct-Clean
3c35d6f5f347
Given a string `s` consisting of characters, your task is to find the longest palindromic substring within `s`. If there are multiple substrings of the same maximum length, return the one that appears first in the string. If the input string is empty, return an empty string. **Input:** - A single string `s` (0 ≤ |s| ≤...
def longest_palindromic_substring(s: str) -> str: """ Finds the longest palindromic substring in the given string s. If there are multiple substrings of the same maximum length, returns the first one. Returns an empty string if the input string is empty. """ if not s: return "" ...
JetBrains-Research/OpenCodeInstruct-Clean
60ad25b06f8c
You are given a sorted list of integers and a target value. Your task is to implement a function that performs a binary search to find the index of the target value in the list. If the target value is not found, the function should return -1. The function signature is `def binary_search(sorted_list, target)`. **Input...
def binary_search(sorted_list, target): """ Perform binary search on a sorted list to find the index of the target value. Parameters: sorted_list (list of int): A list of integers sorted in non-decreasing order. target (int): The target value to search for in the list. Returns: int...
JetBrains-Research/OpenCodeInstruct-Clean
9b2aa8999206
You are given a string `s` consisting of uppercase and lowercase English letters. Your task is to write a function `convert_case` that transforms the string by converting all uppercase letters to lowercase and all lowercase letters to uppercase. The function should not utilize any built-in string methods for case conve...
def convert_case(s): """ Convert all uppercase letters in the string to lowercase and vice versa. :param s: Input string consisting of uppercase and lowercase English letters. :return: A new string with the case of each letter converted. """ result = "" for char in s: ascii_val ...
JetBrains-Research/OpenCodeInstruct-Clean
8d92d8299843
You are given a list of integers which may contain duplicates. Your task is to determine the second smallest unique integer in the list. If there are fewer than two unique integers, return `None`. **Input:** - A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^5), where each integer is in the range [-10^9, 10^9]. **...
def second_smallest(numbers): """ Returns the second smallest unique integer in the list. If there are fewer than two unique integers, returns None. :param numbers: List of integers :return: Second smallest unique integer or None """ unique_numbers = set(numbers) if len(unique_numbe...
JetBrains-Research/OpenCodeInstruct-Clean
3c35d6f5f347
You are given a string `text`. Your task is to determine if it is a palindrome, ignoring punctuation, whitespace, and capitalization. A palindrome is a string that reads the same forwards and backwards. **Input:** - A single string `text` (1 ≤ len(text) ≤ 1000). **Output:** - Return `True` if `text` is a palindrome, ...
import string def detect_palindrome(text): """ Determines if the given string is a palindrome, ignoring punctuation, whitespace, and capitalization. Parameters: text (str): The input string to check. Returns: bool: True if the string is a palindrome, False otherwise. """ clean...
JetBrains-Research/OpenCodeInstruct-Clean
e200849f687b
You are tasked with implementing a function to validate IPv4 addresses. An IPv4 address consists of four octets, each ranging from 0 to 255, separated by dots. Leading zeros in any octet are not allowed, except for the single digit zero itself. Your function should return `True` if the given string is a valid IPv4 addr...
def validate_ip(ip: str) -> bool: """ Validates if the given string is a valid IPv4 address. :param ip: A string representing the IPv4 address. :return: True if the IP address is valid, False otherwise. """ parts = ip.split('.') if len(parts) != 4: return False for...
JetBrains-Research/OpenCodeInstruct-Clean
9271ff007eb7
You are given a task to debug a recursive function that calculates the factorial of a positive integer `n`. The function is currently incomplete and contains logical errors. Your goal is to correct these errors so that the function returns the correct factorial for all positive integers `n`. Note that you are not allow...
def factorial(n): """ Calculate the factorial of a positive integer n using recursion. Parameters: n (int): A positive integer for which the factorial is to be calculated. Returns: int: The factorial of the integer n. """ if n == 0 or n == 1: return 1 return n * factorial(n...
JetBrains-Research/OpenCodeInstruct-Clean
71bb91e9df37
You are given a positive integer `n`. Your task is to compute the sum of all prime numbers between 1 and `n` (inclusive). Optimize your solution for both time and space complexity. **Input:** - A single integer `n` (1 ≤ n ≤ 10^6) **Output:** - A single integer representing the sum of all prime numbers between 1 and `...
def sum_primes(n): """ Computes the sum of all prime numbers between 1 and n (inclusive). :param n: An integer representing the upper limit. :return: The sum of all prime numbers between 1 and n. """ if n < 2: return 0 is_prime = [True] * (n + 1) p = 2 while p * p <= n: ...
JetBrains-Research/OpenCodeInstruct-Clean
79d51791fda4
You are given a list of strings. Your task is to implement a function that identifies the most frequently occurring string in the list. In the event of a tie, the function should return the string that first achieves the highest frequency. If the list is empty, the function should return `None`. **Sample Input:** ```p...
def most_common_string(strings): """ Returns the most common string in the list. In case of a tie, returns the first string that reaches the highest frequency. Returns None if the list is empty. :param strings: List of strings :return: Most common string or None if the list is empty """ ...
JetBrains-Research/OpenCodeInstruct-Clean
c782c0f8bf74
You are given a list of integers. Your task is to write a Python function that returns a tuple containing the smallest and largest numbers in the list. If the list is empty, the function should return `None`. The function must operate with a time complexity of O(n). **Sample Input:** ``` [3, 1, 4, 1, 5, 9, 2, 6, 5, 3,...
def find_min_max(numbers): """ Returns a tuple containing the smallest and largest numbers in the list. If the list is empty, returns None. :param numbers: List of integers :return: Tuple of (min, max) or None if the list is empty """ if not numbers: return None minimum = m...
JetBrains-Research/OpenCodeInstruct-Clean
ef6dc28decbd
You are given a binary tree where each node contains an integer value. Your task is to compute the sum of all node values in the tree using a recursive approach. The tree is defined by its root node, and each node has pointers to its left and right children. If a node does not have a left or right child, the correspond...
class TreeNode: def __init__(self, value=0, left=None, right=None): self.value = value self.left = left self.right = right def sum_of_all_nodes(root): """ Recursively calculates the sum of all node values in a binary tree. :param root: TreeNode, the root of the binary tree ...
JetBrains-Research/OpenCodeInstruct-Clean
e6719cf90a7c
You are given a list of integers. Your task is to write a Python function that converts this list into a single string, with each integer separated by a comma. The function should be able to handle lists of any length, including an empty list. **Sample Input:** ``` [1, 2, 3, 4, 5] ``` **Sample Output:** ``` "1,2,3,4,...
def list_to_comma_separated_string(int_list): """ Converts a list of integers to a single string with elements separated by commas. Parameters: int_list (list): A list of integers. Returns: str: A string representation of the list with elements separated by commas. """ return '...
JetBrains-Research/OpenCodeInstruct-Clean
5bd8dfe0f19a
You are given two strings `s1` and `s2` of equal length. Determine if `s2` is a rotation of `s1`. A string `s2` is considered a rotation of `s1` if it can be obtained by rotating `s1` in some manner. For example, if `s1 = "waterbottle"` and `s2 = "erbottlewat"`, then `s2` is a rotation of `s1`. **Input:** - Two string...
def is_rotation(s1, s2): """ Determines if s2 is a rotation of s1. :param s1: First string :param s2: Second string :return: True if s2 is a rotation of s1, False otherwise """ if len(s1) != len(s2): return False s1s1 = s1 + s1 return s2 in s1s1 # Example usage: s...
JetBrains-Research/OpenCodeInstruct-Clean
bcf1c4895352
You are given two strings, `a` and `b`. Your task is to determine the minimum number of edit operations (insert, delete, or replace) required to transform string `a` into string `b`. This is known as the Levenshtein distance. **Input:** - Two strings `a` and `b` (1 ≤ |a|, |b| ≤ 1000). **Output:** - An integer represe...
def min_operations(a, b): """ Calculate the minimum number of edit operations (insert, delete, replace) required to transform string a into string b. :param a: First input string :param b: Second input string :return: Minimum number of edit operations """ m = len(a) n = len(b) ...
JetBrains-Research/OpenCodeInstruct-Clean
342809406f8f
Write a Python function to generate the Fibonacci sequence up to the nth number using an iterative approach. The function should return a list containing the Fibonacci sequence up to the nth number. If n is less than or equal to 0, return an empty list. If n is 1, return a list containing only the first Fibonacci numbe...
def fibonacci(n): """ Generate the Fibonacci sequence up to the nth number using an iterative approach. Parameters: n (int): The number of Fibonacci numbers to generate. Returns: list: A list containing the Fibonacci sequence up to the nth number. """ if n <= 0: return ...
JetBrains-Research/OpenCodeInstruct-Clean
f0b6c23d6077
You are given an integer `n`. Your task is to determine if `n` is a prime number. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Write a function `is_prime` that returns `True` if `n` is a prime number and `False` otherwise. **Input:** - An integer `n` (1 ≤ n ≤...
def is_prime(n): """Return True if n is a prime number, otherwise False.""" if n <= 1: return False elif n <= 3: return True elif n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i +...
JetBrains-Research/OpenCodeInstruct-Clean
2b31ceb77514
You are given a string `s`. Your task is to implement a function `count_vowels` that returns the number of vowels in the string. Vowels are defined as 'a', 'e', 'i', 'o', 'u' (both lowercase and uppercase). If the string is empty, the function should return 0. **Input:** - A single string `s` (0 ≤ |s| ≤ 1000). **Outp...
def count_vowels(s): """ Counts the number of vowels in the given string. Parameters: s (str): The input string. Returns: int: The number of vowels in the string. """ vowels = 'aeiouAEIOU' count = sum(1 for char in s if char in vowels) return count # Testing the function with ...
JetBrains-Research/OpenCodeInstruct-Clean
80204abc6d76
You are tasked with implementing a function `generate_prime_numbers(limit: int) -> list` that efficiently generates all prime numbers up to and including a given integer `limit`. Your solution should be optimized for performance, capable of handling large values of `limit` without significant time or memory overhead. ...
def generate_prime_numbers(limit: int) -> list: """ Generate a list of all prime numbers up to and including the given limit. :param limit: The upper bound (inclusive) for generating prime numbers. :return: A list of prime numbers up to the specified limit. """ if limit < 2: return [] ...
JetBrains-Research/OpenCodeInstruct-Clean
342809406f8f
You are given a positive integer `n`. Your task is to write a function that generates the first `n` terms of the Fibonacci sequence. The Fibonacci sequence is defined as follows: the first term is 0, the second term is 1, and each subsequent term is the sum of the two preceding ones. Your function should return the seq...
def generate_fibonacci(n_terms): """ Generate the first n_terms of the Fibonacci sequence. Parameters: n_terms (int): The number of terms in the Fibonacci sequence to generate. Returns: list: A list containing the first n_terms of the Fibonacci sequence. """ if n_terms <= 0: re...
JetBrains-Research/OpenCodeInstruct-Clean
2e2554ee8819
You are given a string `s` consisting of words separated by spaces. Your task is to reverse the order of the words in the string. The resulting string should not contain any leading, trailing, or extra spaces between the words. **Input:** - A single string `s` (1 ≤ len(s) ≤ 1000), where `s` consists of uppercase and l...
def reverse_words(input_string: str) -> str: """ Reverses the order of words in the input string, removing any leading, trailing, or extra spaces. :param input_string: A string containing words separated by spaces. :return: A string with the words in reverse order, with no leading, trailing, or ext...
JetBrains-Research/OpenCodeInstruct-Clean
3c35d6f5f347
You are given a string `s`. Your task is to implement a function `check_palindrome(s)` that returns `True` if the string is a palindrome and `False` otherwise. A string is considered a palindrome if it reads the same forwards and backwards, ignoring case, spaces, and punctuation. **Input:** - A single string `s` (1 ≤ ...
import string def check_palindrome(s): """ Determines if the given string is a palindrome, ignoring case, spaces, and punctuation. :param s: The input string to check. :return: True if the string is a palindrome, False otherwise. """ cleaned = ''.join(char.lower() for char in s if char.isalnum...
JetBrains-Research/OpenCodeInstruct-Clean
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
705