instruction_seed
stringlengths
42
1.67k
response_seed
stringlengths
83
5.94k
testcase
listlengths
3
39
response
stringlengths
46
5.35k
__original_row_idx
int64
0
50k
conversations
listlengths
2
2
Write a function to find the minimum element in a rotated sorted array without duplicates.
Here is the code to solve this problem: ```python def find_minimum(nums): left, right = 0, len(nums) - 1 while left < right: mid = (left + right) // 2 if nums[mid] > nums[right]: left = mid + 1 else: right = mid return nums[left] ```
[ "assert find_minimum([1, 2, 3, 4, 5]) == 1", "assert find_minimum([2, 3, 4, 5, 1]) == 1", "assert find_minimum([3, 4, 5, 1, 2]) == 1" ]
Sure! You can find the minimum element in a rotated sorted array using a modified binary search algorithm. The approach exploits the properties of the rotated array, where if you compare the middle element with the end element, you can determine which part of the array is sorted and which part is rotated. Here is a Py...
1,200
[ { "from": "human", "value": "Write a function to find the minimum element in a rotated sorted array without duplicates." }, { "from": "gpt", "value": "Sure! You can find the minimum element in a rotated sorted array using a modified binary search algorithm. The approach exploits the properties o...
Write a Python function to find the maximum number of consecutive 1's in the binary representation of a given non-negative integer.
Here is the code to solve this problem: ```python def find_max_consecutive_ones(n): binary = bin(n)[2:] max_count = 0 current_count = 0 for bit in binary: if bit == '1': current_count += 1 max_count = max(max_count, current_count) else: current_count ...
[ "assert find_max_consecutive_ones(1023) == 10", "assert find_max_consecutive_ones(15) == 4", "assert find_max_consecutive_ones(13) == 2" ]
Certainly! You can create a function in Python to find the maximum number of consecutive 1's in the binary representation of a given non-negative integer. Here is a sample implementation: ```python def max_consecutive_ones(n: int) -> int: # Convert the integer to its binary representation binary_representation...
1,201
[ { "from": "human", "value": "Write a Python function to find the maximum number of consecutive 1's in the binary representation of a given non-negative integer." }, { "from": "gpt", "value": "Certainly! You can create a function in Python to find the maximum number of consecutive 1's in the bina...
Write a python function to find the Fibonacci number at a given position using recursion.
Here is the code to solve this problem: ```python def fib(n): if n <= 1: return n else: return(fib(n-1) + fib(n-2)) ```
[ "assert fib(0) == 0", "assert fib(5) == 5", "assert fib(1) == 1" ]
Certainly! Below is a Python function that computes the Fibonacci number at a given position using recursion: ```python def fibonacci(n): # base case: the first Fibonacci number is 0 (at position 0) if n == 0: return 0 # base case: the second Fibonacci number is 1 (at position 1) elif n == 1: ...
1,202
[ { "from": "human", "value": "Write a python function to find the Fibonacci number at a given position using recursion." }, { "from": "gpt", "value": "Certainly! Below is a Python function that computes the Fibonacci number at a given position using recursion:\n\n```python\ndef fibonacci(n):\n ...
Write a function that generates all the possible combinations of `n` pairs of balanced parentheses.
Here is the code to solve this problem: ```python def balanced_parentheses(n): """ Generate all combinations of n pairs of balanced parentheses. :param n: Number of pairs of parentheses. :return: List of strings representing all possible combinations of balanced parentheses. """ result = [...
[ "assert balanced_parentheses(1) == [\"()\"]", "assert balanced_parentheses(2) == [\"(())\", \"()()\"]", "assert balanced_parentheses(3) == [\"((()))\", \"(()())\", \"(())()\", \"()(())\", \"()()()\"]" ]
You can generate all the possible combinations of `n` pairs of balanced parentheses using a recursive backtracking approach. Below is a Python function that does just that. ```python def generate_parenthesis(n): def backtrack(current, open_count, close_count): # If the current string is of the correct leng...
1,203
[ { "from": "human", "value": "Write a function that generates all the possible combinations of `n` pairs of balanced parentheses." }, { "from": "gpt", "value": "You can generate all the possible combinations of `n` pairs of balanced parentheses using a recursive backtracking approach. Below is a ...
Write a function that receives a list of integers and returns a list of the positions (0-indexed) where the numbers are palindromes. A palindrome number is a number that remains the same when its digits are reversed.
Here is the code to solve this problem: ```python def find_palindrome_positions(numbers): def is_palindrome(num): return str(num) == str(num)[::-1] return [i for i, num in enumerate(numbers) if is_palindrome(num)] ```
[ "assert find_palindrome_positions([121, 123, 343, 111, 112211]) == [0, 2, 3, 4]", "assert find_palindrome_positions([123, 456, 789, 101]) == [3]", "assert find_palindrome_positions([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33]) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]" ]
You can create a function in Python that checks for palindrome numbers and returns the positions of those palindromic numbers in a given list of integers. Here's a sample implementation of this function: ```python def is_palindrome(num): # Convert the number to string and check if it reads the same forwards and ba...
1,204
[ { "from": "human", "value": "Write a function that receives a list of integers and returns a list of the positions (0-indexed) where the numbers are palindromes.\n\nA palindrome number is a number that remains the same when its digits are reversed." }, { "from": "gpt", "value": "You can create a...
Write a function to check whether a given string is a valid hexadecimal color code or not. A valid hexadecimal color code starts with a '#' followed by exactly six hexadecimal characters (0-9 or a-f, case-insensitive).
Here is the code to solve this problem: ```python import re def is_valid_hex_color(code): if re.match(r'^#([A-Fa-f0-9]{6})$', code): return True else: return False ```
[ "assert is_valid_hex_color(\"#eaecc\") == False", "assert is_valid_hex_color(\"#CD5C5C\") == True", "assert is_valid_hex_color(\"#EAECEE\") == True", "assert is_valid_hex_color(\"##CD5C5C\") == False" ]
You can use a regular expression to validate whether a given string is a valid hexadecimal color code. Here is a Python function that implements this check: ```python import re def is_valid_hex_color_code(s): # Define the regex pattern for a valid hex color code pattern = r'^#([A-Fa-f0-9]{6})$' # Use...
1,205
[ { "from": "human", "value": "Write a function to check whether a given string is a valid hexadecimal color code or not. A valid hexadecimal color code starts with a '#' followed by exactly six hexadecimal characters (0-9 or a-f, case-insensitive)." }, { "from": "gpt", "value": "You can use a reg...
Write a python function to find the maximum sum of any contiguous subarray of size K in a given array.
Here is the code to solve this problem: ```python def max_sub_array_of_size_k(k, arr): max_sum = float('-inf') window_sum = 0 window_start = 0 for window_end in range(len(arr)): window_sum += arr[window_end] if window_end >= k-1: max_sum = max(max_sum, window_sum) ...
[ "assert max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2]) == 9", "assert max_sub_array_of_size_k(2, [2, 3, 4, 1, 5]) == 7", "assert max_sub_array_of_size_k(1, [3, 3, 3, 3]) == 3" ]
You can find the maximum sum of any contiguous subarray of size \( K \) using a sliding window approach. This approach helps to maintain an efficient \( O(n) \) time complexity, where \( n \) is the number of elements in the array. Here’s how you can implement this in Python: ```python def max_sum_subarray(arr, K): ...
1,206
[ { "from": "human", "value": "Write a python function to find the maximum sum of any contiguous subarray of size K in a given array." }, { "from": "gpt", "value": "You can find the maximum sum of any contiguous subarray of size \\( K \\) using a sliding window approach. This approach helps to mai...
Write a function to find the next greater element for each element in an array. The next greater element for an element x is the first greater element on the right side of x in the array. Elements for which no greater element exist, consider the next greater element as -1.
Here is the code to solve this problem: ```python def next_greater_elements(arr): stack = [] res = [-1] * len(arr) for i, t in enumerate(arr): while stack and t > arr[stack[-1]]: stackInd = stack.pop() res[stackInd] = t stack.append(i) return res ```
[ "assert next_greater_elements([2, 7, 3, 5, 4, 6, 8]) == [7, 8, 5, 6, 6, 8, -1]", "assert next_greater_elements([9, 8, 7, 6, 5, 4, 3, 2, 1]) == [-1, -1, -1, -1, -1, -1, -1, -1, -1]", "assert next_greater_elements([1, 2, 3, 4, 5]) == [2, 3, 4, 5, -1]" ]
You can solve the problem of finding the next greater element for each element in an array using a stack. This approach efficiently finds the next greater element for each array element in O(n) time complexity. Below is the Python function that implements this approach: ```python def next_greater_element(arr): # I...
1,207
[ { "from": "human", "value": "Write a function to find the next greater element for each element in an array. The next greater element for an element x is the first greater element on the right side of x in the array. Elements for which no greater element exist, consider the next greater element as -1." },...
Write a python function to find the sum of all even numbers in a given list.
Here is the code to solve this problem: ```python def sum_even_numbers(numbers): return sum(num for num in numbers if num % 2 == 0) ```
[ "assert sum_even_numbers([10, 23, 36, 47, 58]) == 104", "assert sum_even_numbers([1, 2, 3, 4, 5, 6]) == 12", "assert sum_even_numbers([12, 24, 35, 46, 57, 68]) == 150" ]
Certainly! You can find the sum of all even numbers in a given list by iterating through the list and checking each number. If the number is even, you add it to a running total. Here’s a Python function that implements this logic: ```python def sum_of_even_numbers(numbers): total = 0 for number in numbers: ...
1,208
[ { "from": "human", "value": "Write a python function to find the sum of all even numbers in a given list." }, { "from": "gpt", "value": "Certainly! You can find the sum of all even numbers in a given list by iterating through the list and checking each number. If the number is even, you add it t...
Write a python function to find the kth largest element in a given list.
Here is the code to solve this problem: ```python def kth_largest(nums, k): nums.sort() return nums[-k] ```
[ "assert kth_largest([1,2,3,4,5], 1) == 5", "assert kth_largest([3,2,1,5,6,4], 2) == 5", "assert kth_largest([3,2,3,1,2,4,5,5,6], 4) == 4" ]
You can find the kth largest element in a list by sorting the list and then accessing the appropriate index. However, a more efficient approach for large lists is to use a min-heap. Below is an implementation of both methods in Python. ### Method 1: Sorting This method sorts the list and retrieves the kth largest elem...
1,209
[ { "from": "human", "value": "Write a python function to find the kth largest element in a given list." }, { "from": "gpt", "value": "You can find the kth largest element in a list by sorting the list and then accessing the appropriate index. However, a more efficient approach for large lists is ...
Write a function to remove a specific character from a string and return the new string. If the character is not found in the string, return the original string.
Here is the code to solve this problem: ```python def remove_char(string, char): return string.replace(char, "") ```
[ "assert remove_char(\"Python Programming\", \"m\")==\"Python Prograing\"", "assert remove_char(\"Hello, World!\", \"o\")==\"Hell, Wrld!\"", "assert remove_char(\"Data Science\", \"z\")==\"Data Science\"", "assert remove_char(\"123456789\", \"3\")==\"12456789\"" ]
Certainly! Below is a Python function that removes a specific character from a string and returns the modified string. If the character is not found, the function will simply return the original string. ```python def remove_character(s, char_to_remove): # Check if the character is in the string if char_to_remo...
1,210
[ { "from": "human", "value": "Write a function to remove a specific character from a string and return the new string. If the character is not found in the string, return the original string." }, { "from": "gpt", "value": "Certainly! Below is a Python function that removes a specific character fr...
Write a function to calculate the minimum deletion cost to make two strings equal, where the cost is defined as the sum of the ASCII values of the deleted characters.
Here is the code to solve this problem: ```python def minimum_deletion_cost(s1: str, s2: str) -> int: m, n = len(s1), len(s2) dp = [[float('inf') for _ in range(n + 1)] for i in range(m + 1)] dp[0][0] = 0 for i in range(m): dp[i + 1][0] = dp[i][0] + ord(s1[i]) for i in range(n): dp[...
[ "assert minimum_deletion_cost(\"sea\", \"eat\")==231", "assert minimum_deletion_cost(\"vwojt\", \"saqhgdrarwntji\")==1613", "assert minimum_deletion_cost(\"delete\", \"leet\")==403", "assert minimum_deletion_cost(\"a\", \"at\")==116" ]
To solve the problem of finding the minimum deletion cost to make two strings equal, we can approach it by utilizing dynamic programming. The idea is to create a 2D table that helps us calculate the minimum deletion cost step by step. Here’s the function that calculates the minimum deletion cost to make two strings eq...
1,211
[ { "from": "human", "value": "Write a function to calculate the minimum deletion cost to make two strings equal, where the cost is defined as the sum of the ASCII values of the deleted characters." }, { "from": "gpt", "value": "To solve the problem of finding the minimum deletion cost to make two...
Write a python function to return the product of two numbers using recursion.
Here is the code to solve this problem: ```python def rec_product(a, b): if b == 0: return 0 if b > 0: return (a + rec_product(a, b - 1)) if b < 0: return -rec_product(a, -b) ```
[ "assert rec_product(12, 4) == 48", "assert rec_product(7, 0) == 0", "assert rec_product(3, 5) == 15" ]
Certainly! Here’s a Python function that calculates the product of two numbers using recursion: ```python def recursive_product(a, b): # Base case: if b is 0, the product is 0 if b == 0: return 0 # If b is positive, add a and reduce b elif b > 0: return a + recursive_product(a, b - 1) ...
1,212
[ { "from": "human", "value": "Write a python function to return the product of two numbers using recursion." }, { "from": "gpt", "value": "Certainly! Here’s a Python function that calculates the product of two numbers using recursion:\n\n```python\ndef recursive_product(a, b):\n # Base case: i...
Write a python function to check if a given string is a valid parentheses string. A valid parentheses string is a string that is balanced with respect to the parentheses character '('. This means that for every opening parenthesis there is a corresponding closing parenthesis and no closing parenthesis appears before it...
Here is the code to solve this problem: ```python def is_valid_parentheses(s): stack = [] for char in s: if char == '(': stack.append(char) elif char == ')': if not stack: return False stack.pop() return not stack ```
[ "assert is_valid_parentheses(\"()\") == True ", "assert is_valid_parentheses(\"(()\") == False", "assert is_valid_parentheses(\"()()\") == True ", "assert is_valid_parentheses(\")(\") == False ", "assert is_valid_parentheses(\"(()())\") == True", "assert is_valid_parentheses(\"(())\") == True", "assert ...
You can write a Python function to check if a given string is a valid parentheses string by using a simple counter to track the balance of parentheses. Each time you encounter an opening parenthesis '(', you increment the counter, and each time you encounter a closing parenthesis ')', you decrement the counter. If at a...
1,213
[ { "from": "human", "value": "Write a python function to check if a given string is a valid parentheses string. A valid parentheses string is a string that is balanced with respect to the parentheses character '('. This means that for every opening parenthesis there is a corresponding closing parenthesis and...
Write a function that takes a list of numbers as an argument and returns a list of all the prime numbers in the list.
Here is the code to solve this problem: ```python def prime_numbers(nums): def is_prime(n): if n <= 1: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True return [num for num in nums if is_prime(num)] ```
[ "assert prime_numbers([4, 6, 8, 10, 12, 14, 16, 18, 20]) == []", "assert prime_numbers([11, 13, 17, 19, 23]) == [11, 13, 17, 19, 23]", "assert prime_numbers([2, 3, 4, 5, 6, 7, 8, 9, 10]) == [2, 3, 5, 7]" ]
Certainly! Below is a Python function that takes a list of numbers and returns a new list containing only the prime numbers from the input list. ```python def is_prime(n): """Helper function to check if a number is prime.""" if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n %...
1,214
[ { "from": "human", "value": "Write a function that takes a list of numbers as an argument and returns a list of all the prime numbers in the list." }, { "from": "gpt", "value": "Certainly! Below is a Python function that takes a list of numbers and returns a new list containing only the prime nu...
Write a function that takes a string and returns a dictionary with the count of each character in the string.
Here is the code to solve this problem: ```python def char_count(s): result = {} for char in s: if char in result: result[char] += 1 else: result[char] = 1 return result ```
[ "assert char_count(\"aaaabbbb\") == {'a': 4, 'b': 4}", "assert char_count(\"python\") == {'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1}", "assert char_count(\"hello\") == {'h': 1, 'e': 1, 'l': 2, 'o': 1}" ]
Certainly! Below is a Python function that takes a string as input and returns a dictionary with the count of each character in the string. ```python def character_count(s): count_dict = {} for char in s: if char in count_dict: count_dict[char] += 1 else: count_dict[char...
1,215
[ { "from": "human", "value": "Write a function that takes a string and returns a dictionary with the count of each character in the string." }, { "from": "gpt", "value": "Certainly! Below is a Python function that takes a string as input and returns a dictionary with the count of each character i...
Write a python function that takes a string as input and returns the string with all the vowels removed.
Here is the code to solve this problem: ```python def remove_vowels(s): vowels = 'aeiouAEIOU' return ''.join([char for char in s if char not in vowels]) ```
[ "assert remove_vowels(\"AEIOUaeiou\") == \"\"", "assert remove_vowels(\"Hello World\") == \"Hll Wrld\"", "assert remove_vowels(\"Python Programming\") == \"Pythn Prgrmmng\"" ]
You can create a function in Python that removes all vowels from a given string. Here's a simple implementation: ```python def remove_vowels(input_string): vowels = "aeiouAEIOU" result = ''.join(char for char in input_string if char not in vowels) return result # Example usage: input_str = "Hello, World!"...
1,216
[ { "from": "human", "value": "Write a python function that takes a string as input and returns the string with all the vowels removed." }, { "from": "gpt", "value": "You can create a function in Python that removes all vowels from a given string. Here's a simple implementation:\n\n```python\ndef ...
Create a function that takes two integers as input and returns the number of common divisors between the two numbers.
Here is the code to solve this problem: ```python def find_common_divisors(n, m): def gcd(a, b): while b: a, b = b, a % b return a common_divisors = 0 for i in range(1, gcd(n, m) + 1): if n % i == 0 and m % i == 0: common_divisors += 1 return common_divi...
[ "assert find_common_divisors(7, 13) == 1", "assert find_common_divisors(12, 18) == 4", "assert find_common_divisors(25, 35) == 2" ]
To create a function that counts the number of common divisors between two integers, you can follow these steps: 1. Calculate the greatest common divisor (GCD) of the two numbers. The common divisors of two numbers are the divisors of their GCD. 2. Count the number of divisors of the GCD. Here is a Python implementat...
1,217
[ { "from": "human", "value": "Create a function that takes two integers as input and returns the number of common divisors between the two numbers." }, { "from": "gpt", "value": "To create a function that counts the number of common divisors between two integers, you can follow these steps:\n\n1....
Write a python function to find the total number of unique substrings that is a palindrome.
Here is the code to solve this problem: ```python def count_palindrome_substrings(s): def expand_around_center(left, right): count = 0 while left >= 0 and right < len(s) and s[left] == s[right]: count += 1 left -= 1 right += 1 return count total_coun...
[ "assert count_palindrome_substrings(\"aaa\") == 6", "assert count_palindrome_substrings(\"abc\") == 3", "assert count_palindrome_substrings(\"racecar\") == 10" ]
To find the total number of unique palindromic substrings in a given string, you can use a combination of techniques including the "expand around center" strategy. Below is a Python function that implements this approach. This function will locate all substrings that are palindromes and store them in a set to ensure ...
1,218
[ { "from": "human", "value": "Write a python function to find the total number of unique substrings that is a palindrome." }, { "from": "gpt", "value": "To find the total number of unique palindromic substrings in a given string, you can use a combination of techniques including the \"expand arou...
Write a Python function that takes a list of integers as input and returns a new list that contains only the unique elements from the input list, preserving their original order.
Here is the code to solve this problem: ```python def unique_elements(lst): seen = set() result = [] for i in lst: if i not in seen: result.append(i) seen.add(i) return result ```
[ "assert unique_elements([1, 2, 2, 3, 4, 4, 5]) == [1, 2, 3, 4, 5]", "assert unique_elements([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]", "assert unique_elements([10, 20, 20, 30, 40, 40, 50]) == [10, 20, 30, 40, 50]" ]
Certainly! You can create a Python function that filters out duplicate elements from a list while maintaining the original order by using a set to keep track of seen elements. Here's how you can implement this: ```python def unique_elements(input_list): seen = set() unique_list = [] for element in inp...
1,219
[ { "from": "human", "value": "Write a Python function that takes a list of integers as input and returns a new list that contains only the unique elements from the input list, preserving their original order." }, { "from": "gpt", "value": "Certainly! You can create a Python function that filters ...
Write a function to check if a number is a perfect square and then find the next perfect square after it. A perfect square is an integer that is the square of an integer. For example, 1, 4, 9, 16 are perfect squares (1^2, 2^2, 3^2, 4^2) but 2, 3, and 14 are not.
Here is the code to solve this problem: ```python import math def next_perfect_square(n): # Check if n is a perfect square root = math.isqrt(n) if root * root == n: # Find the next perfect square return (root + 1) * (root + 1) else: # Find the nearest greater perfect square ...
[ "assert next_perfect_square(16)==25 ", "assert next_perfect_square(1)==4", "assert next_perfect_square(3)==4 " ]
To check if a number is a perfect square and find the next perfect square, we can implement a Python function that performs these tasks. Below is a function `find_next_perfect_square` that takes an integer as input, checks if it is a perfect square, and if so, finds the next perfect square. ```python import math def ...
1,220
[ { "from": "human", "value": "Write a function to check if a number is a perfect square and then find the next perfect square after it.\n\nA perfect square is an integer that is the square of an integer. For example, 1, 4, 9, 16 are perfect squares (1^2, 2^2, 3^2, 4^2) but 2, 3, and 14 are not." }, { ...
Write a python function to find the number of unique binary search trees (BSTs) that store values 1...n. A unique binary search tree is defined as a binary search tree that is not identical to any other binary search tree. Two binary search trees are considered identical if we can make them exactly the same by swappin...
Here is the code to solve this problem: ```python def num_unique_bst(n): # Initialize a list to store the number of unique binary search trees for each number up to n dp = [0] * (n + 1) # There is 1 unique binary search tree for 0 and 1 nodes dp[0], dp[1] = 1, 1 # Iterate over each number from 2 t...
[ "assert num_unique_bst(5) == 42", "assert num_unique_bst(4) == 14", "assert num_unique_bst(3) == 5" ]
You can find the number of unique binary search trees (BSTs) that can be constructed with `n` distinct values using a well-known combinatorial approach. The number of unique BSTs can be calculated using the Catalan number formula. The `n`-th Catalan number can be calculated using the following recursive formula: \[ C...
1,221
[ { "from": "human", "value": "Write a python function to find the number of unique binary search trees (BSTs) that store values 1...n.\n\nA unique binary search tree is defined as a binary search tree that is not identical to any other binary search tree. Two binary search trees are considered identical if w...
Write a function to find the maximum difference between two elements in a list such that the larger element appears after the smaller one.
Here is the code to solve this problem: ```python def max_diff(arr): max_diff_val = 0 min_val = arr[0] for i in range(1, len(arr)): if arr[i] - min_val > max_diff_val: max_diff_val = arr[i] - min_val if arr[i] < min_val: min_val = arr[i] return max_diff_val ```
[ "assert max_diff([2, 3, 10, 2, 4, 8, 1]) == 8", "assert max_diff([1, 2, 3, 4, 5]) == 4", "assert max_diff([7, 9, 5, 6, 3, 2]) == 2" ]
To find the maximum difference between two elements in a list such that the larger element appears after the smaller one, we can iterate through the list while keeping track of the minimum value we've encountered so far. For each element, we calculate the difference between the current element and the minimum value. We...
1,222
[ { "from": "human", "value": "Write a function to find the maximum difference between two elements in a list such that the larger element appears after the smaller one." }, { "from": "gpt", "value": "To find the maximum difference between two elements in a list such that the larger element appear...
Write a function that accepts a list of integers and returns the list sorted in descending order using the quicksort algorithm.
Here is the code to solve this problem: ```python def quicksort_desc(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x > pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x < pivot] return quicksort_desc(left) + middle + qu...
[ "assert quicksort_desc([3, 6, 8, 10, 1, 2, 1]) == [10, 8, 6, 3, 2, 1, 1]", "assert quicksort_desc([10, 7, 8, 9, 1, 5]) == [10, 9, 8, 7, 5, 1]", "assert quicksort_desc([20, -1, 4, 5, -3, 0]) == [20, 5, 4, 0, -1, -3]" ]
Certainly! Below is a Python function that implements the quicksort algorithm to sort a list of integers in descending order. ```python def quicksort_desc(arr): if len(arr) <= 1: return arr else: pivot = arr[0] # We take the first element as the pivot # Partitioning step: elements grea...
1,223
[ { "from": "human", "value": "Write a function that accepts a list of integers and returns the list sorted in descending order using the quicksort algorithm." }, { "from": "gpt", "value": "Certainly! Below is a Python function that implements the quicksort algorithm to sort a list of integers in ...
Write a function to check if a number is a perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding the number itself.
Here is the code to solve this problem: ```python def is_perfect_number(n): if n < 1: return False sum = 1 i = 2 while i * i <= n: if n % i: i += 1 else: if i * (n // i) == n: sum = sum + i + n//i i += 1 return sum == n ```
[ "assert is_perfect_number(12)==False", "assert is_perfect_number(6)==True", "assert is_perfect_number(28)==True" ]
Sure! A perfect number is a positive integer that is equal to the sum of its proper divisors (the divisors excluding the number itself). For example, 6 is a perfect number because its proper divisors (1, 2, 3) sum up to 6. Here’s a Python function to check if a given number is a perfect number: ```python def is_perfe...
1,224
[ { "from": "human", "value": "Write a function to check if a number is a perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding the number itself." }, { "from": "gpt", "value": "Sure! A perfect number is a positive integer that is equal t...
Write a function to find the nth Lucas number.
Here is the code to solve this problem: ```python def lucas_number(n): if n == 0: return 2 if n == 1: return 1 a, b = 2, 1 for _ in range(2, n + 1): a, b = b, a + b return b ```
[ "assert lucas_number(7) == 29", "assert lucas_number(10) == 123", "assert lucas_number(3) == 4" ]
The Lucas numbers are a sequence similar to the Fibonacci numbers, where each term is the sum of the two preceding ones, but they start with different initial values. The Lucas numbers are defined as follows: - L(0) = 2 - L(1) = 1 - L(n) = L(n-1) + L(n-2) for n > 1 Here's a Python function to find the nth Lucas numbe...
1,225
[ { "from": "human", "value": "Write a function to find the nth Lucas number." }, { "from": "gpt", "value": "The Lucas numbers are a sequence similar to the Fibonacci numbers, where each term is the sum of the two preceding ones, but they start with different initial values. The Lucas numbers are ...
Write a python function to check if a given number is a perfect square or not.
Here is the code to solve this problem: ```python import math def check_perfect_square(num): if num < 0: return False root = math.sqrt(num) return int(root + 0.5) ** 2 == num ```
[ "assert check_perfect_square(16) == True", "assert check_perfect_square(25) == True", "assert check_perfect_square(14) == False" ]
Certainly! A perfect square is a number that can be expressed as the square of an integer. For example, 1, 4, 9, 16, and 25 are perfect squares. Here is a Python function to check if a given number is a perfect square: ```python import math def is_perfect_square(n): if n < 0: return False # Negative num...
1,226
[ { "from": "human", "value": "Write a python function to check if a given number is a perfect square or not." }, { "from": "gpt", "value": "Certainly! A perfect square is a number that can be expressed as the square of an integer. For example, 1, 4, 9, 16, and 25 are perfect squares.\n\nHere is a...
Write a function to count the number of times a specific digit appears in a number.
Here is the code to solve this problem: ```python def count_digit(n, digit): count = 0 while n > 0: if n % 10 == digit: count += 1 n = n // 10 return count ```
[ "assert count_digit(88888888, 7) == 0", "assert count_digit(55055, 5) == 4", "assert count_digit(123456789, 3) == 1" ]
Here’s a simple Python function that counts the number of times a specific digit appears in a given number. The function takes two arguments: the number in which to search for the digit, and the digit itself. It converts the number to a string and counts the occurrences of the digit using the `count` method. ```python...
1,227
[ { "from": "human", "value": "Write a function to count the number of times a specific digit appears in a number." }, { "from": "gpt", "value": "Here’s a simple Python function that counts the number of times a specific digit appears in a given number. The function takes two arguments: the number...
Write a function to create a dictionary from two lists, where the first list is the keys and the second list is the values.
Here is the code to solve this problem: ```python def create_dict(keys, values): dict1 = dict(zip(keys, values)) return dict1 ```
[ "assert create_dict(['w', 'r', 's', 'o', 'u', 'r', 'c', 'e'], [4, 3, 12, 1, 9, 7, 2, 11]) == {'w': 4, 'r': 3, 's': 12, 'o': 1, 'u': 9, 'r': 7, 'c': 2, 'e': 11}", "assert create_dict(['p', 'y', 't', 'h', 'o', 'n'], [2, 4, 6, 8, 10, 12]) == {'p': 2, 'y': 4, 't': 6, 'h': 8, 'o': 10, 'n': 12}", "assert create_dict(...
You can create a function to combine two lists into a dictionary using Python's built-in capabilities. Here's a simple function that accomplishes this: ```python def create_dictionary(keys, values): if len(keys) != len(values): raise ValueError("The length of keys and values must be the same.") re...
1,228
[ { "from": "human", "value": "Write a function to create a dictionary from two lists, where the first list is the keys and the second list is the values." }, { "from": "gpt", "value": "You can create a function to combine two lists into a dictionary using Python's built-in capabilities. Here's a ...
Write a function that finds the maximum XOR value of any subarray within a given list of integers.
Here is the code to solve this problem: ```python from typing import List from functools import reduce from operator import xor def max_xor_subarray(nums: List[int]) -> int: prefix_xor = [0] for num in nums: prefix_xor.append(prefix_xor[-1] ^ num) max_xor = 0 for i in range(len(prefix_xor)): ...
[ "assert max_xor_subarray([5, 2, 1, 6, 4]) == 7", "assert max_xor_subarray([1, 2, 3, 4, 5, 6, 7, 8, 9]) == 15", "assert max_xor_subarray([3, 8, 2, 12, 9, 10]) == 15" ]
To find the maximum XOR value of any subarray within a given list of integers, we can utilize some properties of the XOR operation. The challenge can be addressed efficiently using a method involving prefix XOR and a trie (or directly using knowledge of binary digits). However, for simplicity, we'll implement a straigh...
1,229
[ { "from": "human", "value": "Write a function that finds the maximum XOR value of any subarray within a given list of integers." }, { "from": "gpt", "value": "To find the maximum XOR value of any subarray within a given list of integers, we can utilize some properties of the XOR operation. The c...
Write a function to find the sequences of one or more digits in a string.
Here is the code to solve this problem: ```python import re def find_digits_in_string(s): pattern = r'\b\d+\b' result = re.findall(pattern, s) return list(map(int, result)) ```
[ "assert find_digits_in_string(\"The 12 monkeys ate 98 bananas\")==[12,98]", "assert find_digits_in_string(\"No digits here!\")==[]", "assert find_digits_in_string(\"The monkey ate 1 banana\")==[1]" ]
You can achieve this by using a regular expression in Python. The regular expression can be designed to search for sequences of one or more digits. Here's a simple function that uses the `re` module to find and return all sequences of digits in a given string: ```python import re def find_digit_sequences(input_string...
1,230
[ { "from": "human", "value": "Write a function to find the sequences of one or more digits in a string." }, { "from": "gpt", "value": "You can achieve this by using a regular expression in Python. The regular expression can be designed to search for sequences of one or more digits. Here's a simpl...
Write a function to find all the prime numbers up to a given number.
Here is the code to solve this problem: ```python def find_prime_numbers(n): primes = [] if n >= 2: primes.append(2) for num in range(3, n + 1, 2): for j in range(3, int(num**0.5) + 1, 2): if num % j == 0: break else: primes.append(num) re...
[ "assert find_prime_numbers(10) == [2, 3, 5, 7]", "assert find_prime_numbers(20) == [2, 3, 5, 7, 11, 13, 17, 19]", "assert find_prime_numbers(50) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]" ]
Certainly! One of the most efficient ways to find all prime numbers up to a given number \( n \) is to use the Sieve of Eratosthenes algorithm. Here's a Python function that implements this algorithm: ```python def sieve_of_eratosthenes(n): if n < 2: return [] # Initialize a list to keep track of prim...
1,231
[ { "from": "human", "value": "Write a function to find all the prime numbers up to a given number." }, { "from": "gpt", "value": "Certainly! One of the most efficient ways to find all prime numbers up to a given number \\( n \\) is to use the Sieve of Eratosthenes algorithm. Here's a Python funct...
Write a function to find the number of ways to decode a message using a given mapping of characters to numbers.
Here is the code to solve this problem: ```python def decode_message(s, mapping): cache = {len(s): 1} def dfs(i): if i in cache: return cache[i] if s[i] == "0": return 0 res = dfs(i + 1) if (i + 1 < len(s) and int(s[i:i+2]) <= 26): res += dfs(...
[ "assert decode_message(\"06\", {\"1\": \"A\", \"2\": \"B\", \"3\": \"C\", \"4\": \"D\", \"5\": \"E\", \"6\": \"F\", \"7\": \"G\", \"8\": \"H\", \"9\": \"I\", \"10\": \"J\", \"11\": \"K\", \"12\": \"L\", \"13\": \"M\", \"14\": \"N\", \"15\": \"O\", \"16\": \"P\", \"17\": \"Q\", \"18\": \"R\", \"19\": \"S\", \"20\": ...
To solve the problem of decoding a message using a given mapping of characters to numbers, we can approach it as a dynamic programming problem. The objective is to determine how many ways we can decode a given string of digits based on the mappings. Let's break down the solution: 1. **Mapping**: Assume we have a mapp...
1,232
[ { "from": "human", "value": "Write a function to find the number of ways to decode a message using a given mapping of characters to numbers." }, { "from": "gpt", "value": "To solve the problem of decoding a message using a given mapping of characters to numbers, we can approach it as a dynamic p...
Write a python function to convert a decimal number to its binary representation as a string.
Here is the code to solve this problem: ```python def decimal_to_binary(num): if num == 0: return '0' binary = '' while num > 0: binary = str(num % 2) + binary num = num // 2 return binary ```
[ "assert decimal_to_binary(255) == '11111111'", "assert decimal_to_binary(10) == '1010'", "assert decimal_to_binary(2) == '10'" ]
You can convert a decimal number to its binary representation in Python using various methods. Here's a simple function that uses a loop to build the binary string manually: ```python def decimal_to_binary(n): if n == 0: return "0" elif n < 0: raise ValueError("This function only supports non-n...
1,233
[ { "from": "human", "value": "Write a python function to convert a decimal number to its binary representation as a string." }, { "from": "gpt", "value": "You can convert a decimal number to its binary representation in Python using various methods. Here's a simple function that uses a loop to bu...
Write a python function to find the median of three numbers.
Here is the code to solve this problem: ```python def find_median(a, b, c): if (a - b) * (c - a) >= 0: return a elif (b - a) * (c - b) >= 0: return b else: return c ```
[ "assert find_median(9, 3, 6) == 6", "assert find_median(5, 2, 5) == 5", "assert find_median(1, 2, 3) == 2" ]
You can find the median of three numbers by sorting them and selecting the middle one. Here's a simple Python function that does that: ```python def median_of_three(a, b, c): # Create a list of the three numbers numbers = [a, b, c] # Sort the list numbers.sort() # The median is the second...
1,234
[ { "from": "human", "value": "Write a python function to find the median of three numbers." }, { "from": "gpt", "value": "You can find the median of three numbers by sorting them and selecting the middle one. Here's a simple Python function that does that:\n\n```python\ndef median_of_three(a, b, ...
Write a Python function that finds the minimum path sum from top to bottom in a triangle.
Here is the code to solve this problem: ```python def minPathSum(triangle): """ Finds the minimum path sum from top to bottom in a triangle. Args: - triangle (List[List[int]]): A list of lists representing the triangle. Returns: - int: The minimum path sum from top to bottom. """ if n...
[ " assert minPathSum(triangle1) == 11", "", " assert minPathSum(triangle2) == -1", "", " assert minPathSum(triangle3) == 7", "", " print(\"All test cases passed.\")" ]
Certainly! To find the minimum path sum from the top to the bottom of a triangle represented as a list of lists, we can use dynamic programming. The idea is to work our way from the bottom of the triangle to the top, updating each element to represent the minimum path sum that can be achieved from that element to the b...
1,235
[ { "from": "human", "value": "Write a Python function that finds the minimum path sum from top to bottom in a triangle." }, { "from": "gpt", "value": "Certainly! To find the minimum path sum from the top to the bottom of a triangle represented as a list of lists, we can use dynamic programming. T...
Write a python function to find the maximum subarray sum in an array using Kadane's Algorithm.
Here is the code to solve this problem: ```python def maxSubarraySum(arr): max_current = max_global = arr[0] for i in range(1, len(arr)): max_current = max(arr[i], max_current + arr[i]) if max_current > max_global: max_global = max_current return max_global ```
[ "assert maxSubarraySum([5,4,-1,7,8]) == 23", "assert maxSubarraySum([-2,1,-3,4,-1,2,1,-5,4]) == 6", "assert maxSubarraySum([1]) == 1", "assert maxSubarraySum([-1,-2,-3,-4]) == -1" ]
Certainly! Kadane's Algorithm is an efficient way to find the maximum subarray sum in a given array. The idea is to iterate through the array while keeping track of the maximum subarray sum that ends at the current position, as well as the overall maximum subarray sum found so far. Here's a Python function that implem...
1,236
[ { "from": "human", "value": "Write a python function to find the maximum subarray sum in an array using Kadane's Algorithm." }, { "from": "gpt", "value": "Certainly! Kadane's Algorithm is an efficient way to find the maximum subarray sum in a given array. The idea is to iterate through the array...
Write a function to multiply two non-negative integers represented as strings and return the product as a string.
Here is the code to solve this problem: ```python def multiply_strings(num1, num2): if num1 == "0" or num2 == "0": return "0" len1, len2 = len(num1), len(num2) result = [0] * (len1 + len2) for i in range(len1-1, -1, -1): for j in range(len2-1, -1, -1): mul = (ord(n...
[ "assert multiply_strings(\"2\", \"3\") == \"6\"", "assert multiply_strings(\"123\", \"456\") == \"56088\"", "assert multiply_strings(\"12\", \"12\") == \"144\"" ]
To multiply two non-negative integers represented as strings, you can implement a function that simulates the multiplication process similarly to how you would do it by hand. Below is a Python function that achieves this: ```python def multiply_strings(num1: str, num2: str) -> str: if num1 == "0" or num2 == "0": ...
1,237
[ { "from": "human", "value": "Write a function to multiply two non-negative integers represented as strings and return the product as a string." }, { "from": "gpt", "value": "To multiply two non-negative integers represented as strings, you can implement a function that simulates the multiplicati...
Write a function that takes in a list of integers and returns the maximum product that can be obtained by multiplying any three integers from the list.
Here is the code to solve this problem: ```python def max_product_of_three(nums): nums.sort() return max(nums[0] * nums[1] * nums[-1], nums[-1] * nums[-2] * nums[-3]) ```
[ "assert max_product_of_three([-10, -10, 1, 3, 2]) == 300", "assert max_product_of_three([1, 2, 3, 4]) == 24", "assert max_product_of_three([-1, -2, -3, -4]) == -6", "assert max_product_of_three([1, 2, 3]) == 6", "assert max_product_of_three([-1, -2, 0, 1, 2]) == 4" ]
To achieve the goal of finding the maximum product of any three integers from a list, we can follow these steps: 1. Sort the list of integers. 2. The maximum product can either be achieved by: - The product of the three largest numbers. - The product of the two smallest numbers (which can be negative) and the la...
1,238
[ { "from": "human", "value": "Write a function that takes in a list of integers and returns the maximum product that can be obtained by multiplying any three integers from the list." }, { "from": "gpt", "value": "To achieve the goal of finding the maximum product of any three integers from a list...
Write a function to find the number of unique paths from top-left corner to bottom-right corner of a grid. You can only move either down or right at any point in time.
Here is the code to solve this problem: ```python def uniquePaths(m, n): if m == 0 or n == 0: return 0 dp = [[1 for _ in range(n)] for _ in range(m)] for i in range(1, m): for j in range(1, n): dp[i][j] = dp[i-1][j] + dp[i][j-1] return dp[-1][-1] ```
[ "assert uniquePaths(3, 2) == 3", "assert uniquePaths(3, 7) == 28", "assert uniquePaths(3, 3) == 6" ]
Certainly! To find the number of unique paths from the top-left corner to the bottom-right corner of an `m x n` grid, we can approach this problem using dynamic programming. We can define a 2D array `dp` where `dp[i][j]` represents the number of unique paths to reach the cell `(i, j)` in the grid. The paths to reach a...
1,239
[ { "from": "human", "value": "Write a function to find the number of unique paths from top-left corner to bottom-right corner of a grid. You can only move either down or right at any point in time." }, { "from": "gpt", "value": "Certainly! To find the number of unique paths from the top-left corn...
Write a python function to find the smallest multiple of a number that is greater than or equal to a threshold.
Here is the code to solve this problem: ```python def smallest_multiple(base, threshold): multiple = base while multiple < threshold: multiple += base return multiple ```
[ "assert smallest_multiple(3, 10) == 12", "assert smallest_multiple(7, 30) == 35", "assert smallest_multiple(5, 25) == 25" ]
Certainly! To find the smallest multiple of a given number that is greater than or equal to a specified threshold, you can follow these steps: 1. Check if the threshold is already a multiple of the number. 2. If it is, the threshold itself is the answer. 3. If it is not, calculate the next multiple of the number that ...
1,240
[ { "from": "human", "value": "Write a python function to find the smallest multiple of a number that is greater than or equal to a threshold." }, { "from": "gpt", "value": "Certainly! To find the smallest multiple of a given number that is greater than or equal to a specified threshold, you can f...
Write a function to determine if a given string is a valid identifier according to the following rules: 1. It must only contain alphanumeric characters and underscores. 2. It must not start with a digit. 3. It must not be a Python keyword.
Here is the code to solve this problem: ```python import keyword def is_valid_identifier(s): if keyword.iskeyword(s): return False if not s or not s[0].isalpha() and s[0] != '_': return False for char in s: if not (char.isalnum() or char == '_'): return False return...
[ "assert is_valid_identifier(\"my_var\") == True", "assert is_valid_identifier(\"class_name\") == True", "assert is_valid_identifier(\"2nd_place\") == False", "assert is_valid_identifier(\"for\") == False", "assert is_valid_identifier(\"42isTheAnswer\") == False" ]
To determine if a given string is a valid identifier based on the specified rules, we can implement a function in Python. This function will check if the string meets the conditions outlined: it contains only alphanumeric characters and underscores, does not start with a digit, and is not a Python keyword. Here's how ...
1,241
[ { "from": "human", "value": "Write a function to determine if a given string is a valid identifier according to the following rules:\n1. It must only contain alphanumeric characters and underscores.\n2. It must not start with a digit.\n3. It must not be a Python keyword." }, { "from": "gpt", "va...
Write a function that checks if a string can be constructed from the characters of another string, considering that each character in the second string can only be used once.
Here is the code to solve this problem: ```python from collections import Counter def can_construct(ransomNote: str, magazine: str) -> bool: return (Counter(ransomNote) - Counter(magazine)) == {} ```
[ "assert can_construct(\"aa\", \"aab\") == True", "assert can_construct(\"cat\", \"cut\") == False", "assert can_construct(\"cat\", \"catch\") == True" ]
To solve the problem of checking if a string can be constructed from the characters of another string (where each character can only be used once), we can use a dictionary to count the occurrences of each character in the second string. Then, we can check if we can satisfy the character requirements of the first string...
1,242
[ { "from": "human", "value": "Write a function that checks if a string can be constructed from the characters of another string, considering that each character in the second string can only be used once." }, { "from": "gpt", "value": "To solve the problem of checking if a string can be construct...
Write a function to find the frequency of each character in a string and return the result as a dictionary.
Here is the code to solve this problem: ```python def character_frequency(string): freq = {} for i in string: if i in freq: freq[i] += 1 else: freq[i] = 1 return freq ```
[ "assert character_frequency(\"banana\") == {'b': 1, 'a': 3, 'n': 2}", "assert character_frequency(\"mississippi\") == {'m': 1, 'i': 4, 's': 4, 'p': 2}", "assert character_frequency(\"hello\") == {'h': 1, 'e': 1, 'l': 2, 'o': 1}" ]
You can define a function in Python to find the frequency of each character in a string and return the result as a dictionary. Here’s a sample implementation: ```python def character_frequency(input_string): frequency = {} for char in input_string: if char in frequency: frequency[char] += 1...
1,243
[ { "from": "human", "value": "Write a function to find the frequency of each character in a string and return the result as a dictionary." }, { "from": "gpt", "value": "You can define a function in Python to find the frequency of each character in a string and return the result as a dictionary. H...
Write a python function to find the missing number in a given list of numbers ranging from 1 to n.
Here is the code to solve this problem: ```python def find_Missing_Number(arr): n = len(arr) + 1 total = n * (n + 1) // 2 sum_of_arr = sum(arr) return total - sum_of_arr ```
[ "assert find_Missing_Number([1, 2, 3, 5]) == 4", "assert find_Missing_Number([1, 3, 4, 5]) == 2", "assert find_Missing_Number([2, 3, 4, 5]) == 1" ]
Certainly! You can find the missing number in a list of numbers from 1 to `n` using a simple mathematical approach. The sum of the first `n` natural numbers is given by the formula: \[ \text{Sum} = \frac{n \times (n + 1)}{2} \] Here's a Python function that implements this approach: ```python def find_missing_number...
1,244
[ { "from": "human", "value": "Write a python function to find the missing number in a given list of numbers ranging from 1 to n." }, { "from": "gpt", "value": "Certainly! You can find the missing number in a list of numbers from 1 to `n` using a simple mathematical approach. The sum of the first ...
Write a python function to check if a given string is a valid number. A valid number can be an integer, a floating point number, or a scientific notation. It can be positive or negative. Leading and trailing whitespaces are ignored.
Here is the code to solve this problem: ```python def is_valid_number(s: str) -> bool: s = s.strip() try: if 'e' in s or 'E' in s: if s.count('e') + s.count('E') > 1: return False if '.' in s: float(s) else: int(s.split...
[ "assert is_valid_number(\" -123 \") == True", "assert is_valid_number(\"123.456\") == True", "assert is_valid_number(\"-123.456\") == True", "assert is_valid_number(\"123.456e7\") == True", "assert is_valid_number(\"123\") == True", "assert is_valid_number(\"abc\") == False", "assert is_valid_number(\"...
To determine if a given string is a valid number, we can use Python's built-in capabilities. However, to ensure we're checking for integer formats, floating point formats, and scientific notation, we can build a custom function using regular expressions. Here's a function that accomplishes this: ```python import re d...
1,245
[ { "from": "human", "value": "Write a python function to check if a given string is a valid number. A valid number can be an integer, a floating point number, or a scientific notation. It can be positive or negative. Leading and trailing whitespaces are ignored." }, { "from": "gpt", "value": "To ...
Write a function to check if a given list is monotonic. A list is said to be monotonic if it is either monotonically increasing or monotonically decreasing. A list is monotonically increasing if for all i <= j, A[i] <= A[j]. Similarly, a list is monotonically decreasing if for all i <= j, A[i] >= A[j].
Here is the code to solve this problem: ```python def is_monotonic(A): increasing = decreasing = True for i in range(1, len(A)): if A[i] > A[i - 1]: decreasing = False elif A[i] < A[i - 1]: increasing = False return increasing or decreasing ```
[ "assert is_monotonic([1, 3, 2])==False", "assert is_monotonic([3, 2, 2, 1])==True", "assert is_monotonic([1, 2, 2, 3])==True" ]
To determine if a given list is monotonic (either monotonically increasing or monotonically decreasing), you can create a Python function that checks both conditions. Here's a simple implementation of such a function: ```python def is_monotonic(arr): if not arr: return True # An empty list is considered m...
1,246
[ { "from": "human", "value": "Write a function to check if a given list is monotonic. A list is said to be monotonic if it is either monotonically increasing or monotonically decreasing. A list is monotonically increasing if for all i <= j, A[i] <= A[j]. Similarly, a list is monotonically decreasing if for a...
Write a function to check if a number is a prime number.
Here is the code to solve this problem: ```python def is_prime(n): if n <= 1: return False if n == 2: return True if n % 2 == 0: return False i = 3 while i * i <= n: if n % i == 0: return False i += 2 return True ```
[ "assert is_prime(2) == True", "assert is_prime(15) == False", "assert is_prime(29) == True" ]
Sure! Below is a Python function that checks if a number is a prime number: ```python def is_prime(n): """Check if a number is prime.""" if n <= 1: return False # 0 and 1 are not prime numbers if n <= 3: return True # 2 and 3 are prime numbers if n % 2 == 0 or n % 3 == 0: ret...
1,247
[ { "from": "human", "value": "Write a function to check if a number is a prime number." }, { "from": "gpt", "value": "Sure! Below is a Python function that checks if a number is a prime number:\n\n```python\ndef is_prime(n):\n \"\"\"Check if a number is prime.\"\"\"\n if n <= 1:\n re...
Write a function to find the number of students that need to move in order to make the students line up in non-decreasing order of their heights. A student can be moved to any position in the line.
Here is the code to solve this problem: ```python def student_move_count(heights): ans = 0 hh = sorted(heights) for i, h in enumerate(heights): if hh[i] != h: ans += 1 return ans ```
[ "assert student_move_count([1,1,4,2,1,3])==3", "assert student_move_count([1,2,3,4,5])==0", "assert student_move_count([5,1,2,3,4])==5" ]
To solve the problem of determining the number of students that need to move in order to arrange the Heights in non-decreasing order, we can follow these steps: 1. **Sort the Heights**: Create a sorted version of the original heights list to represent the correct order. 2. **Determine Positions**: Loop through the or...
1,248
[ { "from": "human", "value": "Write a function to find the number of students that need to move in order to make the students line up in non-decreasing order of their heights. A student can be moved to any position in the line." }, { "from": "gpt", "value": "To solve the problem of determining th...
Write a python function to find the number of subarrays in a given array that have a sum divisible by a given number k.
Here is the code to solve this problem: ```python def count_subarrays(arr, k): count = 0 n = len(arr) for i in range(n): sum = 0 for j in range(i, n): sum += arr[j] if sum % k == 0: count += 1 return count ```
[ "assert count_subarrays([1,2,3], 2) == 2", "assert count_subarrays([5], 9) == 0", "assert count_subarrays([4,5,0,-2,-3,1], 5) == 7" ]
To find the number of subarrays in a given array that have a sum divisible by a given number \( k \), we can use a hashmap (or dictionary in Python) to store the frequencies of the prefix sums modulo \( k \). This technique allows us to efficiently count the valid subarrays. Here's a Python function that accomplishes ...
1,249
[ { "from": "human", "value": "Write a python function to find the number of subarrays in a given array that have a sum divisible by a given number k." }, { "from": "gpt", "value": "To find the number of subarrays in a given array that have a sum divisible by a given number \\( k \\), we can use a...
Write a function to find the length of the longest palindromic subsequence in a given string.
Here is the code to solve this problem: ```python def longest_palindromic_subsequence(s: str) -> int: n = len(s) dp = [[0] * n for _ in range(n)] for i in range(n - 1, -1, -1): dp[i][i] = 1 for j in range(i + 1, n): if s[i] == s[j]: dp[i][j] = dp[i + 1][j - 1] + ...
[ "assert longest_palindromic_subsequence(\"a\") == 1", "assert longest_palindromic_subsequence(\"bbbab\") == 4", "assert longest_palindromic_subsequence(\"cbbd\") == 2" ]
You can find the length of the longest palindromic subsequence in a given string using dynamic programming. A palindromic subsequence is a sequence that appears in the same order forwards and backwards. The following Python function implements this approach: ```python def longest_palindromic_subsequence(s: str) -> int...
1,250
[ { "from": "human", "value": "Write a function to find the length of the longest palindromic subsequence in a given string." }, { "from": "gpt", "value": "You can find the length of the longest palindromic subsequence in a given string using dynamic programming. A palindromic subsequence is a seq...
Write a Python function to find the number of days between two dates.
Here is the code to solve this problem: ```python from datetime import datetime def days_between_dates(date1, date2): date_format = "%Y-%m-%d" a = datetime.strptime(date1, date_format) b = datetime.strptime(date2, date_format) delta = b - a return abs(delta.days) ```
[ "assert days_between_dates(date1 = \"2019-06-29\", date2 = \"2019-06-30\") == 1", "assert days_between_dates(date1 = \"2020-01-15\", date2 = \"2019-12-31\") == 15", "assert days_between_dates(date1 = \"2021-03-12\", date2 = \"2021-03-15\") == 3" ]
Certainly! You can use Python's built-in `datetime` module for this task. Below is a function that takes two dates as strings, converts them into `datetime` objects, and then computes the number of days between them. Here's the code: ```python from datetime import datetime def days_between_dates(date_str1, date_str2...
1,251
[ { "from": "human", "value": "Write a Python function to find the number of days between two dates." }, { "from": "gpt", "value": "Certainly! You can use Python's built-in `datetime` module for this task. Below is a function that takes two dates as strings, converts them into `datetime` objects, ...
Write a python function that takes in two strings and returns the length of the longest common subsequence. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Here is the code to solve this problem: ```python def longest_common_subsequence(s1: str, s2: str) -> int: m, n = len(s1), len(s2) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if s1[i - 1] == s2[j - 1]: dp[i][j] = dp[i -...
[ "assert longest_common_subsequence(\"abcde\", \"ace\") == 3", "assert longest_common_subsequence(\"abc\", \"def\") == 0", "assert longest_common_subsequence(\"bsbininm\", \"jmjkbkjkv\") == 1" ]
To find the length of the longest common subsequence (LCS) of two strings, you can use dynamic programming. Here’s a Python function that implements this: ```python def longest_common_subsequence(str1: str, str2: str) -> int: # Get the lengths of both strings m = len(str1) n = len(str2) # Create a 2D ...
1,252
[ { "from": "human", "value": "Write a python function that takes in two strings and returns the length of the longest common subsequence.\n\nA subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements." }, { ...
Write a python function to check if a given graph is bipartite or not. A graph is bipartite if its vertices can be partitioned into two groups such that every edge connects a vertex in one group to a vertex in the other.
Here is the code to solve this problem: ```python from collections import deque def is_bipartite(graph): n = len(graph) visited = {} # not visited for node in range(n): if node not in visited: dq = deque([node]) visited[node] = 0 # set group to arbitary 0 or 1 wh...
[ "assert is_bipartite([[1,3], [0,2], [1,3], [0,2]]) == True", "assert is_bipartite([[1], [0]]) == True", "assert is_bipartite([[1,2,3], [0,2], [0,1,3], [0,2]]) == False" ]
Certainly! To determine if a graph is bipartite, we can use a breadth-first search (BFS) or depth-first search (DFS) algorithm. The basic idea is to try coloring the graph using two colors (often represented as 0 and 1). If we can color the graph without conflicts, then it is bipartite. Here is an implementation of th...
1,253
[ { "from": "human", "value": "Write a python function to check if a given graph is bipartite or not. A graph is bipartite if its vertices can be partitioned into two groups such that every edge connects a vertex in one group to a vertex in the other." }, { "from": "gpt", "value": "Certainly! To d...
Write a function to implement the Sieve of Eratosthenes algorithm which finds all prime numbers up to any given limit.
Here is the code to solve this problem: ```python def sieve_of_eratosthenes(n): primes = [True for i in range(n + 1)] p = 2 while(p * p <= n): if (primes[p] == True): for i in range(p * p, n + 1, p): primes[i] = False p += 1 prime_numbers = [] for p in ra...
[ "assert sieve_of_eratosthenes(10) == [2, 3, 5, 7]", "assert sieve_of_eratosthenes(30) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]", "assert sieve_of_eratosthenes(20) == [2, 3, 5, 7, 11, 13, 17, 19]" ]
Sure! The Sieve of Eratosthenes is an efficient algorithm for finding all prime numbers up to a specified integer. Below is a Python function that implements this algorithm: ```python def sieve_of_eratosthenes(limit): if limit < 2: return [] # Initialize a boolean array of size limit+1 is_prime = ...
1,254
[ { "from": "human", "value": "Write a function to implement the Sieve of Eratosthenes algorithm which finds all prime numbers up to any given limit." }, { "from": "gpt", "value": "Sure! The Sieve of Eratosthenes is an efficient algorithm for finding all prime numbers up to a specified integer. Be...
Write a function to find the maximum difference between two elements in a list, where the larger element comes after the smaller one.
Here is the code to solve this problem: ```python def max_difference(lst): if len(lst) < 2: return 0 min_val = lst[0] max_diff = lst[1] - lst[0] for i in range(1, len(lst)): if lst[i] - min_val > max_diff: max_diff = lst[i] - min_val if lst[i] < min_val: ...
[ "assert max_difference([2, 3, 10, 6, 4, 8, 1]) == 8", "assert max_difference([1, 2, 9, 4, 10, 3]) == 9", "assert max_difference([7, 9, 5, 6, 3, 2]) == 2" ]
Certainly! You can solve the problem of finding the maximum difference between two elements in a list, where the larger element comes after the smaller one, with a single pass through the list. Here's how you can implement this in Python: ```python def max_difference(arr): if len(arr) < 2: return 0 # Not ...
1,255
[ { "from": "human", "value": "Write a function to find the maximum difference between two elements in a list, where the larger element comes after the smaller one." }, { "from": "gpt", "value": "Certainly! You can solve the problem of finding the maximum difference between two elements in a list,...
Write a function that returns the largest number in a list of integers. If the list is empty, return None.
Here is the code to solve this problem: ```python def find_largest(lst): if not lst: return None return max(lst) ```
[ "assert find_largest([1, 2, 3, 4, 5]) == 5", "assert find_largest([-1, -2, -3, -4, 0]) == 0", "assert find_largest([10, 5, 2, 7, 8, 7]) == 10", "assert find_largest([]) == None" ]
Certainly! Below is a Python function that takes a list of integers as input and returns the largest number in the list. If the list is empty, it returns `None`. ```python def find_largest_number(numbers): if not numbers: # Check if the list is empty return None else: largest = numbers[0] # I...
1,256
[ { "from": "human", "value": "Write a function that returns the largest number in a list of integers. If the list is empty, return None." }, { "from": "gpt", "value": "Certainly! Below is a Python function that takes a list of integers as input and returns the largest number in the list. If the l...
Write a function to find the length of the longest substring of repeated characters in a given string.
Here is the code to solve this problem: ```python def longest_repeated_substring(s): if len(s) == 0: return 0 max_length = 1 current_length = 1 for i in range(1, len(s)): if s[i] == s[i-1]: current_length += 1 max_length = max(max_length, current_length) ...
[ "assert longest_repeated_substring(\"aaabbbcccccdd\") == 5", "assert longest_repeated_substring(\"aabbccddeeffgg\") == 2", "assert longest_repeated_substring(\"zzzzzzzz\") == 8", "assert longest_repeated_substring(\"\") == 0", "assert longest_repeated_substring(\"abcd\") == 1" ]
Certainly! You can write a function in Python that finds the length of the longest substring consisting of repeated characters. Here's a simple implementation of that function: ```python def longest_repeated_substring(s): if not s: return 0 max_length = 1 current_length = 1 # Loop thr...
1,257
[ { "from": "human", "value": "Write a function to find the length of the longest substring of repeated characters in a given string." }, { "from": "gpt", "value": "Certainly! You can write a function in Python that finds the length of the longest substring consisting of repeated characters. Here'...
Write a python function that takes an array of integers and returns the maximum sum of non-adjacent elements in the array. The function should return 0 if the array is empty or contains only negative numbers.
Here is the code to solve this problem: ```python def max_sum_non_adjacent(arr): if len(arr) == 0: return 0 dp = [0] * len(arr) dp[0] = max(0, arr[0]) dp[1] = max(dp[0], arr[1]) for i in range(2, len(arr)): dp[i] = max(dp[i-1], dp[i-2] + arr[i]) return dp[-1] ```
[ "assert max_sum_non_adjacent([3, 2, 7, 10]) == 13", "assert max_sum_non_adjacent([3, 2, 5, 10, 7]) == 15", "assert max_sum_non_adjacent([-1, -2, -3, -4]) == 0" ]
You can solve this problem using dynamic programming. The idea is to use an iterative approach to keep track of the maximum sum while ensuring that you do not select adjacent elements. Here's a Python function that accomplishes this: ```python def max_non_adjacent_sum(nums): if not nums: # Check if the array is e...
1,258
[ { "from": "human", "value": "Write a python function that takes an array of integers and returns the maximum sum of non-adjacent elements in the array. The function should return 0 if the array is empty or contains only negative numbers." }, { "from": "gpt", "value": "You can solve this problem ...
Write a function to find the smallest missing positive integer from a given list of integers.
Here is the code to solve this problem: ```python def smallest_missing_positive(nums): n = len(nums) for i in range(n): while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]: nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] for i in range(n): if nums[i] != i + 1: ...
[ "assert smallest_missing_positive([1, 2, 0]) == 3", "assert smallest_missing_positive([7, 8, 9, 11, 12]) == 1", "assert smallest_missing_positive([3, 4, -1, 1]) == 2", "assert smallest_missing_positive([1, 2, 3]) == 4" ]
To find the smallest missing positive integer from a list of integers, we can utilize an efficient algorithm that operates in O(n) time complexity and O(1) space complexity (excluding the input list). This method involves modifying the list in place to index the integers. Here's the step-by-step approach: 1. **Ignore...
1,259
[ { "from": "human", "value": "Write a function to find the smallest missing positive integer from a given list of integers." }, { "from": "gpt", "value": "To find the smallest missing positive integer from a list of integers, we can utilize an efficient algorithm that operates in O(n) time comple...
Write a function to find the number of occurrences of an element in a list.
Here is the code to solve this problem: ```python def count_occurrences(lst, element): return lst.count(element) ```
[ "assert count_occurrences(['apple', 'banana', 'apple', 'orange'], 'apple') == 2", "assert count_occurrences([True, False, True, True], True) == 3", "assert count_occurrences([1, 2, 3, 2, 4, 2], 2) == 3" ]
You can create a function in Python to find the number of occurrences of a specific element in a list using the `count` method or by iterating through the list. Below are two examples of such functions. ### Example 1: Using the `count` method ```python def count_occurrences(lst, element): return lst.count(element...
1,260
[ { "from": "human", "value": "Write a function to find the number of occurrences of an element in a list." }, { "from": "gpt", "value": "You can create a function in Python to find the number of occurrences of a specific element in a list using the `count` method or by iterating through the list....
Write a function to check if two strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Here is the code to solve this problem: ```python def is_anagram(str1, str2): str1 = str1.replace(' ','').lower() str2 = str2.replace(' ','').lower() if len(str1) != len(str2): return False count = {} for letter in str1: if letter in count: count[letter] +...
[ "assert is_anagram(\"listen\", \"silent\") == True", "assert is_anagram(\"debit card\", \"bad credit\") == True", "assert is_anagram(\"hello\", \"world\") == False" ]
You can determine if two strings are anagrams by checking if they contain the same characters in the same frequencies. One effective way to do this in Python is to use the `collections.Counter` from the standard library, which allows you to count the occurrences of each character in both strings and then compare the co...
1,261
[ { "from": "human", "value": "Write a function to check if two strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once." }, { "from": "gpt", "value": "You can determin...
Write a function that finds the maximum number of tasks that can be completed given the start and end times of each task. Tasks can overlap but cannot be performed simultaneously.
Here is the code to solve this problem: ```python def max_tasks(tasks): tasks.sort(key=lambda x: x[1]) count, end = 0, -1 for task in tasks: if task[0] >= end: count += 1 end = task[1] return count ```
[ "assert max_tasks([(0, 1), (1, 3), (2, 4)]) == 2", "assert max_tasks([(0, 1), (0, 2), (1, 3), (1, 4)]) == 2", "assert max_tasks([(0, 1), (1, 3), (2, 4), (3, 6)]) == 3" ]
To solve the problem of finding the maximum number of tasks that can be completed given their start and end times, we can use a greedy algorithm approach. The basic idea is to always choose the task that finishes the earliest among those that are available. This way, we leave as much room as possible for subsequent tas...
1,262
[ { "from": "human", "value": "Write a function that finds the maximum number of tasks that can be completed given the start and end times of each task. Tasks can overlap but cannot be performed simultaneously." }, { "from": "gpt", "value": "To solve the problem of finding the maximum number of ta...
Write a function to find the length of the longest strictly increasing subsequence in a given list of integers.
Here is the code to solve this problem: ```python def longest_increasing_subsequence(nums): if not nums: return 0 dp = [1] * len(nums) for i in range(len(nums)): for j in range(i): if nums[i] > nums[j]: dp[i] = max(dp[i], dp[j] + 1) return max(dp) ```
[ "assert longest_increasing_subsequence([0, 1, 0, 3, 2, 3]) == 4", "assert longest_increasing_subsequence([10, 9, 2, 5, 3, 7, 101, 18]) == 4", "assert longest_increasing_subsequence([7, 7, 7, 7, 7, 7, 7]) == 1" ]
You can find the length of the longest strictly increasing subsequence (LIS) in a list of integers using dynamic programming. Here's a Python function that implements this algorithm: ```python def longest_increasing_subsequence(nums): if not nums: return 0 n = len(nums) dp = [1] * n # Initial...
1,263
[ { "from": "human", "value": "Write a function to find the length of the longest strictly increasing subsequence in a given list of integers." }, { "from": "gpt", "value": "You can find the length of the longest strictly increasing subsequence (LIS) in a list of integers using dynamic programming...
Write a function to transform a given list of numbers into a dictionary where keys are the index of the elements and values are the elements themselves.
Here is the code to solve this problem: ```python def indexify(arr): return {i: v for i, v in enumerate(arr)} ```
[ "assert indexify([1, 2, 3, 4, 5]) == {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}", "assert indexify([10, 20, 30, 40, 50]) == {0: 10, 1: 20, 2: 30, 3: 40, 4: 50}", "assert indexify([100, 200, 300, 400, 500]) == {0: 100, 1: 200, 2: 300, 3: 400, 4: 500}" ]
You can create a function in Python to transform a list of numbers into a dictionary where the keys are the indices of the elements and the values are the elements themselves. Here’s a simple implementation of such a function: ```python def list_to_dict(numbers): return {index: value for index, value in enumerate(...
1,264
[ { "from": "human", "value": "Write a function to transform a given list of numbers into a dictionary where keys are the index of the elements and values are the elements themselves." }, { "from": "gpt", "value": "You can create a function in Python to transform a list of numbers into a dictionar...
Write a python function to find two numbers such that they add up to a specific target number. The function should return the indices of the two numbers (1-indexed) in the form of a list of length 2. You may assume that each input would have exactly one solution, and you may not use the same element twice.
Here is the code to solve this problem: ```python def twoSum(nums, target): num_dict = {} for i, num in enumerate(nums): complement = target - num if complement in num_dict: return [num_dict[complement] + 1, i + 1] num_dict[num] = i return [] ```
[ "assert twoSum([2,7,11,15],9) == [1,2]", "assert twoSum([3,2,4],6) == [2,3]", "assert twoSum([3,3],6) == [1,2]" ]
You can use a dictionary to store the indices of the numbers you've seen so far. As you iterate through the list, you can check if the complement (i.e., `target - current_number`) exists in the dictionary. If it does, you have found the two numbers that add up to the target. Here's a Python function implementing this l...
1,265
[ { "from": "human", "value": "Write a python function to find two numbers such that they add up to a specific target number. The function should return the indices of the two numbers (1-indexed) in the form of a list of length 2. You may assume that each input would have exactly one solution, and you may not...
Write a python function to find the minimum number of jumps required to reach the end of an array from the first element. Each element in the array represents the maximum jump length at that position.
Here is the code to solve this problem: ```python def min_jumps(nums): if len(nums) == 1: return 0 curReach, maxReach, step = 0, 0, 0 for i, n in enumerate(nums[:-1]): maxReach = max(maxReach, i+n) if i == curReach: step += 1 curReach = maxReach return step ```
[ "assert min_jumps([10,9,8,7,6,5,4,3,2,1,0]) == 1", "assert min_jumps([2,3,1,1,4]) == 2", "assert min_jumps([1,1,1,1,1]) == 4" ]
To solve the problem of finding the minimum number of jumps required to reach the end of an array where each element represents the maximum jump length at that position, we can use a greedy approach. Here's a Python function that implements this algorithm: ```python def min_jumps(arr): if not arr or len(arr) == ...
1,266
[ { "from": "human", "value": "Write a python function to find the minimum number of jumps required to reach the end of an array from the first element. Each element in the array represents the maximum jump length at that position." }, { "from": "gpt", "value": "To solve the problem of finding the...
Write a function to find the maximum number in a list of integers.
Here is the code to solve this problem: ```python def max_num(lst): max_num = lst[0] for num in lst: if num > max_num: max_num = num return max_num ```
[ "assert max_num([1, 2, 3, 4, 5]) == 5", "assert max_num([10, 20, 30, 40, 50]) == 50", "assert max_num([-1, -2, -3, -4, -5]) == -1" ]
Certainly! You can find the maximum number in a list of integers using a simple function in Python. Here’s an example of how you can implement this: ```python def find_maximum(numbers): if not numbers: raise ValueError("The list is empty.") max_num = numbers[0] # Start by assuming the first n...
1,267
[ { "from": "human", "value": "Write a function to find the maximum number in a list of integers." }, { "from": "gpt", "value": "Certainly! You can find the maximum number in a list of integers using a simple function in Python. Here’s an example of how you can implement this:\n\n```python\ndef fi...
Write a function to find the first missing positive integer in an unsorted array of integers.
Here is the code to solve this problem: ```python def first_missing_positive(nums): if not nums: return 1 for i in range(len(nums)): while 1 <= nums[i] <= len(nums) and nums[nums[i] - 1] != nums[i]: nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1] for i in range(len(nums)): ...
[ "assert first_missing_positive([-1, -2, -3])==1", "assert first_missing_positive([1, 2, 0])==3", "assert first_missing_positive([3, 4, -1, 1])==2" ]
You can find the first missing positive integer in an unsorted array using an efficient algorithm with a time complexity of O(n) and a space complexity of O(1). The approach involves placing each number in its correct position in the array and then checking for the first missing positive. Here’s a Python function to a...
1,268
[ { "from": "human", "value": "Write a function to find the first missing positive integer in an unsorted array of integers." }, { "from": "gpt", "value": "You can find the first missing positive integer in an unsorted array using an efficient algorithm with a time complexity of O(n) and a space c...
Write a function that takes a list of strings as input and returns a dictionary where the keys are the strings from the input list and the values are the lengths of these strings.
Here is the code to solve this problem: ```python def string_lengths(lst): return {word: len(word) for word in lst} ```
[ "assert string_lengths([\"dog\", \"cat\", \"elephant\"]) == {\"dog\": 3, \"cat\": 3, \"elephant\": 8}", "assert string_lengths([\"hello\", \"world\"]) == {\"hello\": 5, \"world\": 5}", "assert string_lengths([\"apple\", \"banana\", \"cherry\"]) == {\"apple\": 5, \"banana\": 6, \"cherry\": 6}" ]
You can create a function in Python that achieves this by iterating through the list of strings and using a dictionary comprehension to map each string to its length. Here’s how you can implement this: ```python def string_lengths(strings): return {s: len(s) for s in strings} # Example usage: input_list = ["apple...
1,269
[ { "from": "human", "value": "Write a function that takes a list of strings as input and returns a dictionary where the keys are the strings from the input list and the values are the lengths of these strings." }, { "from": "gpt", "value": "You can create a function in Python that achieves this b...
Write a function to merge multiple dictionaries by adding the values of common keys.
Here is the code to solve this problem: ```python from collections import Counter def merge_dicts(*dicts): merged_dict = Counter() for dictionary in dicts: merged_dict.update(dictionary) return dict(merged_dict) ```
[ "assert merge_dicts({\"a\": 1, \"b\": 2, \"c\": 3}, {\"a\": 4, \"b\": 5, \"d\": 6}, {\"a\": 7, \"c\": 8, \"e\": 9})=={\"a\": 12, \"b\": 7, \"c\": 11, \"d\": 6, \"e\": 9}", "assert merge_dicts({\"x\": 10, \"y\": 20}, {\"x\": 30, \"z\": 40}, {\"x\": 50, \"y\": 60, \"z\": 70})=={\"x\": 90, \"y\": 80, \"z\": 110}", ...
You can create a function that merges multiple dictionaries by summing the values of common keys. Below is a Python implementation of such a function: ```python def merge_dictionaries(*dicts): merged_dict = {} for d in dicts: for key, value in d.items(): if key in merged_dict: ...
1,270
[ { "from": "human", "value": "Write a function to merge multiple dictionaries by adding the values of common keys." }, { "from": "gpt", "value": "You can create a function that merges multiple dictionaries by summing the values of common keys. Below is a Python implementation of such a function:\...
Write a python function to find the mode(s) in a binary search tree.
Here is the code to solve this problem: ```python from collections import defaultdict class Node: def __init__(self, data): self.data = data self.left = None self.right = None def insert(node, data): if node is None: return Node(data) else: if data <= node.data: ...
[ "assert find_modes(root1) == [5]", "assert find_modes(root) == [2, 3]", "assert find_modes(root2) == [4, 5]" ]
To find the mode(s) in a binary search tree (BST), we can perform an in-order traversal of the tree, which will yield values in sorted order. During the traversal, we can keep track of the frequency of each value and determine which value(s) occur most frequently. Below is a Python function that achieves this. We'll d...
1,271
[ { "from": "human", "value": "Write a python function to find the mode(s) in a binary search tree." }, { "from": "gpt", "value": "To find the mode(s) in a binary search tree (BST), we can perform an in-order traversal of the tree, which will yield values in sorted order. During the traversal, we ...
Write a python function to check if a given string is a palindrome. A string is a palindrome if it reads the same backward as forward.
Here is the code to solve this problem: ```python def is_string_palindrome(s): return s == s[::-1] ```
[ "assert is_string_palindrome('python') == False", "assert is_string_palindrome('radar') == True", "assert is_string_palindrome('racecar') == True", "assert is_string_palindrome('') == True" ]
Certainly! Here is a Python function that checks if a given string is a palindrome: ```python def is_palindrome(s): # Normalize the string: remove spaces and convert to lowercase normalized_str = ''.join(s.lower().split()) # Check if the normalized string is the same as its reverse return normaliz...
1,272
[ { "from": "human", "value": "Write a python function to check if a given string is a palindrome. A string is a palindrome if it reads the same backward as forward." }, { "from": "gpt", "value": "Certainly! Here is a Python function that checks if a given string is a palindrome:\n\n```python\ndef...
Write a function that calculates the sum of squares of all the elements in a given list.
Here is the code to solve this problem: ```python def sum_of_squares(lst): """ Calculate the sum of squares of all the elements in a given list. :param lst: A list of numbers :return: The sum of squares of all the numbers in the list """ return sum(x ** 2 for x in lst) ```
[ "assert sum_of_squares([1, 2, 3, 4, 5]) == 55", "assert sum_of_squares([0, 0, 0, 0]) == 0", "assert sum_of_squares([-1, -2, -3, -4, -5]) == 55" ]
Sure! Below is a Python function that calculates the sum of squares of all the elements in a given list: ```python def sum_of_squares(numbers): """Calculate the sum of squares of all elements in the list.""" return sum(x ** 2 for x in numbers) # Example usage: example_list = [1, 2, 3, 4] result = sum_of_squar...
1,273
[ { "from": "human", "value": "Write a function that calculates the sum of squares of all the elements in a given list." }, { "from": "gpt", "value": "Sure! Below is a Python function that calculates the sum of squares of all the elements in a given list:\n\n```python\ndef sum_of_squares(numbers):...
Write a python function `find_peak_element` that takes a list of integers as input and returns the index of a peak element. A peak element is an element that is greater than its neighbors. Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. The array may contain multiple peak...
Here is the code to solve this problem: ```python def find_peak_element(nums): if not nums: return None left, right = 0, len(nums) - 1 while left < right: mid = (left + right) // 2 if nums[mid] > nums[mid + 1]: right = mid else: left = mid + 1 ret...
[ "assert find_peak_element([6, 1, 2, 3, 4, 5]) == 5", "assert find_peak_element([1, 2, 3, 1]) == 2", "assert find_peak_element([1, 2, 1, 3, 5, 6, 4]) == 5 or find_peak_element([1, 2, 1, 3, 5, 6, 4]) == 1" ]
You can find a peak element in a list of integers using a binary search approach, which is efficient and has a time complexity of O(log n). Here's a Python function `find_peak_element` that implements this logic: ```python def find_peak_element(nums): left, right = 0, len(nums) - 1 while left < right: ...
1,274
[ { "from": "human", "value": "Write a python function `find_peak_element` that takes a list of integers as input and returns the index of a peak element. A peak element is an element that is greater than its neighbors. Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its i...
Write a python function to find the first non-repeating character in a given string.
Here is the code to solve this problem: ```python def first_non_repeating_char(str1): dict = {} for i in str1: if i in dict: dict[i] += 1 else: dict[i] = 1 for i in str1: if dict[i] == 1: return i ```
[ "assert first_non_repeating_char(\"data\") == \"d\"", "assert first_non_repeating_char(\"brilliant girl\") == \"b\"", "assert first_non_repeating_char(\"create\") == \"c\"" ]
Certainly! You can write a Python function to find the first non-repeating character in a string using a simple algorithm. Below is an implementation of such a function: ```python def first_non_repeating_character(s): # Create a dictionary to count occurrences of each character char_count = {} # Count occ...
1,275
[ { "from": "human", "value": "Write a python function to find the first non-repeating character in a given string." }, { "from": "gpt", "value": "Certainly! You can write a Python function to find the first non-repeating character in a string using a simple algorithm. Below is an implementation o...
Write a function to find all the prime numbers less than or equal to a given integer n using the Sieve of Eratosthenes algorithm.
Here is the code to solve this problem: ```python def sieve_of_eratosthenes(n): sieve = [True] * (n+1) sieve[0:2] = [False, False] for current in range(2, int(n**0.5) + 1): if sieve[current]: for multiple in range(current*current, n + 1, current): sieve[multiple] = False...
[ "assert sieve_of_eratosthenes(5) == [2, 3, 5]", "assert sieve_of_eratosthenes(10) == [2, 3, 5, 7]", "assert sieve_of_eratosthenes(30) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]" ]
Certainly! The Sieve of Eratosthenes is an efficient algorithm for finding all prime numbers up to a specified integer \( n \). Below is a Python function that implements this algorithm: ```python def sieve_of_eratosthenes(n): if n < 2: return [] # Step 1: Initialize a list of boolean values is_pr...
1,276
[ { "from": "human", "value": "Write a function to find all the prime numbers less than or equal to a given integer n using the Sieve of Eratosthenes algorithm." }, { "from": "gpt", "value": "Certainly! The Sieve of Eratosthenes is an efficient algorithm for finding all prime numbers up to a speci...
Write a python function to find the maximum number of non-overlapping intervals that can be scheduled in a room. Given a list of intervals, where each interval is represented as a tuple (start, end), the function should return the maximum number of non-overlapping intervals.
Here is the code to solve this problem: ```python def max_non_overlapping_intervals(intervals): if not intervals: return 0 intervals.sort(key=lambda x: x[1]) # Sort intervals based on end time count = 1 # Count of non-overlapping intervals end_time = intervals[0][1] for i in range(1, l...
[ "assert max_non_overlapping_intervals([(1, 2), (2, 3), (3, 4)]) == 3", "assert max_non_overlapping_intervals([(1, 2), (2, 3), (1, 3)]) == 2", "assert max_non_overlapping_intervals([(1, 2), (1, 2), (1, 2)]) == 1" ]
To solve the problem of finding the maximum number of non-overlapping intervals that can be scheduled in a room, we can use a greedy algorithm. The main idea is to always choose the interval that ends the earliest and can be scheduled after the last selected interval. Here's a step-by-step outline of the approach: 1....
1,277
[ { "from": "human", "value": "Write a python function to find the maximum number of non-overlapping intervals that can be scheduled in a room. Given a list of intervals, where each interval is represented as a tuple (start, end), the function should return the maximum number of non-overlapping intervals." ...
Write a function to calculate the number of valid parentheses combinations for a given number of pairs.
Here is the code to solve this problem: ```python def valid_parentheses(n): if n == 0: return 1 if n == 1: return 1 result = 0 for i in range(n): result += valid_parentheses(i) * valid_parentheses(n - 1 - i) return result ```
[ "assert valid_parentheses(4) == 14", "assert valid_parentheses(3) == 5", "assert valid_parentheses(5) == 42" ]
To calculate the number of valid combinations of parentheses for a given number of pairs, you can use the concept of Catalan numbers. The nth Catalan number can be calculated using the following formula: \[ C(n) = \frac{1}{n+1} \binom{2n}{n} = \frac{(2n)!}{(n+1)!n!} \] Alternatively, you can use dynamic programming t...
1,278
[ { "from": "human", "value": "Write a function to calculate the number of valid parentheses combinations for a given number of pairs." }, { "from": "gpt", "value": "To calculate the number of valid combinations of parentheses for a given number of pairs, you can use the concept of Catalan numbers...
Write a python function to find the nth Fibonacci number using a recursive approach.
Here is the code to solve this problem: ```python def fib(n): if n <= 1: return n else: return(fib(n-1) + fib(n-2)) ```
[ "assert fib(1) == 1", "assert fib(0) == 0", "assert fib(10) == 55", "assert fib(15) == 610" ]
Certainly! The Fibonacci sequence is defined as follows: - \( F(0) = 0 \) - \( F(1) = 1 \) - \( F(n) = F(n-1) + F(n-2) \) for \( n \geq 2 \) Here’s a Python function that uses a recursive approach to find the nth Fibonacci number: ```python def fibonacci(n): if n < 0: raise ValueError("Input should be a...
1,279
[ { "from": "human", "value": "Write a python function to find the nth Fibonacci number using a recursive approach." }, { "from": "gpt", "value": "Certainly! The Fibonacci sequence is defined as follows: \n\n- \\( F(0) = 0 \\)\n- \\( F(1) = 1 \\)\n- \\( F(n) = F(n-1) + F(n-2) \\) for \\( n \\geq 2...
Write a function to find the minimum number of jumps required to reach the end of the given array from the first element. Starting from the first element, you can jump according to the value at the current position in the array. The goal is to reach the last index in the minimum number of jumps.
Here is the code to solve this problem: ```python def min_jumps(arr): if len(arr) <= 1: return 0 if arr[0] == 0: return -1 max_reach = arr[0] step = arr[0] jump = 1 for i in range(1, len(arr)): if i == len(arr) - 1: return jump max_reach = max(max_...
[ "assert min_jumps([0, 2, 3]) == -1", "assert min_jumps([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) == 1", "assert min_jumps([2, 3, 1, 1, 4]) == 2" ]
You can solve the problem of finding the minimum number of jumps required to reach the last index of an array using a greedy approach. The idea is to keep track of the maximum reachable index at each step and to increment the jump count whenever you reach the end of the current jump range. Here's a Python function tha...
1,280
[ { "from": "human", "value": "Write a function to find the minimum number of jumps required to reach the end of the given array from the first element. Starting from the first element, you can jump according to the value at the current position in the array. The goal is to reach the last index in the minimum...
Write a python function to find the kth smallest element in a given unsorted array using QuickSelect algorithm.
Here is the code to solve this problem: ```python def partition(arr, low, high): i = (low-1) pivot = arr[high] for j in range(low, high): if arr[j] <= pivot: i = i+1 arr[i], arr[j] = arr[j], arr[i] arr[i+1], arr[high] = arr[high], arr[i+1] return (i+1) def quicks...
[ "assert find_kth_smallest([7, 10, 4, 3, 20, 15], 4) == 10", "assert find_kth_smallest([7, 10, 4, 3, 20, 15], 3) == 7", "assert find_kth_smallest([12, 3, 5, 7, 19], 2) == 5" ]
Certainly! The QuickSelect algorithm is an efficient way to find the k-th smallest element in an unsorted array. It is related to the QuickSort sorting algorithm and follows a similar partitioning approach. Here's a Python function that implements the QuickSelect algorithm to find the k-th smallest element: ```python...
1,281
[ { "from": "human", "value": "Write a python function to find the kth smallest element in a given unsorted array using QuickSelect algorithm." }, { "from": "gpt", "value": "Certainly! The QuickSelect algorithm is an efficient way to find the k-th smallest element in an unsorted array. It is relat...
Write a function that takes an integer n and returns a list of all possible unique binary strings of length n.
Here is the code to solve this problem: ```python def generate_binary_strings(n): if n == 0: return [""] sub_list = generate_binary_strings(n-1) return ['0'+s for s in sub_list] + ['1'+s for s in sub_list] ```
[ "assert generate_binary_strings(3) == ['000', '001', '010', '011', '100', '101', '110', '111']", "assert generate_binary_strings(1) == ['0', '1']", "assert generate_binary_strings(2) == ['00', '01', '10', '11']" ]
Certainly! Below is a Python function that generates all possible unique binary strings of a given length `n`. The function uses a recursive approach to build the binary strings. ```python def generate_binary_strings(n): def backtrack(current_string): # Base case: if the current string's length is equal to...
1,282
[ { "from": "human", "value": "Write a function that takes an integer n and returns a list of all possible unique binary strings of length n." }, { "from": "gpt", "value": "Certainly! Below is a Python function that generates all possible unique binary strings of a given length `n`. The function u...
Write a function that finds the number of ways to represent a given number as a sum of 3 positive integers, considering the order as significant. For example, if the target number is 4, the possible representations are: (1, 1, 2), (1, 2, 1), (2, 1, 1), (1, 3, 0), (3, 1, 0), (0, 1, 3), (0, 3, 1), (2, 2, 0), (2, 0, 2), (...
Here is the code to solve this problem: ```python def sum_of_three(n): count = 0 for i in range(1, n): for j in range(1, n): for k in range(1, n): if i + j + k == n: count += 1 return count ```
[ "assert sum_of_three(5) == 6", "assert sum_of_three(4) == 3", "assert sum_of_three(6) == 10" ]
To compute the number of ways to represent a given number \( n \) as a sum of 3 positive integers while considering the order of summands, we can use a combinatorial approach. When we say we want to find the number of ways to write \( n \) as the sum of three positive integers \( x_1, x_2, \) and \( x_3 \), we can tra...
1,283
[ { "from": "human", "value": "Write a function that finds the number of ways to represent a given number as a sum of 3 positive integers, considering the order as significant. For example, if the target number is 4, the possible representations are: (1, 1, 2), (1, 2, 1), (2, 1, 1), (1, 3, 0), (3, 1, 0), (0, ...
Write a function to find the smallest missing positive integer from a given unsorted array of integers.
Here is the code to solve this problem: ```python def smallest_missing_positive(nums): n = len(nums) for i in range(n): while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]: nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] for i in range(n): if nums[i] != i + 1: ...
[ "assert smallest_missing_positive([1, 2, 0]) == 3", "assert smallest_missing_positive([3, 4, -1, 1]) == 2", "assert smallest_missing_positive([7, 8, 9, 11, 12]) == 1" ]
To find the smallest missing positive integer from an unsorted array of integers, we can use an efficient algorithm that operates in linear time, O(n), and uses constant space, O(1). This method involves rearranging the array elements so that each positive integer `n` is placed at index `n-1` (if it's within the bounds...
1,284
[ { "from": "human", "value": "Write a function to find the smallest missing positive integer from a given unsorted array of integers." }, { "from": "gpt", "value": "To find the smallest missing positive integer from an unsorted array of integers, we can use an efficient algorithm that operates in...
Write a python function to find the mode of a list of numbers.
Here is the code to solve this problem: ```python from collections import Counter def mode(lst): count = Counter(lst) max_count = max(list(count.values())) mode_val = [num for num, freq in count.items() if freq == max_count] return mode_val[0] if len(mode_val) == 1 else mode_val ```
[ "assert mode([1, 2, 3, 2, 4, 5, 2]) == 2", "assert mode([1, 1, 2, 3, 3, 3, 4, 4, 4, 4]) == 4", "assert mode([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]" ]
To find the mode of a list of numbers in Python, we can use the `collections.Counter` class, which makes it easy to count the occurrences of each number. Here’s a function that will return the mode(s) of the list: ```python from collections import Counter def find_mode(numbers): if not numbers: return Non...
1,285
[ { "from": "human", "value": "Write a python function to find the mode of a list of numbers." }, { "from": "gpt", "value": "To find the mode of a list of numbers in Python, we can use the `collections.Counter` class, which makes it easy to count the occurrences of each number. Here’s a function t...
Write a function that returns the number of vowels in a given string. The function should ignore case sensitivity.
Here is the code to solve this problem: ```python def count_vowels(text): vowels = "aeiou" count = 0 for char in text.lower(): if char in vowels: count += 1 return count ```
[ "assert count_vowels(\"Python Programming\") == 4", "assert count_vowels(\"Hello World\") == 3", "assert count_vowels(\"AEIOU\") == 5" ]
You can create a function in Python that counts the number of vowels in a given string while ignoring case sensitivity. Here's a simple implementation of such a function: ```python def count_vowels(input_string): # Define the set of vowels vowels = "aeiouAEIOU" # Initialize a counter for vowels co...
1,286
[ { "from": "human", "value": "Write a function that returns the number of vowels in a given string. The function should ignore case sensitivity." }, { "from": "gpt", "value": "You can create a function in Python that counts the number of vowels in a given string while ignoring case sensitivity. H...
Write a python function to find the sum of the digits of a given number.
Here is the code to solve this problem: ```python def sum_of_digits(number): sum_digits = 0 for digit in str(number): sum_digits += int(digit) return sum_digits ```
[ "assert sum_of_digits(9999) == 36", "assert sum_of_digits(1234) == 10", "assert sum_of_digits(5678) == 26" ]
Certainly! You can create a Python function to find the sum of the digits of a given number by converting the number to a string, iterating over each character, converting them back to integers, and then summing them up. Here's how you can do it: ```python def sum_of_digits(n): # Convert the number to a string to ...
1,287
[ { "from": "human", "value": "Write a python function to find the sum of the digits of a given number." }, { "from": "gpt", "value": "Certainly! You can create a Python function to find the sum of the digits of a given number by converting the number to a string, iterating over each character, co...
Write a python function to find the minimum number of swaps required to sort an array.
Here is the code to solve this problem: ```python def min_swaps(arr): n = len(arr) arr_pos =[*enumerate(arr)] arr_pos.sort(key = lambda it:it[1]) vis = {k:False for k in range(n)} ans = 0 for i in range(n): if vis[i] or arr_pos[i][0] == i: continue cycle_size = 0 ...
[ "assert min_swaps([1,3,5,2,4,6,7]) == 3", "assert min_swaps([10,19,6,3,5]) == 2", "assert min_swaps([7,6,5,8]) == 1" ]
To find the minimum number of swaps required to sort an array, you can use the concept of graph cycles. Each element of the array can be considered as a vertex in a graph, and the position it should go to can be considered as the directed edge from the current index to the index of its sorted position. Here's how you...
1,288
[ { "from": "human", "value": "Write a python function to find the minimum number of swaps required to sort an array." }, { "from": "gpt", "value": "To find the minimum number of swaps required to sort an array, you can use the concept of graph cycles. Each element of the array can be considered a...
Write a function to convert a decimal number to a binary string. The function should return the binary string without any leading zeros.
Here is the code to solve this problem: ```python def decimal_to_binary(n): if n == 0: return "0" binary = "" while n > 0: binary = str(n % 2) + binary n = n // 2 return binary ```
[ "assert decimal_to_binary(0) == \"0\"", "assert decimal_to_binary(255) == \"11111111\"", "assert decimal_to_binary(10) == \"1010\"" ]
You can create a function in Python to convert a decimal number to a binary string without leading zeros. Here’s a simple implementation: ```python def decimal_to_binary(n): if n == 0: return "0" binary_str = "" while n > 0: binary_str = str(n % 2) + binary_str n //= 2 return bi...
1,289
[ { "from": "human", "value": "Write a function to convert a decimal number to a binary string. The function should return the binary string without any leading zeros." }, { "from": "gpt", "value": "You can create a function in Python to convert a decimal number to a binary string without leading ...
Write a python function to find the Greatest Common Divisor (GCD) of two numbers using Euclidean algorithm.
Here is the code to solve this problem: ```python def find_gcd(x, y): while(y): x, y = y, x % y return x ```
[ "assert find_gcd(12, 16) == 4", "assert find_gcd(7, 3) == 1", "assert find_gcd(100, 85) == 5" ]
Certainly! The Euclidean algorithm is an efficient way to compute the Greatest Common Divisor (GCD) of two integers. Here is a Python function that implements the Euclidean algorithm to find the GCD of two numbers: ```python def gcd(a, b): """Return the Greatest Common Divisor (GCD) of two numbers using the Euclid...
1,290
[ { "from": "human", "value": "Write a python function to find the Greatest Common Divisor (GCD) of two numbers using Euclidean algorithm." }, { "from": "gpt", "value": "Certainly! The Euclidean algorithm is an efficient way to compute the Greatest Common Divisor (GCD) of two integers. Here is a P...
Write a python function to find the largest number in a list of integers that does not exceed a given threshold. If no such number exists, return None.
Here is the code to solve this problem: ```python def find_largest_within_threshold(nums, threshold): max_within_threshold = None for num in nums: if num <= threshold: if max_within_threshold is None or num > max_within_threshold: max_within_threshold = num return max_wi...
[ "assert find_largest_within_threshold([1, 5, 3, 10, 4], 5) == 5", "assert find_largest_within_threshold([10, 20, 30], 50) == 30", "assert find_largest_within_threshold([], 100) == None", "assert find_largest_within_threshold([10, 20, 30], 5) == None" ]
Certainly! Below is a Python function that takes a list of integers and a threshold value, and returns the largest integer from the list that does not exceed the threshold. If no such integer exists, the function will return `None`. ```python def largest_below_threshold(numbers, threshold): largest = None for ...
1,291
[ { "from": "human", "value": "Write a python function to find the largest number in a list of integers that does not exceed a given threshold. If no such number exists, return None." }, { "from": "gpt", "value": "Certainly! Below is a Python function that takes a list of integers and a threshold ...
Write a python function to find the maximum product of three numbers in a list.
Here is the code to solve this problem: ```python def max_product_three(nums): nums.sort() return max(nums[0] * nums[1] * nums[-1], nums[-1] * nums[-2] * nums[-3]) if len(nums) >= 3 else None ```
[ "assert max_product_three([1, 10, 2, 6, 5, 3]) == 300", "assert max_product_three([-10, -10, 5, 2]) == 500", "assert max_product_three([1, 2]) == None" ]
To find the maximum product of three numbers in a list, you can follow these steps: 1. Sort the list. 2. The maximum product of three numbers can be obtained either from the product of the three largest numbers or from the product of the two smallest numbers (which can be negative) and the largest number. Here's a Py...
1,292
[ { "from": "human", "value": "Write a python function to find the maximum product of three numbers in a list." }, { "from": "gpt", "value": "To find the maximum product of three numbers in a list, you can follow these steps:\n\n1. Sort the list.\n2. The maximum product of three numbers can be obt...
Write a python function that takes a list of strings as input and returns a new list with the strings in reverse order.
Here is the code to solve this problem: ```python def reverse_strings(strings): return strings[::-1] ```
[ "assert reverse_strings([\"hello\", \"world\", \"!\"]) == [\"!\", \"world\", \"hello\"]", "assert reverse_strings([\"python\", \"is\", \"awesome\"]) == [\"awesome\", \"is\", \"python\"]", "assert reverse_strings([]) == []" ]
Certainly! You can create a Python function that takes a list of strings and returns a new list with the strings in reverse order. Here's a simple implementation: ```python def reverse_strings(input_list): return input_list[::-1] # Example usage: strings = ["apple", "banana", "cherry"] reversed_strings = reverse_...
1,293
[ { "from": "human", "value": "Write a python function that takes a list of strings as input and returns a new list with the strings in reverse order." }, { "from": "gpt", "value": "Certainly! You can create a Python function that takes a list of strings and returns a new list with the strings in ...
Write a python function to check if a given string is an anagram of another string. An anagram is a word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman.
Here is the code to solve this problem: ```python def is_anagram(str1,str2): if(sorted(str1)== sorted(str2)): return True else: return False ```
[ "assert is_anagram('listen','silent') == True", "assert is_anagram('triangle','integral') == True", "assert is_anagram('cinema','iceman') == True", "assert is_anagram('apple','peach') == False" ]
You can create a Python function to check if two given strings are anagrams of each other by following these steps: 1. Normalize the strings by removing spaces and converting them to lowercase. 2. Count the occurrences of each character in both strings. 3. Compare the two counts. Here's one way to implement this: ``...
1,294
[ { "from": "human", "value": "Write a python function to check if a given string is an anagram of another string. An anagram is a word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman." }, { "from": "gpt", "value": "You can create a Python function...
Write a Python function to find the maximum and minimum element in a list of numbers using a single traversal of the list.
Here is the code to solve this problem: ```python def find_max_min(numbers): if not numbers: return None, None max_num = min_num = numbers[0] for num in numbers[1:]: if num > max_num: max_num = num elif num < min_num: min_num = num return max_num, min_num...
[ "assert find_max_min([1, 2, 3, 4, 5]) == (5, 1)", "assert find_max_min([5, 4, 3, 2, 1]) == (5, 1)", "assert find_max_min([10]) == (10, 10)" ]
You can find both the maximum and minimum elements in a list of numbers in a single traversal by iterating through the list once and updating the maximum and minimum values as you go. Here’s a Python function that does just that: ```python def find_max_min(numbers): if not numbers: raise ValueError("The li...
1,295
[ { "from": "human", "value": "Write a Python function to find the maximum and minimum element in a list of numbers using a single traversal of the list." }, { "from": "gpt", "value": "You can find both the maximum and minimum elements in a list of numbers in a single traversal by iterating throug...
Write a function that takes a list of integers and moves all negative numbers to the beginning of the list while keeping the relative order of the non-negative numbers unchanged.
Here is the code to solve this problem: ```python def move_negatives_to_start(nums): negative_list = [] non_negative_list = [] for num in nums: if num < 0: negative_list.append(num) else: non_negative_list.append(num) return negative_list + non_negative_list ```
[ "assert move_negatives_to_start([10, 20, 30, 40, 50]) == [10, 20, 30, 40, 50]", "assert move_negatives_to_start([1, -2, 3, -4, 5]) == [-2, -4, 1, 3, 5]", "assert move_negatives_to_start([-1, -2, -3, -4, -5]) == [-1, -2, -3, -4, -5]", "assert move_negatives_to_start([-7, 0, 8, -9, 1, 2, -3]) == [-7, -9, -3, 0,...
You can accomplish this task by creating a function that iterates through the list and separates the negative numbers from the non-negative ones. After that, you can combine the two lists, with the negative numbers at the front. Here's an example of how you can implement this in Python: ```python def move_negatives_to...
1,296
[ { "from": "human", "value": "Write a function that takes a list of integers and moves all negative numbers to the beginning of the list while keeping the relative order of the non-negative numbers unchanged." }, { "from": "gpt", "value": "You can accomplish this task by creating a function that ...
Write a function to find the maximum difference between two elements in an array such that the larger element appears after the smaller element.
Here is the code to solve this problem: ```python def max_diff(arr): max_diff = 0 min_element = arr[0] for i in range(1,len(arr)): if (arr[i] - min_element) > max_diff: max_diff = arr[i] - min_element if arr[i] < min_element: min_element = arr[i] return max_diff ...
[ "assert max_diff([2, 3, 10, 6, 4, 8, 1]) == 8", "assert max_diff([7, 9, 5, 6, 3, 2]) == 2", "assert max_diff([1, 5, 2, 10]) == 9" ]
Certainly! Below is a Python function that implements the approach to find the maximum difference between two elements in an array (with the constraint that the larger element must appear after the smaller element). The approach involves iterating through the array while keeping track of the minimum element encountere...
1,297
[ { "from": "human", "value": "Write a function to find the maximum difference between two elements in an array such that the larger element appears after the smaller element." }, { "from": "gpt", "value": "Certainly! Below is a Python function that implements the approach to find the maximum diff...
Write a python function that takes a list of integers as input and returns the largest number in the list.
Here is the code to solve this problem: ```python def find_largest(list1): max_num = list1[0] for num in list1: if num > max_num: max_num = num return max_num ```
[ "assert find_largest([1, 2, 3, 4, 5]) == 5", "assert find_largest([-1, -2, -3, -4, -5]) == -1", "assert find_largest([10, 20, 30, 40, 50]) == 50" ]
Certainly! Below is a Python function that takes a list of integers as input and returns the largest number in that list: ```python def find_largest_number(numbers): """ Returns the largest number in a list of integers. Parameters: numbers (list of int): A list of integers. Returns: int: The ...
1,298
[ { "from": "human", "value": "Write a python function that takes a list of integers as input and returns the largest number in the list." }, { "from": "gpt", "value": "Certainly! Below is a Python function that takes a list of integers as input and returns the largest number in that list:\n\n```p...
Write a function to generate the nth row of Pascal's triangle.
Here is the code to solve this problem: ```python def pascal_row(n): if n==0: return [1] if n==1: return [1,1] last = [1,1] for _ in range(2, n + 1): row = [] for i in range(len(last) - 1): row.append(last[i] + last[i + 1]) row.insert(0, 1) r...
[ "assert pascal_row(0)==[1]", "assert pascal_row(5)==[1,5,10,10,5,1]", "assert pascal_row(1)==[1,1]", "assert pascal_row(3)==[1,3,3,1]" ]
To generate the nth row of Pascal's triangle, we can use a simple approach leveraging the properties of combinations. Each element in the nth row corresponds to the binomial coefficient, specifically given by \( C(n, k) = \frac{n!}{k!(n-k)!} \) for \( k = 0, 1, 2, \ldots, n \). Here’s a Python function that generates ...
1,299
[ { "from": "human", "value": "Write a function to generate the nth row of Pascal's triangle." }, { "from": "gpt", "value": "To generate the nth row of Pascal's triangle, we can use a simple approach leveraging the properties of combinations. Each element in the nth row corresponds to the binomial...