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 mode(s) in a list of numbers. The mode is the number that appears most frequently in the list. If there are multiple modes, return all of them in a list. | Here is the code to solve this problem:
```python
from collections import Counter
def find_modes(nums):
count = Counter(nums)
max_count = max(count.values())
modes = [num for num, freq in count.items() if freq == max_count]
return modes
``` | [
"assert find_modes([1, 2, 2, 3, 3, 4, 4, 5, 5]) == [2, 3, 4, 5]",
"assert find_modes([1, 1, 2, 3, 4, 4, 5, 5, 5, 5]) == [5]",
"assert find_modes([1, 2, 3, 3, 4, 4, 4, 5]) == [4]"
] | Certainly! Below is a Python function that will find the mode(s) in a list of numbers. If there are multiple modes, it will return all of them in a list. If there are no repeating numbers, it will return an empty list.
```python
def find_modes(numbers):
from collections import Counter
# Count the frequenc... | 1,900 | [
{
"from": "human",
"value": "Write a function to find the mode(s) in a list of numbers. The mode is the number that appears most frequently in the list. If there are multiple modes, return all of them in a list."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that will find ... |
Write a function to find the minimum number of operations required to convert a given source string into a target string using the following three operations: insert a character, delete a character, or replace a character. | Here is the code to solve this problem:
```python
def edit_distance(s, t):
m, n = len(s), len(t)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
... | [
"assert edit_distance(\"horse\", \"ros\") == 3",
"assert edit_distance(\"intention\", \"execution\") == 5",
"assert edit_distance(\"abc\", \"abc\") == 0"
] | You can solve the problem of converting a source string into a target string using dynamic programming. The problem is essentially to find the edit distance (Levenshtein distance) between the two strings. Below is a Python function that implements this approach:
```python
def min_edit_distance(source: str, target: str... | 1,901 | [
{
"from": "human",
"value": "Write a function to find the minimum number of operations required to convert a given source string into a target string using the following three operations: insert a character, delete a character, or replace a character."
},
{
"from": "gpt",
"value": "You can solve... |
Write a function to calculate the sum of all prime numbers up to a given limit. | Here is the code to solve this problem:
```python
def prime_sum(n):
if n < 2:
return 0
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
sum_primes = 0
... | [
"assert prime_sum(100) == 1060",
"assert prime_sum(10) == 17",
"assert prime_sum(20) == 77"
] | Certainly! Below is a Python function that calculates the sum of all prime numbers up to a given limit. We'll use the Sieve of Eratosthenes algorithm for efficient prime number generation.
```python
def sum_of_primes(limit):
if limit < 2:
return 0
# Create a boolean array "is_prime[0..limit]" and ... | 1,902 | [
{
"from": "human",
"value": "Write a function to calculate the sum of all prime numbers up to a given limit."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that calculates the sum of all prime numbers up to a given limit. We'll use the Sieve of Eratosthenes algorithm for ef... |
Write a Python function that creates a binary search tree (BST) from a given list of integers and returns the root of the tree. The function should handle duplicate values by inserting them as right children of their respective nodes. | Here is the code to solve this problem:
```python
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def create_bst(nums: List[int]) -> TreeNode:
if not nums:
return None
root = Tree... | [
"# Given a list of integers",
"",
"nums = [10, 5, 15, 3, 7, 12, 18]",
"# A binary search tree where:",
"# Left child with value 3,",
"# Left child with value 5,",
"# Expected output",
"# Left child with value 12,",
"# Right child with value 15,",
"# Root with value 10,",
"# Right... | To create a binary search tree (BST) from a given list of integers, we can define a `TreeNode` class to represent each node in the tree. Then, we can create a function that iterates through the list of integers, inserting each value into the BST while adhering to the rules of BST insertion. Specifically, duplicate valu... | 1,903 | [
{
"from": "human",
"value": "Write a Python function that creates a binary search tree (BST) from a given list of integers and returns the root of the tree. The function should handle duplicate values by inserting them as right children of their respective nodes."
},
{
"from": "gpt",
"value": "T... |
Write a function to find the maximum product of a contiguous subarray within a given one-dimensional integer array. | Here is the code to solve this problem:
```python
def max_product_subarray(nums):
if len(nums) == 1:
return nums[0]
res = -float('inf')
pos, neg = 0, 0
for n in nums:
if n >= 0:
pos, neg = max(pos*n, n), neg * n
else:
pos, neg = neg * n, min(pos*n, n)
... | [
"assert max_product_subarray([2, 3, -2, 4]) == 6",
"assert max_product_subarray([0, 2]) == 2",
"assert max_product_subarray([-2, 0, -1]) == 0"
] | To find the maximum product of a contiguous subarray within a given one-dimensional integer array, you can use a dynamic programming approach. The key idea is to keep track of the maximum and minimum products at each position, since a negative number can turn a minimum product into a maximum product when multiplied.
H... | 1,904 | [
{
"from": "human",
"value": "Write a function to find the maximum product of a contiguous subarray within a given one-dimensional integer array."
},
{
"from": "gpt",
"value": "To find the maximum product of a contiguous subarray within a given one-dimensional integer array, you can use a dynamic... |
Write a function to find the maximum product subarray in a given array. | Here is the code to solve this problem:
```python
def find_max_product(nums):
if not nums:
return 0
n = len(nums)
max_dp = [0] * n
min_dp = [0] * n
max_dp[0] = min_dp[0] = nums[0]
for i in range(1, n):
max_dp[i] = max(nums[i], max_dp[i-1] * nums[i], min_dp[i-1] * nums[i])
... | [
"assert find_max_product([2,3,-2,4]) == 6",
"assert find_max_product([-2,0,-1]) == 0",
"assert find_max_product([0,2]) == 2"
] | To find the maximum product subarray in a given array, you can use a dynamic programming approach, where you keep track of the maximum and minimum products at each position in the array. This is important because the product of two negative numbers can become positive, and therefore could lead to a larger maximum produ... | 1,905 | [
{
"from": "human",
"value": "Write a function to find the maximum product subarray in a given array."
},
{
"from": "gpt",
"value": "To find the maximum product subarray in a given array, you can use a dynamic programming approach, where you keep track of the maximum and minimum products at each ... |
Write a python function to find the maximum number of unique characters in any substring of a given string. | Here is the code to solve this problem:
```python
def max_unique_substring(s):
char_map = {}
left = 0
max_length = 0
for right in range(len(s)):
char_map[s[right]] = char_map.get(s[right], 0) + 1
while char_map[s[right]] > 1:
char_map[s[left]] -= 1
left += 1
... | [
"assert max_unique_substring(\"bbbbb\") == 1",
"assert max_unique_substring(\"pwwkew\") == 3",
"assert max_unique_substring(\"abcabcbb\") == 3"
] | You can find the maximum number of unique characters in any substring of a given string using a sliding window approach. The idea is to maintain a window that contains unique characters and expand or contract this window based on the characters we encounter.
Here's a Python function that implements this logic:
```pyt... | 1,906 | [
{
"from": "human",
"value": "Write a python function to find the maximum number of unique characters in any substring of a given string."
},
{
"from": "gpt",
"value": "You can find the maximum number of unique characters in any substring of a given string using a sliding window approach. The ide... |
Write a function that takes a list of integers and returns a new list with the integers sorted in descending order. | Here is the code to solve this problem:
```python
def sort_descending(lst):
return sorted(lst, reverse=True)
``` | [
"assert sort_descending([10, 8, 12, 5, 9]) == [12, 10, 9, 8, 5]",
"assert sort_descending([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]",
"assert sort_descending([5, 4, 3, 2, 1]) == [5, 4, 3, 2, 1]"
] | Certainly! Here's a simple function in Python that takes a list of integers and returns a new list sorted in descending order:
```python
def sort_descending(int_list):
# Sort the list in descending order
sorted_list = sorted(int_list, reverse=True)
return sorted_list
```
You can use this function like thi... | 1,907 | [
{
"from": "human",
"value": "Write a function that takes a list of integers and returns a new list with the integers sorted in descending order."
},
{
"from": "gpt",
"value": "Certainly! Here's a simple function in Python that takes a list of integers and returns a new list sorted in descending ... |
Write a function to calculate the number of trailing zeros in a given number's factorial. | Here is the code to solve this problem:
```python
def count_trailing_zeros(n):
count = 0
while n >= 5:
n //= 5
count += n
return count
``` | [
"assert count_trailing_zeros(3)==0",
"assert count_trailing_zeros(5)==1",
"assert count_trailing_zeros(10)==2",
"assert count_trailing_zeros(100)==24"
] | To calculate the number of trailing zeros in a factorial of a number, you can use the following function. The trailing zeros in \( n! \) (the factorial of \( n \)) are produced by the factors of 10 in the number. Since 10 is made up of the factors 2 and 5, and there are typically more factors of 2 than factors of 5 in ... | 1,908 | [
{
"from": "human",
"value": "Write a function to calculate the number of trailing zeros in a given number's factorial."
},
{
"from": "gpt",
"value": "To calculate the number of trailing zeros in a factorial of a number, you can use the following function. The trailing zeros in \\( n! \\) (the fa... |
Write a function that takes a list of integers and returns a new list where each element is the product of all the other elements in the original list. Do not use division in your solution. | Here is the code to solve this problem:
```python
def productArray(nums):
length = len(nums)
answer = [1] * length
left = 1
for i in range(length):
answer[i] *= left
left *= nums[i]
right = 1
for i in range(length-1, -1, -1):
answer[i] *= right
right *= nums[i]
... | [
"assert productArray([1,2,3,4]) == [24,12,8,6]",
"assert productArray([4,3,2,1]) == [6,8,12,24]",
"assert productArray([2,5,3]) == [15,6,10]"
] | You can achieve this by creating a function that calculates the product of all the elements in the list while keeping track of the products of elements that come before and after each position. Here's how you can implement this in Python:
```python
def product_of_all_except_self(nums):
length = len(nums)
# Cre... | 1,909 | [
{
"from": "human",
"value": "Write a function that takes a list of integers and returns a new list where each element is the product of all the other elements in the original list. Do not use division in your solution."
},
{
"from": "gpt",
"value": "You can achieve this by creating a function th... |
Write a python function to return the first recurring character in a given string. If there is no recurring character, return None. | Here is the code to solve this problem:
```python
def first_recurring_char(s):
seen = set()
for char in s:
if char in seen:
return char
seen.add(char)
return None
``` | [
"assert first_recurring_char('abca') == 'a'",
"assert first_recurring_char('abcdef') == None",
"assert first_recurring_char('') == None",
"assert first_recurring_char('abac') == 'a'"
] | You can implement a function to find the first recurring character in a string using a set to keep track of characters you have seen so far. Here is a simple implementation of that logic:
```python
def first_recurring_character(s):
seen = set()
for char in s:
if char in seen:
return ch... | 1,910 | [
{
"from": "human",
"value": "Write a python function to return the first recurring character in a given string. If there is no recurring character, return None."
},
{
"from": "gpt",
"value": "You can implement a function to find the first recurring character in a string using a set to keep track... |
Write a function that takes a list of integers and returns a new list with the integers in reverse order. | Here is the code to solve this problem:
```python
def reverse_list(lst):
return lst[::-1]
``` | [
"assert reverse_list([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]",
"assert reverse_list([10, 20, 30]) == [30, 20, 10]",
"assert reverse_list([1, 2, 3, 4]) == [4, 3, 2, 1]"
] | You can create a function in Python to reverse a list of integers as follows:
```python
def reverse_list(int_list):
return int_list[::-1]
# Example usage:
original_list = [1, 2, 3, 4, 5]
reversed_list = reverse_list(original_list)
print(reversed_list) # Output: [5, 4, 3, 2, 1]
```
In this function, the slicing ... | 1,911 | [
{
"from": "human",
"value": "Write a function that takes a list of integers and returns a new list with the integers in reverse order."
},
{
"from": "gpt",
"value": "You can create a function in Python to reverse a list of integers as follows:\n\n```python\ndef reverse_list(int_list):\n retur... |
Write a python function to find the next greater element for every element in the given array. If no such element exists, return -1. | Here is the code to solve this problem:
```python
def next_greater_element(arr):
result = [-1] * len(arr)
stack = []
for i in range(len(arr)):
while stack and arr[i] > arr[stack[-1]]:
idx = stack.pop()
result[idx] = arr[i]
stack.append(i)
return result
``` | [
"assert next_greater_element([13,7,6,12]) == [-1,12,12,-1]",
"assert next_greater_element([1, 2, 3, 4, 5]) == [2, 3, 4, 5, -1]",
"assert next_greater_element([4,5,2,25]) == [5,25,25,-1] "
] | You can solve the problem of finding the next greater element for each element in an array using a stack. The idea is to iterate through the array and use a stack to keep track of the elements for which we are yet to find the next greater element.
Here's a Python function that implements this approach:
```python
def ... | 1,912 | [
{
"from": "human",
"value": "Write a python function to find the next greater element for every element in the given array. If no such element exists, return -1."
},
{
"from": "gpt",
"value": "You can solve the problem of finding the next greater element for each element in an array using a stac... |
Write a function to find the minimum element in a list of numbers. | Here is the code to solve this problem:
```python
def find_min(lst):
min_element = lst[0]
for i in range(len(lst)):
if lst[i] < min_element:
min_element = lst[i]
return min_element
``` | [
"assert find_min([1, 2, 3, 4, 5]) == 1",
"assert find_min([10, 20, 30, 40, 50]) == 10",
"assert find_min([5, 4, 3, 2, 1]) == 1"
] | Certainly! Below is a simple Python function that finds the minimum element in a list of numbers.
```python
def find_minimum(numbers):
if not numbers:
raise ValueError("The list is empty.")
min_value = numbers[0] # Start by assuming the first element is the minimum
for num in numbers:
... | 1,913 | [
{
"from": "human",
"value": "Write a function to find the minimum element in a list of numbers."
},
{
"from": "gpt",
"value": "Certainly! Below is a simple Python function that finds the minimum element in a list of numbers.\n\n```python\ndef find_minimum(numbers):\n if not numbers:\n ... |
Write a python function to check if a list of numbers is strictly increasing. A list is strictly increasing if each element is greater than the preceding one. | Here is the code to solve this problem:
```python
def is_strictly_increasing(numbers):
for i in range(1, len(numbers)):
if numbers[i] <= numbers[i-1]:
return False
return True
``` | [
"assert is_strictly_increasing([1, 3, 5, 7, 9]) == True",
"assert is_strictly_increasing([1, 2, 3, 4, 5]) == True",
"assert is_strictly_increasing([10, 9, 8, 7, 6]) == False",
"assert is_strictly_increasing([1, 1, 2, 3, 4]) == False"
] | Certainly! Below is a Python function that checks if a list of numbers is strictly increasing:
```python
def is_strictly_increasing(numbers):
# Check if the list has less than 2 elements; if so, it is considered strictly increasing.
if len(numbers) < 2:
return True
# Iterate through the list a... | 1,914 | [
{
"from": "human",
"value": "Write a python function to check if a list of numbers is strictly increasing. A list is strictly increasing if each element is greater than the preceding one."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that checks if a list of numbers is str... |
Write a function that takes a string as an input and returns a dictionary where the keys are the characters in the string and the values are the number of times each character appears in the string. | Here is the code to solve this problem:
```python
def char_frequency(string):
frequency = {}
for char in string:
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
return frequency
``` | [
"assert char_frequency(\"python\") == {'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1}",
"assert char_frequency(\"aaa\") == {'a': 3}",
"assert char_frequency(\"hello\") == {'h': 1, 'e': 1, 'l': 2, 'o': 1}"
] | You can create a function in Python that counts the occurrences of each character in a string and returns a dictionary with characters as keys and their counts as values. Here’s a simple implementation:
```python
def count_characters(input_string):
char_count = {}
for char in input_string:
if char in c... | 1,915 | [
{
"from": "human",
"value": "Write a function that takes a string as an input and returns a dictionary where the keys are the characters in the string and the values are the number of times each character appears in the string."
},
{
"from": "gpt",
"value": "You can create a function in Python t... |
Write a function to calculate the average of all elements in a list. | Here is the code to solve this problem:
```python
def average_list(lst):
return sum(lst) / len(lst)
``` | [
"assert average_list([10, 20, 30, 40, 50])==30.0",
"assert average_list([100, 200, 300, 400, 500])==300.0",
"assert average_list([1, 2, 3, 4, 5])==3.0"
] | You can calculate the average of all elements in a list by summing the elements and dividing the sum by the number of elements. Here’s a simple Python function to do this:
```python
def calculate_average(numbers):
if not numbers: # Check if the list is empty
return 0 # Return 0 or None depending on your ... | 1,916 | [
{
"from": "human",
"value": "Write a function to calculate the average of all elements in a list."
},
{
"from": "gpt",
"value": "You can calculate the average of all elements in a list by summing the elements and dividing the sum by the number of elements. Here’s a simple Python function to do t... |
Write a python function to find all prime numbers less than or equal to a given number using the Sieve of Eratosthenes algorithm. | 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 = [p for p in range(2, ... | [
"assert sieve_of_eratosthenes(1) == []",
"assert sieve_of_eratosthenes(30) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]",
"assert sieve_of_eratosthenes(10) == [2, 3, 5, 7]"
] | Certainly! The Sieve of Eratosthenes is an efficient algorithm to find all prime numbers up to a specified integer. Here's how you can implement this in Python:
```python
def sieve_of_eratosthenes(n):
"""Return a list of all prime numbers less than or equal to n."""
if n < 2:
return []
# Step 1: C... | 1,917 | [
{
"from": "human",
"value": "Write a python function to find all prime numbers less than or equal to a given number using the Sieve of Eratosthenes algorithm."
},
{
"from": "gpt",
"value": "Certainly! The Sieve of Eratosthenes is an efficient algorithm to find all prime numbers up to a specified... |
Write a python function to find the maximum number of unique characters in a substring of a given string. | Here is the code to solve this problem:
```python
def max_unique_substring(s):
char_map = {}
left = 0
max_length = 0
for right in range(len(s)):
if s[right] in char_map:
left = max(left, char_map[s[right]] + 1)
char_map[s[right]] = right
max_length = max(ma... | [
"assert max_unique_substring(\"pwwkew\") == 3",
"assert max_unique_substring(\"abcabcbb\") == 3",
"assert max_unique_substring(\"bbbbb\") == 1"
] | To find the maximum number of unique characters in any substring of a given string, you can use a sliding window approach. This method efficiently tracks the characters in the current substring and adjusts the window as necessary to maintain uniqueness.
Here's a function that implements this logic:
```python
def max_... | 1,918 | [
{
"from": "human",
"value": "Write a python function to find the maximum number of unique characters in a substring of a given string."
},
{
"from": "gpt",
"value": "To find the maximum number of unique characters in any substring of a given string, you can use a sliding window approach. This me... |
Create a function that takes an array of integers and returns the number of good pairs. A pair (i, j) is called good if nums[i] == nums[j] and i < j. | Here is the code to solve this problem:
```python
def count_good_pairs(nums):
count = 0
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] == nums[j]:
count += 1
return count
``` | [
"assert count_good_pairs([1,2,3]) == 0",
"assert count_good_pairs([1,2,3,1,1,3]) == 4",
"assert count_good_pairs([1,1,1,1]) == 6"
] | To solve the problem of counting "good pairs" in an array of integers, we can implement a function in Python. We will iterate through the array and count the occurrences of each integer using a dictionary. Then, for every integer that appears `count` times, we can calculate the number of good pairs that can be formed u... | 1,919 | [
{
"from": "human",
"value": "Create a function that takes an array of integers and returns the number of good pairs. A pair (i, j) is called good if nums[i] == nums[j] and i < j."
},
{
"from": "gpt",
"value": "To solve the problem of counting \"good pairs\" in an array of integers, we can implem... |
Write a function that takes a list of integers and reverses the digits of each number in the list. | Here is the code to solve this problem:
```python
def reverse_digits(lst):
return [int(str(abs(num))[::-1]) * (-1 if num < 0 else 1) for num in lst]
``` | [
"assert reverse_digits([-123, -456, -789]) == [-321, -654, -987]",
"assert reverse_digits([123, 456, 789]) == [321, 654, 987]",
"assert reverse_digits([1000, 200, 30]) == [1, 2, 3]"
] | Sure! You can create a function in Python that takes a list of integers and reverses the digits of each number. Here’s one way to do this:
```python
def reverse_digits(num_list):
reversed_list = []
for num in num_list:
# Convert the number to string, reverse it, and convert back to int
reversed... | 1,920 | [
{
"from": "human",
"value": "Write a function that takes a list of integers and reverses the digits of each number in the list."
},
{
"from": "gpt",
"value": "Sure! You can create a function in Python that takes a list of integers and reverses the digits of each number. Here’s one way to do this... |
Write a function to reverse the digits of a positive integer. | Here is the code to solve this problem:
```python
def reverse_number(n):
reversed_num = 0
while n > 0:
reversed_num = reversed_num * 10 + n % 10
n = n // 10
return reversed_num
``` | [
"assert reverse_number(1000) == 1",
"assert reverse_number(1200) == 21",
"assert reverse_number(123) == 321"
] | You can create a function in Python to reverse the digits of a positive integer. Here's a simple implementation:
```python
def reverse_integer(n):
if n < 0:
raise ValueError("Input should be a positive integer")
reversed_num = 0
while n > 0:
digit = n % 10
reversed_num = revers... | 1,921 | [
{
"from": "human",
"value": "Write a function to reverse the digits of a positive integer."
},
{
"from": "gpt",
"value": "You can create a function in Python to reverse the digits of a positive integer. Here's a simple implementation:\n\n```python\ndef reverse_integer(n):\n if n < 0:\n ... |
Write a function to find the longest palindromic subsequence in a given string.
A palindromic subsequence is a sequence that appears in the same order whether read forward or backward. This function should return the length of the longest palindromic subsequence. | 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(\"agbdba\") == 5",
"assert longest_palindromic_subsequence(\"bbbab\") == 4",
"assert longest_palindromic_subsequence(\"cbbd\") == 2"
] | To find the longest palindromic subsequence in a given string, we can use dynamic programming. The key idea is to build a table that stores the lengths of the longest palindromic subsequences for substrings of the given string.
Here's how the function works:
1. We create a 2D array `dp` where `dp[i][j]` will represen... | 1,922 | [
{
"from": "human",
"value": "Write a function to find the longest palindromic subsequence in a given string.\n\nA palindromic subsequence is a sequence that appears in the same order whether read forward or backward. This function should return the length of the longest palindromic subsequence."
},
{
... |
Write a python function to convert a number from one base to another base. | Here is the code to solve this problem:
```python
def convert_base(num: str, from_base: int, to_base: int) -> str:
# Convert from the from_base to base 10
decimal = int(num, from_base)
# Convert from base 10 to the to_base
if to_base == 10:
return str(decimal)
else:
result = ""... | [
"assert convert_base(\"1010\", 2, 8) == \"12\"",
"assert convert_base(\"101\", 2, 10) == \"5\"",
"assert convert_base(\"FF\", 16, 2) == \"11111111\""
] | To convert a number from one base to another in Python, you can create a function that first converts the number to base 10 (decimal) and then converts that decimal number to the target base. Below is a Python function that accomplishes this:
```python
def convert_base(number: str, from_base: int, to_base: int) -> str... | 1,923 | [
{
"from": "human",
"value": "Write a python function to convert a number from one base to another base."
},
{
"from": "gpt",
"value": "To convert a number from one base to another in Python, you can create a function that first converts the number to base 10 (decimal) and then converts that deci... |
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_palindrome_subseq(s):
n = len(s)
dp = [[0 for _ in range(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] + 2
... | [
"assert longest_palindrome_subseq(\"cbbd\") == 2",
"assert longest_palindrome_subseq(\"abac\") == 3",
"assert longest_palindrome_subseq(\"bbbab\") == 4"
] | To find the length of the longest palindromic subsequence in a given string, we can use dynamic programming. A palindromic subsequence is a sequence that appears in the same order forward and backward.
Here's a function that implements this approach:
```python
def longest_palindromic_subsequence(s: str) -> int:
n... | 1,924 | [
{
"from": "human",
"value": "Write a function to find the length of the longest palindromic subsequence in a given string."
},
{
"from": "gpt",
"value": "To find the length of the longest palindromic subsequence in a given string, we can use dynamic programming. A palindromic subsequence is a se... |
Write a function to merge two sorted lists into a single sorted list. | Here is the code to solve this problem:
```python
def merge_sorted_lists(l1, l2):
i, j = 0, 0
merged_list = []
while i < len(l1) and j < len(l2):
if l1[i] < l2[j]:
merged_list.append(l1[i])
i += 1
else:
merged_list.append(l2[j])
j += 1
whi... | [
"assert merge_sorted_lists([1, 3, 5], [2, 4, 6]) == [1, 2, 3, 4, 5, 6]",
"assert merge_sorted_lists([1, 2, 3], [4, 5, 6]) == [1, 2, 3, 4, 5, 6]",
"assert merge_sorted_lists([1, 4, 7], [2, 5, 8]) == [1, 2, 4, 5, 7, 8]"
] | Certainly! You can merge two sorted lists by comparing the elements of both lists and combining them into one sorted list. Here's a Python function that accomplishes this:
```python
def merge_sorted_lists(list1, list2):
merged_list = []
i, j = 0, 0
# Merge while there are elements in both lists
while ... | 1,925 | [
{
"from": "human",
"value": "Write a function to merge two sorted lists into a single sorted list."
},
{
"from": "gpt",
"value": "Certainly! You can merge two sorted lists by comparing the elements of both lists and combining them into one sorted list. Here's a Python function that accomplishes ... |
Write a function to find the largest digit in a given integer. | Here is the code to solve this problem:
```python
def find_largest_digit(n):
n = abs(n)
max_digit = 0
while n:
max_digit = max(max_digit, n % 10)
n //= 10
return max_digit
``` | [
"assert find_largest_digit(12345)==5",
"assert find_largest_digit(9870)==9",
"assert find_largest_digit(0)==0"
] | Certainly! You can write a function in Python to find the largest digit in a given integer. Below is an example of such a function:
```python
def largest_digit(n):
# Convert the integer to a string to iterate through each character
n_str = str(abs(n)) # Use abs() to handle negative integers
# Use max() to... | 1,926 | [
{
"from": "human",
"value": "Write a function to find the largest digit in a given integer."
},
{
"from": "gpt",
"value": "Certainly! You can write a function in Python to find the largest digit in a given integer. Below is an example of such a function:\n\n```python\ndef largest_digit(n):\n ... |
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(s):
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
for char in s:
if char_count[char] == 1:
return char
retu... | [
"assert first_non_repeating_char(\"mississippi\") == \"m\"",
"assert first_non_repeating_char(\"programming\") == \"p\"",
"assert first_non_repeating_char(\"algorithm\") == \"a\""
] | Certainly! You can create a function to find the first non-repeating character in a given string by using a dictionary to count the occurrences of each character. Here's how you can do it:
```python
def first_non_repeating_character(s):
# Create a dictionary to count occurrences of each character
char_count = ... | 1,927 | [
{
"from": "human",
"value": "Write a python function to find the first non-repeating character in a given string."
},
{
"from": "gpt",
"value": "Certainly! You can create a function to find the first non-repeating character in a given string by using a dictionary to count the occurrences of each... |
Write a function to find the largest possible number by rearranging the digits of a given non-negative integer. | Here is the code to solve this problem:
```python
def largest_number(n):
return int("".join(sorted(str(n), reverse=True)))
``` | [
"assert largest_number(120) == 210",
"assert largest_number(123) == 321",
"assert largest_number(213) == 321",
"assert largest_number(102) == 210"
] | You can create a function to find the largest possible number by rearranging the digits of a given non-negative integer by converting the integer to a string, sorting the digits in descending order, and then joining them back together. Here's an implementation in Python:
```python
def largest_number(n: int) -> int:
... | 1,928 | [
{
"from": "human",
"value": "Write a function to find the largest possible number by rearranging the digits of a given non-negative integer."
},
{
"from": "gpt",
"value": "You can create a function to find the largest possible number by rearranging the digits of a given non-negative integer by c... |
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_character(string):
character_count = {}
for char in string:
if char in character_count:
character_count[char] += 1
else:
character_count[char] = 1
for char in string:
if character_count[char] == 1:
retur... | [
"assert first_non_repeating_character('pythonlanguage') == ('p')",
"assert first_non_repeating_character('programming') == ('p')",
"assert first_non_repeating_character('abacabad') == ('c')"
] | Certainly! You can create a function in Python to find the first non-repeating character in a given string by using a dictionary to keep track of character counts. Here's one way to implement it:
```python
def first_non_repeating_character(s):
# Create a dictionary to hold character counts
char_count = {}
... | 1,929 | [
{
"from": "human",
"value": "Write a python function to find the first non-repeating character in a given string."
},
{
"from": "gpt",
"value": "Certainly! You can create a function in Python to find the first non-repeating character in a given string by using a dictionary to keep track of chara... |
Write a function to find the number of distinct islands in a given grid. An island is surrounded by water and formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. | Here is the code to solve this problem:
```python
def dfs(grid, i, j, direction, shape):
if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] == 0:
return
grid[i][j] = 0
shape.append(direction)
dfs(grid, i + 1, j, "D", shape)
dfs(grid, i - 1, j, "U", shape)
dfs(grid, i... | [
"assert count_distinct_islands([[1, 1, 0, 1, 1], [1, 0, 0, 0, 0], [0, 0, 0, 0, 1], [1, 1, 0, 1, 1]]) == 3",
"assert count_distinct_islands([[1, 1, 0, 1, 1], [1, 0, 0, 0, 0], [0, 0, 0, 0, 1], [1, 1, 0, 1, 1], [0, 1, 0, 1, 0]]) == 4",
"assert count_distinct_islands([[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 1, ... | To solve the problem of finding the number of distinct islands in a given 2D grid, we can use Depth-First Search (DFS) to traverse and mark parts of the islands. We need to keep track of the shape of each island to distinguish between different islands. Here's a step-by-step breakdown of the solution:
1. **Traversal**... | 1,930 | [
{
"from": "human",
"value": "Write a function to find the number of distinct islands in a given grid. An island is surrounded by water and formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water."
},
{
"from": "gpt",
"... |
Write a function to return the intersection of two lists. The intersection of two lists is a list of unique elements present in both lists. The elements in the resulting list should be in the order they appear in the first list. | Here is the code to solve this problem:
```python
def list_intersection(list1, list2):
set1 = set(list1)
set2 = set(list2)
return [item for item in list1 if item in set2]
# Alternative solution using set intersection
def list_intersection(list1, list2):
set1 = set(list1)
set2 = set(list2)
retu... | [
"assert list_intersection(['a', 'b', 'c'], ['b', 'c', 'd']) == ['b', 'c']",
"assert list_intersection([10, 20, 30], [15, 20, 25, 30, 35]) == [20, 30]",
"assert list_intersection([1, 2, 3, 4], [3, 4, 5, 6]) == [3, 4]"
] | You can create a function to find the intersection of two lists by following these steps:
1. Loop through the first list and check if each element is present in the second list.
2. Use a set to keep track of the unique elements that are found in both lists to avoid duplicates in the result.
3. Maintain the order of el... | 1,931 | [
{
"from": "human",
"value": "Write a function to return the intersection of two lists. The intersection of two lists is a list of unique elements present in both lists. The elements in the resulting list should be in the order they appear in the first list."
},
{
"from": "gpt",
"value": "You can... |
Write a python function to find the largest sum of any contiguous subarray within a given array. | Here is the code to solve this problem:
```python
def largest_sum_subarray(nums):
if not nums:
return None
max_sum = current_sum = nums[0]
for i in range(1, len(nums)):
current_sum = max(nums[i], current_sum + nums[i])
max_sum = max(max_sum, current_sum)
return max_sum
``` | [
"assert largest_sum_subarray([1, 2, 3, 4, 5]) == 15",
"assert largest_sum_subarray([-1, -2, -3, -4]) == -1",
"assert largest_sum_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6"
] | You can solve the problem of finding the largest sum of any contiguous subarray using Kadane’s algorithm. This algorithm efficiently finds the maximum sum in O(n) time complexity, where n is the length of the array. Here’s the Python function implementing this:
```python
def max_subarray_sum(arr):
if not arr:
... | 1,932 | [
{
"from": "human",
"value": "Write a python function to find the largest sum of any contiguous subarray within a given array."
},
{
"from": "gpt",
"value": "You can solve the problem of finding the largest sum of any contiguous subarray using Kadane’s algorithm. This algorithm efficiently finds ... |
Write a python function to count the number of pairs in an array that have a difference of k. | Here is the code to solve this problem:
```python
def count_pairs_with_diff_k(arr, k):
count = 0
arr.sort()
i, j = 0, 1
while j < len(arr):
if arr[j] - arr[i] == k:
count += 1
i += 1
j += 1
elif arr[j] - arr[i] < k:
j += 1
else:
... | [
"assert count_pairs_with_diff_k([8, 12, 16, 4, 0, 20], 4) == 5",
"assert count_pairs_with_diff_k([1, 5, 3, 4, 2], 1) == 4",
"assert count_pairs_with_diff_k([1, 2, 3, 4, 5], 1) == 4"
] | Certainly! You can use a Python function to count the number of unique pairs in an array that have a specific difference \( k \).
Here's a sample implementation using a set to store the elements for efficient look-up:
```python
def count_pairs_with_difference(arr, k):
# Use a set to store the elements for fast l... | 1,933 | [
{
"from": "human",
"value": "Write a python function to count the number of pairs in an array that have a difference of k."
},
{
"from": "gpt",
"value": "Certainly! You can use a Python function to count the number of unique pairs in an array that have a specific difference \\( k \\). \n\nHere's... |
Write a function to check if a given number is a prime number or not. | Here is the code to solve this problem:
```python
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while (i * i <= n):
if (n % i == 0 or n % (i + 2) == 0):
return False
i += 6
retu... | [
"assert is_prime(29) == True",
"assert is_prime(11) == True",
"assert is_prime(4) == False",
"assert is_prime(10) == False"
] | Certainly! Below is a Python function that checks if a number is a prime number:
```python
def is_prime(n):
"""Check if a number is a prime number.
Args:
n (int): The number to check.
Returns:
bool: True if n is a prime number, False otherwise.
"""
if n <= 1:
return False ... | 1,934 | [
{
"from": "human",
"value": "Write a function to check if a given number is a prime number or not."
},
{
"from": "gpt",
"value": "Certainly! 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 a prime number.\n\n ... |
Write a function that takes a list of numbers and returns the index of the smallest number in the list. | Here is the code to solve this problem:
```python
def find_smallest_index(nums):
smallest_index = 0
for i in range(1, len(nums)):
if nums[i] < nums[smallest_index]:
smallest_index = i
return smallest_index
``` | [
"assert find_smallest_index([4, 2, 1, 5, 3]) == 2",
"assert find_smallest_index([10, 22, 5, 75, 65, 80]) == 2",
"assert find_smallest_index([1, 2, 3, 4, 5]) == 0"
] | You can define a function in Python to find the index of the smallest number in a list. Here is a simple implementation:
```python
def index_of_smallest(numbers):
if not numbers: # Check if the list is empty
return None # Return None if the list is empty
smallest_index = 0 # Start with the fir... | 1,935 | [
{
"from": "human",
"value": "Write a function that takes a list of numbers and returns the index of the smallest number in the list."
},
{
"from": "gpt",
"value": "You can define a function in Python to find the index of the smallest number in a list. Here is a simple implementation:\n\n```pytho... |
Write a python function to find the number of ways to climb a staircase of n steps, given that you can take 1, 2, or 3 steps at a time. | Here is the code to solve this problem:
```python
def count_ways_to_climb(n):
if n <= 1:
return 1
if n == 2:
return 2
a, b, c = 1, 1, 2
for _ in range(3, n + 1):
a, b, c = b, c, a + b + c
return c
``` | [
"assert count_ways_to_climb(5) == 13",
"assert count_ways_to_climb(3) == 4",
"assert count_ways_to_climb(4) == 7"
] | Certainly! You can solve the problem of finding the number of ways to climb a staircase of `n` steps using a dynamic programming approach. The idea is that the total number of ways to reach the nth step is the sum of the ways to reach the (n-1)th, (n-2)th, and (n-3)th steps, since you can take 1, 2, or 3 steps at a tim... | 1,936 | [
{
"from": "human",
"value": "Write a python function to find the number of ways to climb a staircase of n steps, given that you can take 1, 2, or 3 steps at a time."
},
{
"from": "gpt",
"value": "Certainly! You can solve the problem of finding the number of ways to climb a staircase of `n` steps... |
Write a python function to split a string into all possible valid IPv4 addresses. An IPv4 address is a string of four groups of numbers separated by periods. Each group of numbers must be between 0 and 255, and cannot have leading zeros. | Here is the code to solve this problem:
```python
def split_ip(s):
def backtrack(start, tmp_res, k):
if k < 0: return
if start == len(s) and k == 0:
res.append(tmp_res[:-1])
return
for i in range(start, min(start + 3, len(s))):
if (i > start and s[start] ... | [
"assert split_ip(\"25525511135\") == [\"255.255.11.135\", \"255.255.111.35\"]",
"assert split_ip(\"101023\") == [\"1.0.10.23\", \"1.0.102.3\", \"10.1.0.23\", \"10.10.2.3\", \"101.0.2.3\"]",
"assert split_ip(\"0000\") == [\"0.0.0.0\"]"
] | To solve the problem of generating all possible valid IPv4 addresses from a given string, we can approach it by using backtracking. The function will iterate through the string and try to split it into 4 parts, ensuring that each part is a valid segment of an IPv4 address (i.e., between 0 and 255 and not having leading... | 1,937 | [
{
"from": "human",
"value": "Write a python function to split a string into all possible valid IPv4 addresses. An IPv4 address is a string of four groups of numbers separated by periods. Each group of numbers must be between 0 and 255, and cannot have leading zeros."
},
{
"from": "gpt",
"value":... |
Write a function to find the largest product of 'k' consecutive digits in a given number 'n'. | Here is the code to solve this problem:
```python
def largest_product(n: int, k: int) -> int:
s = str(n)
if k > len(s):
return 0
max_product = 0
for i in range(len(s) - k + 1):
product = 1
for j in range(k):
product *= int(s[i+j])
max_product = max(max_produc... | [
"assert largest_product(123456, 3) == 120",
"assert largest_product(12345, 2) == 20",
"assert largest_product(123456789, 4) == 3024"
] | Certainly! Here is a Python function that takes a number `n` (as a string or integer) and an integer `k`, and returns the largest product of `k` consecutive digits in `n`.
```python
def largest_product_of_consecutive_digits(n, k):
# Convert the number to a string if it's not already
n_str = str(n)
# I... | 1,938 | [
{
"from": "human",
"value": "Write a function to find the largest product of 'k' consecutive digits in a given number 'n'."
},
{
"from": "gpt",
"value": "Certainly! Here is a Python function that takes a number `n` (as a string or integer) and an integer `k`, and returns the largest product of `... |
Write a function to calculate the sum of all prime numbers in a list. | Here is the code to solve this problem:
```python
def sum_of_primes(numbers):
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 sum(filter(is_prime, numbers))
``` | [
"assert sum_of_primes([1, 4, 6, 8, 10, 12]) == 0",
"assert sum_of_primes([2, 3, 5, 7, 11, 13]) == 41",
"assert sum_of_primes([29, 37, 41, 43, 47]) == 197"
] | Sure! Here is a Python function that calculates the sum of all prime numbers in a given list. We'll use a helper function to determine if a number is prime.
```python
def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0... | 1,939 | [
{
"from": "human",
"value": "Write a function to calculate the sum of all prime numbers in a list."
},
{
"from": "gpt",
"value": "Sure! Here is a Python function that calculates the sum of all prime numbers in a given list. We'll use a helper function to determine if a number is prime.\n\n```pyt... |
Write a python function to find the smallest missing positive integer in a given unsorted array. | Here is the code to solve this problem:
```python
def find_smallest_missing(arr):
arr = [x for x in arr if x > 0]
arr.sort()
smallest_missing = 1
for num in arr:
if num == smallest_missing:
smallest_missing += 1
elif num > smallest_missing:
break
return small... | [
"assert find_smallest_missing([7, 8, 9, 11, 12]) == 1",
"assert find_smallest_missing([1, 2, 0]) == 3",
"assert find_smallest_missing([3, 4, -1, 1]) == 2"
] | Certainly! The task of finding the smallest missing positive integer in an unsorted array can be efficiently accomplished using a set or by rearranging the array. Below is a Python function that follows the efficient approach using the same array for constant space complexity.
Here's the code implementation:
```pytho... | 1,940 | [
{
"from": "human",
"value": "Write a python function to find the smallest missing positive integer in a given unsorted array."
},
{
"from": "gpt",
"value": "Certainly! The task of finding the smallest missing positive integer in an unsorted array can be efficiently accomplished using a set or by... |
Design a function to calculate the average of a list of numbers, excluding the minimum and maximum values. | Here is the code to solve this problem:
```python
def calculate_average(numbers):
if len(numbers) <= 2:
raise ValueError("The list must have more than two numbers")
numbers.sort()
trimmed = numbers[1:-1]
return sum(trimmed) / len(trimmed)
``` | [
"assert calculate_average([1, 2, 3, 4, 5]) == 3.0",
"assert calculate_average([10, 20, 30, 40, 50]) == 30.0",
"assert calculate_average([4, 5, 6, 7]) == 5.5"
] | Certainly! Below is a Python function that calculates the average of a list of numbers while excluding the minimum and maximum values:
```python
def average_excluding_min_max(numbers):
# Check if there are enough numbers to exclude min and max
if len(numbers) <= 2:
raise ValueError("List must contain m... | 1,941 | [
{
"from": "human",
"value": "Design a function to calculate the average of a list of numbers, excluding the minimum and maximum values."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that calculates the average of a list of numbers while excluding the minimum and maximum va... |
Write a python function to find the sum of all elements in a binary tree. | Here is the code to solve this problem:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def sum_of_tree(root):
if root is None:
return 0
return root.val + sum_of_tree(root.left) + sum_of_tree(roo... | [
"# 1",
"# Tree:",
"# 2 3",
"# / \\",
"# Example 1:",
"# 4 5 6",
"# / \\ \\",
"# 2 3",
"# / \\",
"# Input:",
"# 1",
"#",
"# 4 5 6",
"# / \\ \\",
"# Output: 21",
"# Example 2:",
"#",
"# Input:",... | To find the sum of all elements in a binary tree, you can use a recursive approach. Below is a Python function that accomplishes this task. First, we need to define the structure of a binary tree using a class for the nodes, and then we'll write a function to compute the sum of all nodes in the tree.
Here's the implem... | 1,942 | [
{
"from": "human",
"value": "Write a python function to find the sum of all elements in a binary tree."
},
{
"from": "gpt",
"value": "To find the sum of all elements in a binary tree, you can use a recursive approach. Below is a Python function that accomplishes this task. First, we need to defi... |
Write a python function that takes a string and returns a dictionary where the keys are the characters in the string and the values are the counts of those characters. | Here is the code to solve this problem:
```python
def character_count(s):
res = {}
for c in s:
if c in res:
res[c] += 1
else:
res[c] = 1
return res
``` | [
"assert character_count(\"banana\") == {'b': 1, 'a': 3, 'n': 2}",
"assert character_count(\"hello\") == {'h': 1, 'e': 1, 'l': 2, 'o': 1}",
"assert character_count(\"apple\") == {'a': 1, 'p': 2, 'l': 1, 'e': 1}"
] | You can achieve this by using a simple function that iterates through the string and counts the occurrences of each character. Here’s a straightforward implementation using a dictionary to store the counts:
```python
def char_count(s):
count_dict = {}
for char in s:
if char in count_dict:
c... | 1,943 | [
{
"from": "human",
"value": "Write a python function that takes a string and returns a dictionary where the keys are the characters in the string and the values are the counts of those characters."
},
{
"from": "gpt",
"value": "You can achieve this by using a simple function that iterates throug... |
Create a function to check if a given text is a pangram. A pangram is a sentence that contains every single letter of the alphabet at least once. | Here is the code to solve this problem:
```python
def is_pangram(text):
alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in alphabet:
if char not in text.lower():
return False
return True
``` | [
"assert is_pangram(\"Hello World\") == False",
"assert is_pangram(\"Pack my box with five dozen liquor jugs\") == True",
"assert is_pangram(\"The quick brown fox jumps over the lazy dog\") == True"
] | Certainly! Below is a Python function that checks if a given text is a pangram:
```python
def is_pangram(text):
# Create a set of all English letters
alphabet_set = set('abcdefghijklmnopqrstuvwxyz')
# Convert the input text to lowercase and create a set of its characters
text_set = set(text.lower(... | 1,944 | [
{
"from": "human",
"value": "Create a function to check if a given text is a pangram. A pangram is a sentence that contains every single letter of the alphabet at least once."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that checks if a given text is a pangram:\n\n```pyth... |
Write a python function to find the largest rectangle containing only 1's in a binary matrix and return its area. | Here is the code to solve this problem:
```python
def largest_rectangle(matrix):
if not matrix:
return 0
n = len(matrix)
m = len(matrix[0])
height = [0] * (m + 1)
max_area = 0
for i in range(n):
for j in range(m):
height[j] = height[j] + 1 if matrix[i][j] == 1 else... | [
"assert largest_rectangle([[1]]) == 1",
"assert largest_rectangle([[0]]) == 0",
"assert largest_rectangle([[1,0,1,0,0],[1,0,1,1,1],[1,1,1,1,1],[1,0,0,1,0]]) == 6"
] | To find the largest rectangle containing only 1's in a binary matrix, you can leverage the concept of treating each row as the base of a histogram and using a stack-based approach to find the maximum rectangle area within that histogram.
Here is a Python function that implements this idea:
```python
def maximalRectan... | 1,945 | [
{
"from": "human",
"value": "Write a python function to find the largest rectangle containing only 1's in a binary matrix and return its area."
},
{
"from": "gpt",
"value": "To find the largest rectangle containing only 1's in a binary matrix, you can leverage the concept of treating each row as... |
Write a python function to find the common elements between two given arrays. The common elements should be returned as a list and each element should appear as many times as it shows in both arrays. | Here is the code to solve this problem:
```python
def commonElements(nums1, nums2):
dict1 = {}
dict2 = {}
for i in nums1:
if i in dict1:
dict1[i] += 1
else:
dict1[i] = 1
for j in nums2:
if j in dict2:
dict2[j] += 1
else:
di... | [
"assert commonElements([1, 2, 2, 1], [2, 2]) == [2, 2]",
"assert commonElements([], [1, 2]) == []",
"assert commonElements([1, 2, 2, 1], [2, 2, 3]) == [2, 2]",
"assert commonElements([1, 2, 3], [3, 4]) == [3]"
] | You can create a Python function to find the common elements between two arrays using the `collections.Counter` class, which makes it easy to count the occurrences of each element in the arrays. Here's a sample implementation:
```python
from collections import Counter
def common_elements(arr1, arr2):
# Count the ... | 1,946 | [
{
"from": "human",
"value": "Write a python function to find the common elements between two given arrays. The common elements should be returned as a list and each element should appear as many times as it shows in both arrays."
},
{
"from": "gpt",
"value": "You can create a Python function to ... |
Write a function to convert a given list of integers into Roman numerals. | Here is the code to solve this problem:
```python
def int_to_roman(nums):
romans = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
numbers = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
result = []
for num in nums:
temp = ""
for n, r ... | [
"assert int_to_roman([11, 12, 13, 14, 15, 16, 20, 30, 40, 50]) == ['XI', 'XII', 'XIII', 'XIV', 'XV', 'XVI', 'XX', 'XXX', 'XL', 'L']",
"assert int_to_roman([60, 70, 80, 90, 100, 200, 300, 400, 500]) == ['LX', 'LXX', 'LXXX', 'XC', 'C', 'CC', 'CCC', 'CD', 'D']",
"assert int_to_roman([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]... | You can create a function in Python to convert a list of integers into their corresponding Roman numeral representations. Below is a sample implementation of such a function.
```python
def int_to_roman(num):
# Define the mapping of integers to their corresponding Roman numerals
val = [
1000, 900, 500, ... | 1,947 | [
{
"from": "human",
"value": "Write a function to convert a given list of integers into Roman numerals."
},
{
"from": "gpt",
"value": "You can create a function in Python to convert a list of integers into their corresponding Roman numeral representations. Below is a sample implementation of such... |
Write a function to find the largest product of three numbers in a given list. | Here is the code to solve this problem:
```python
def find_largest_product(nums):
if len(nums) < 3:
return None
nums.sort()
return max(nums[0] * nums[1] * nums[-1], nums[-1] * nums[-2] * nums[-3])
``` | [
"assert find_largest_product([1, 10, 2, 6, 5, 3]) == 300",
"assert find_largest_product([1, 2]) == None",
"assert find_largest_product([-10, -10, 5, 2]) == 500"
] | You can find the largest product of three numbers in a given list by considering a few key scenarios:
1. The largest product can come from the three largest positive numbers.
2. The largest product can also come from two smallest (potentially negative) numbers and the largest positive number.
This is important becaus... | 1,948 | [
{
"from": "human",
"value": "Write a function to find the largest product of three numbers in a given list."
},
{
"from": "gpt",
"value": "You can find the largest product of three numbers in a given list by considering a few key scenarios:\n\n1. The largest product can come from the three large... |
Write a function to generate the nth term of the look-and-say sequence. | Here is the code to solve this problem:
```python
def nth_look_and_say(n):
if n == 1:
return '1'
previous_term = nth_look_and_say(n - 1)
result = ''
count = 1
for i in range(1, len(previous_term)):
if previous_term[i] == previous_term[i - 1]:
count += 1
else:
... | [
"assert nth_look_and_say(1) == '1'",
"assert nth_look_and_say(2) == '11'",
"assert nth_look_and_say(3) == '21'",
"assert nth_look_and_say(5) == '111221'",
"assert nth_look_and_say(4) == '1211'"
] | Sure! The Look-and-Say sequence is a sequence of integers where each term after the first describes the digits of the previous term.
Here's how the sequence starts:
1. The first term is "1".
2. The second term describes the first term: one "1", which is "11".
3. The third term describes the second term: two "1s", whic... | 1,949 | [
{
"from": "human",
"value": "Write a function to generate the nth term of the look-and-say sequence."
},
{
"from": "gpt",
"value": "Sure! The Look-and-Say sequence is a sequence of integers where each term after the first describes the digits of the previous term.\n\nHere's how the sequence star... |
Write a python function to find the longest substring without repeating characters in a given string. | Here is the code to solve this problem:
```python
def longest_substring_without_repeating_characters(s):
char_set = set()
left = 0
max_length = 0
for right in range(len(s)):
while s[right] in char_set:
char_set.remove(s[left])
left += 1
char_set.add(s[right])
... | [
"assert longest_substring_without_repeating_characters(\"bbbbb\") == 1",
"assert longest_substring_without_repeating_characters(\"abcabcbb\") == 3",
"assert longest_substring_without_repeating_characters(\"pwwkew\") == 3"
] | Certainly! You can solve the problem of finding the longest substring without repeating characters using a sliding window approach. Here's a Python function that implements this logic:
```python
def longest_substring_without_repeating(s: str) -> str:
char_index_map = {}
start = 0
max_length = 0
longest... | 1,950 | [
{
"from": "human",
"value": "Write a python function to find the longest substring without repeating characters in a given string."
},
{
"from": "gpt",
"value": "Certainly! You can solve the problem of finding the longest substring without repeating characters using a sliding window approach. He... |
Write a Python function to find the shortest path between two nodes in a graph using Dijkstra's algorithm. | Here is the code to solve this problem:
```python
import heapq
def shortest_path(graph, start, end):
distances = {node: float('infinity') for node in graph}
distances[start] = 0
queue = [(0, start)]
while queue:
current_distance, current_node = heapq.heappop(queue)
if current_distance ... | [
"assert shortest_path({\"A\": {\"B\": 1, \"C\": 4}, \"B\": {\"A\": 1, \"C\": 2}, \"C\": {\"A\": 4, \"B\": 2}}, \"B\", \"A\") == 1",
"assert shortest_path({\"A\": {\"B\": 1, \"C\": 4}, \"B\": {\"A\": 1, \"C\": 2}, \"C\": {\"A\": 4, \"B\": 2}}, \"C\", \"A\") == 3",
"assert shortest_path({\"A\": {\"B\": 1, \"C\": ... | Certainly! Below is a Python function that implements Dijkstra's algorithm to find the shortest path between two nodes in a graph. The graph is represented as an adjacency list, where each node has a list of tuples indicating its neighboring nodes and the associated edge weights.
Here's the implementation of Dijkstra'... | 1,951 | [
{
"from": "human",
"value": "Write a Python function to find the shortest path between two nodes in a graph using Dijkstra's algorithm."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that implements Dijkstra's algorithm to find the shortest path between two nodes in a graph... |
Write a python function to remove all occurrences of a given character from a string. | Here is the code to solve this problem:
```python
def remove_char(s, char):
return s.replace(char, "")
``` | [
"assert remove_char(\"1234567890\", \"5\") == \"123467890\"",
"assert remove_char(\"python programming\", \"m\") == \"python prograing\"",
"assert remove_char(\"hello world\", \"l\") == \"heo word\""
] | Certainly! You can create a Python function to remove all occurrences of a specified character from a string using the `str.replace()` method or by using a list comprehension to filter out the character. Here are both methods presented in a function:
### Method 1: Using `str.replace()`
```python
def remove_char(strin... | 1,952 | [
{
"from": "human",
"value": "Write a python function to remove all occurrences of a given character from a string."
},
{
"from": "gpt",
"value": "Certainly! You can create a Python function to remove all occurrences of a specified character from a string using the `str.replace()` method or by us... |
Write a python function to find the smallest number whose digits add up to a given sum 'n'. | Here is the code to solve this problem:
```python
def smallest_num(n):
if n < 0:
return None
if n == 0:
return 0
result = ""
while n > 9:
result = '9' + result
n -= 9
result = str(n) + result
return int(result)
``` | [
"assert smallest_num(10) == 19",
"assert smallest_num(21) == 399",
"assert smallest_num(4) == 4"
] | To find the smallest number whose digits add up to a given sum `n`, we can use a backtracking approach. The main idea is to start from the least significant digit and assign values to each digit while ensuring that the sum does not exceed `n` and that we always try to use the smallest possible digits at the most signif... | 1,953 | [
{
"from": "human",
"value": "Write a python function to find the smallest number whose digits add up to a given sum 'n'."
},
{
"from": "gpt",
"value": "To find the smallest number whose digits add up to a given sum `n`, we can use a backtracking approach. The main idea is to start from the least... |
Write a python function to find the longest decreasing subsequence in a given array. | Here is the code to solve this problem:
```python
def longest_decreasing(nums):
n = len(nums)
dp = [1]*n
for i in range(1, n):
for j in range(i):
if nums[j] > nums[i]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
``` | [
"assert longest_decreasing([5, 2, 8, 6, 3, 6, 9, 7]) == 3",
"assert longest_decreasing([0, 1, 0, 3, 2, 3]) == 2",
"assert longest_decreasing([10, 9, 2, 5, 3, 7, 101, 18]) == 4"
] | Certainly! To find the longest decreasing subsequence (LDS) in a given array, you can use a dynamic programming approach. Here’s a Python function to do that:
```python
def longest_decreasing_subsequence(arr):
if not arr:
return []
n = len(arr)
# Create an array to store the length of the longest ... | 1,954 | [
{
"from": "human",
"value": "Write a python function to find the longest decreasing subsequence in a given array."
},
{
"from": "gpt",
"value": "Certainly! To find the longest decreasing subsequence (LDS) in a given array, you can use a dynamic programming approach. Here’s a Python function to d... |
Write a python function to count the number of inversions in an array. An inversion is a pair of indices (i, j) such that i < j and arr[i] > arr[j]. | Here is the code to solve this problem:
```python
def merge_count_split_inv(left, right):
i = j = inv_count = 0
merged = []
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
... | [
"assert count_inversions([1, 2, 3, 4, 5]) == 0",
"assert count_inversions([1, 3, 5, 2, 4, 6]) == 3",
"assert count_inversions([1, 20, 6, 4, 5]) == 5"
] | To count the number of inversions in an array, you can use a modified merge sort algorithm. This approach is efficient, with a time complexity of O(n log n), which is significantly better than the naive O(n^2) approach.
Below is the Python function that implements this method to count the number of inversions:
```pyt... | 1,955 | [
{
"from": "human",
"value": "Write a python function to count the number of inversions in an array. An inversion is a pair of indices (i, j) such that i < j and arr[i] > arr[j]."
},
{
"from": "gpt",
"value": "To count the number of inversions in an array, you can use a modified merge sort algori... |
Write a python function to find the length of the longest consecutive sequence in an unsorted array of integers. The sequence must be strictly increasing by one. | Here is the code to solve this problem:
```python
def longest_consecutive_sequence(nums):
if not nums:
return 0
num_set = set(nums)
max_length = 0
for num in num_set:
if num - 1 not in num_set:
current_num = num
current_length = 1
while current_num... | [
"assert longest_consecutive_sequence([10, 5, 12, 3]) == 1",
"assert longest_consecutive_sequence([100, 4, 200, 1, 3, 2]) == 4",
"assert longest_consecutive_sequence([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]) == 9"
] | Certainly! To find the length of the longest consecutive sequence in an unsorted array of integers where the sequence must be strictly increasing by one, you can follow these steps:
1. Use a set to store the unique elements of the array. This will allow for O(1) average time complexity when checking for the presence o... | 1,956 | [
{
"from": "human",
"value": "Write a python function to find the length of the longest consecutive sequence in an unsorted array of integers. The sequence must be strictly increasing by one."
},
{
"from": "gpt",
"value": "Certainly! To find the length of the longest consecutive sequence in an un... |
Write a python function to find the longest word in a given list of words. | Here is the code to solve this problem:
```python
def longest_word(words):
return max(words, key=len)
``` | [
"assert longest_word([\"hello\", \"world\", \"python\", \"programming\"]) == \"programming\"",
"assert longest_word([\"a\", \"ab\", \"abc\"]) == \"abc\"",
"assert longest_word([\"short\", \"longer\", \"longest\"]) == \"longest\""
] | You can create a Python function to find the longest word in a given list of words by iterating through the list and comparing the lengths of the words. Here's a simple implementation of such a function:
```python
def find_longest_word(words):
if not words: # Check if the list is empty
return None
... | 1,957 | [
{
"from": "human",
"value": "Write a python function to find the longest word in a given list of words."
},
{
"from": "gpt",
"value": "You can create a Python function to find the longest word in a given list of words by iterating through the list and comparing the lengths of the words. Here's a... |
Write a python function to find the smallest and largest number in an array. | Here is the code to solve this problem:
```python
def min_max(arr):
return (min(arr), max(arr))
``` | [
"assert min_max([10]) == (10, 10)",
"assert min_max([1, 2, 3, 4, 5]) == (1, 5)",
"assert min_max([4, 2, 9, 7, 5, 6]) == (2, 9)"
] | You can create a simple function in Python to find the smallest and largest numbers in an array (or list). Here's a function that does just that:
```python
def find_smallest_and_largest(arr):
if not arr: # Check if the array is empty
return None, None
smallest = largest = arr[0] # Initialize both sm... | 1,958 | [
{
"from": "human",
"value": "Write a python function to find the smallest and largest number in an array."
},
{
"from": "gpt",
"value": "You can create a simple function in Python to find the smallest and largest numbers in an array (or list). Here's a function that does just that:\n\n```python\... |
Write a python function that takes a list of integers as input and returns a list of all possible subarrays. A subarray is a contiguous part of an array. | Here is the code to solve this problem:
```python
def all_subarrays(nums):
result = []
for i in range(len(nums)):
for j in range(i, len(nums)):
result.append(nums[i:j+1])
return result
``` | [
"assert all_subarrays([1, 2, 3]) == [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]",
"assert all_subarrays([10, 20, 30]) == [[10], [10, 20], [10, 20, 30], [20], [20, 30], [30]]",
"assert all_subarrays([4, 5, 6, 7]) == [[4], [4, 5], [4, 5, 6], [4, 5, 6, 7], [5], [5, 6], [5, 6, 7], [6], [6, 7], [7]]"
] | Certainly! Below is a Python function that takes a list of integers as input and returns a list of all possible subarrays. A subarray is defined as a contiguous part of the array and can vary in size from 1 element up to the length of the entire array.
Here’s the implementation:
```python
def all_subarrays(arr):
... | 1,959 | [
{
"from": "human",
"value": "Write a python function that takes a list of integers as input and returns a list of all possible subarrays. A subarray is a contiguous part of an array."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that takes a list of integers as input and r... |
Write a python function to find the maximum subarray sum in a given list of integers. | Here is the code to solve this problem:
```python
def find_max_subarray_sum(nums):
current_sum = max_sum = nums[0]
for num in nums[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
``` | [
"assert find_max_subarray_sum([5,4,-1,7,8]) == 23",
"assert find_max_subarray_sum([-2,1,-3,4,-1,2,1,-5,4]) == 6",
"assert find_max_subarray_sum([1]) == 1"
] | Certainly! You can use Kadane's algorithm to efficiently find the maximum subarray sum in a list of integers. This algorithm runs in O(n) time and works as follows:
1. Initialize two variables: `max_current` and `max_global`. Set both to the first element of the list.
2. Iterate through the list starting from the seco... | 1,960 | [
{
"from": "human",
"value": "Write a python function to find the maximum subarray sum in a given list of integers."
},
{
"from": "gpt",
"value": "Certainly! You can use Kadane's algorithm to efficiently find the maximum subarray sum in a list of integers. This algorithm runs in O(n) time and wor... |
Write a function to find the median of two sorted arrays. | Here is the code to solve this problem:
```python
def median_sorted_arrays(A,B):
m, n = len(A), len(B)
if m > n:
A, B, m, n = B, A, n, m
i, j = 0, 0
imin, imax, half_len = 0, m, (m + n + 1) // 2
while imin <= imax:
i = (imin + imax) // 2
j = half_len - i
if i < m and... | [
"assert median_sorted_arrays([1,2],[3,4])==2.5",
"assert median_sorted_arrays([1,3],[2])==2",
"assert median_sorted_arrays([1,3],[2,7])==2.5"
] | To find the median of two sorted arrays, we can use a binary search approach to achieve a time complexity of O(log(min(n, m))), where `n` and `m` are the lengths of the two arrays. This method efficiently partitions the two arrays to find the median. Here's a Python function that implements this technique:
```python
d... | 1,961 | [
{
"from": "human",
"value": "Write a function to find the median of two sorted arrays."
},
{
"from": "gpt",
"value": "To find the median of two sorted arrays, we can use a binary search approach to achieve a time complexity of O(log(min(n, m))), where `n` and `m` are the lengths of the two array... |
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 are_anagrams(str1, str2):
if len(str1) != len(str2):
return False
char_count = {}
for char in str1:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
for char in str2:
... | [
"assert are_anagrams(\"listen\", \"silent\") == True",
"assert are_anagrams(\"triangle\", \"integral\") == True",
"assert are_anagrams(\"hello\", \"world\") == False"
] | Certainly! Below is a Python function that checks if two strings are anagrams of each other. This function removes any whitespace and ignores case differences, so it can handle phrases as well.
```python
def are_anagrams(str1, str2):
# Normalize the strings: remove whitespace and convert to lowercase
str1 = st... | 1,962 | [
{
"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": "Certainly! Below... |
Write a python function to find the longest valid parentheses in a given string. | Here is the code to solve this problem:
```python
def longest_valid_parentheses(s: str) -> int:
max_len = 0
stack = [-1]
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
el... | [
"assert longest_valid_parentheses(\"(()\") == 2",
"assert longest_valid_parentheses(\"\") == 0",
"assert longest_valid_parentheses(\")()())\") == 4"
] | Certainly! You can find the longest valid parentheses substring by using a stack or by using dynamic programming. Here’s a simple and efficient approach using a stack:
```python
def longestValidParentheses(s: str) -> int:
# Stack to hold the indices of the characters
stack = [-1]
max_length = 0
fo... | 1,963 | [
{
"from": "human",
"value": "Write a python function to find the longest valid parentheses in a given string."
},
{
"from": "gpt",
"value": "Certainly! You can find the longest valid parentheses substring by using a stack or by using dynamic programming. Here’s a simple and efficient approach us... |
Write a python function to find the number of times a pattern appears in a given string. The pattern can overlap. | Here is the code to solve this problem:
```python
def find_pattern(string, pattern):
count = start = 0
while start < len(string):
pos = string.find(pattern, start)
if pos != -1:
start = pos + 1
count += 1
else:
break
return count
``` | [
"assert find_pattern(\"hello\", \"l\") == 2",
"assert find_pattern(\"test\", \"z\") == 0",
"assert find_pattern(\"abababa\", \"aba\") == 3"
] | You can find the number of times a pattern appears in a given string, including overlapping occurrences, by using a simple loop or a regular expression. Below is a Python function that demonstrates both approaches.
### Using a Loop
This method iteratively checks for the pattern in the string and counts overlapping occ... | 1,964 | [
{
"from": "human",
"value": "Write a python function to find the number of times a pattern appears in a given string. The pattern can overlap."
},
{
"from": "gpt",
"value": "You can find the number of times a pattern appears in a given string, including overlapping occurrences, by using a simple... |
Write a function to find the length of the longest string in a list of strings. | Here is the code to solve this problem:
```python
def longest_string_length(strings):
if not strings:
return 0
return max(len(s) for s in strings)
``` | [
"assert longest_string_length([\"apple\", \"banana\", \"cherry\"]) == 6",
"assert longest_string_length([\"hello\", \"world\", \"python\", \"programming\"]) == 11",
"assert longest_string_length([\"short\", \"longer\", \"longest\"]) == 7"
] | You can achieve this by writing a simple function in Python that iterates through the list of strings and keeps track of the length of the longest string found. Here is one way to implement this function:
```python
def longest_string_length(strings):
if not strings:
return 0 # Return 0 if the list is empt... | 1,965 | [
{
"from": "human",
"value": "Write a function to find the length of the longest string in a list of strings."
},
{
"from": "gpt",
"value": "You can achieve this by writing a simple function in Python that iterates through the list of strings and keeps track of the length of the longest string fo... |
Write a function to calculate the number of unique characters in a given string and return a dictionary where the keys are the unique characters and the values are the counts of those characters in the string. | Here is the code to solve this problem:
```python
def char_frequency(string):
freq = {}
for char in string:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
return freq
``` | [
"assert char_frequency(\"programming\") == {'p': 1, 'r': 2, 'o': 1, 'g': 2, 'a': 1, 'm': 2, 'i': 1, 'n': 1}",
"assert char_frequency(\"hello\") == {'h': 1, 'e': 1, 'l': 2, 'o': 1}",
"assert char_frequency(\"mississippi\") == {'m': 1, 'i': 4, 's': 4, 'p': 2}"
] | You can achieve this by defining a function that utilizes a dictionary to count the occurrences of each character in the input string. Below is a Python function that implements this logic:
```python
def count_unique_characters(input_string):
# Create an empty dictionary to store character counts
char_count = ... | 1,966 | [
{
"from": "human",
"value": "Write a function to calculate the number of unique characters in a given string and return a dictionary where the keys are the unique characters and the values are the counts of those characters in the string."
},
{
"from": "gpt",
"value": "You can achieve this by de... |
Write a function to calculate the number of unique paths from the top-left corner to the bottom-right corner of a 2D grid. You can only move either down or right at any point in time. | Here is the code to solve this problem:
```python
def unique_paths(m, n):
dp = [[1] * 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 unique_paths(3,2)==3",
"assert unique_paths(3,3)==6",
"assert unique_paths(7,3)==28"
] | Certainly! To calculate the number of unique paths in a 2D grid from the top-left corner to the bottom-right corner, you can use a dynamic programming approach or a combinatorial method. Below, I'll provide a Python function that implements the dynamic programming approach.
### Dynamic Programming Approach:
1. We wil... | 1,967 | [
{
"from": "human",
"value": "Write a function to calculate the number of unique paths from the top-left corner to the bottom-right corner of a 2D grid. You can only move either down or right at any point in time."
},
{
"from": "gpt",
"value": "Certainly! To calculate the number of unique paths i... |
Write a function to find the number of unique pairs in a given list of integers that have a difference of k. | Here is the code to solve this problem:
```python
from collections import Counter
def find_pairs(nums, k):
if k < 0:
return 0
freq = Counter(nums)
result = 0
if k == 0:
for num in freq:
if freq[num] > 1:
result += 1
else:
for num in freq:
... | [
"assert find_pairs([3, 1, 4, 1, 5], 2) == 2",
"assert find_pairs([1, 3, 1, 5, 4], 0) == 1",
"assert find_pairs([1, 2, 3, 4, 5], 1) == 4"
] | You can find the number of unique pairs in a list of integers that have a specific difference `k` using a Python function. Here’s a simple and efficient way to implement this by using a set to track the elements we have seen:
```python
def count_unique_pairs_with_difference(nums, k):
if k < 0:
return 0 # ... | 1,968 | [
{
"from": "human",
"value": "Write a function to find the number of unique pairs in a given list of integers that have a difference of k."
},
{
"from": "gpt",
"value": "You can find the number of unique pairs in a list of integers that have a specific difference `k` using a Python function. Here... |
Write a function that takes a list of numbers and returns a list of the unique numbers in the original list, sorted in ascending order. | Here is the code to solve this problem:
```python
def unique_sorted_list(nums):
return sorted(set(nums))
``` | [
"assert unique_sorted_list([4, 2, 6, 2, 3, 4]) == [2, 3, 4, 6]",
"assert unique_sorted_list([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]",
"assert unique_sorted_list([1, 1, 1, 1, 1, 1]) == [1]"
] | You can accomplish this task by defining a function in Python that takes a list of numbers, removes duplicates, and sorts the remaining numbers. Here’s a simple implementation:
```python
def unique_sorted_numbers(numbers):
# Use set to remove duplicates and then convert back to list
unique_numbers = list(set(n... | 1,969 | [
{
"from": "human",
"value": "Write a function that takes a list of numbers and returns a list of the unique numbers in the original list, sorted in ascending order."
},
{
"from": "gpt",
"value": "You can accomplish this task by defining a function in Python that takes a list of numbers, removes ... |
Write a python function to find the length of the longest consecutive sequence in an array. | Here is the code to solve this problem:
```python
def find_longest_consecutive(nums):
if not nums:
return 0
nums_set = set(nums)
longest_streak = 0
for num in nums_set:
if num - 1 not in nums_set:
current_num = num
current_streak = 1
while current_num... | [
"assert find_longest_consecutive([100, 4, 200, 1, 3, 2]) == 4",
"assert find_longest_consecutive([10]) == 1",
"assert find_longest_consecutive([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]) == 9"
] | Certainly! You can find the length of the longest consecutive sequence in an array by using a set to store the unique elements and then iterating through the array to count the lengths of consecutive sequences. Here’s a Python function that accomplishes this:
```python
def longest_consecutive_sequence(nums):
if no... | 1,970 | [
{
"from": "human",
"value": "Write a python function to find the length of the longest consecutive sequence in an array."
},
{
"from": "gpt",
"value": "Certainly! You can find the length of the longest consecutive sequence in an array by using a set to store the unique elements and then iteratin... |
Write a python function to find the number of subarrays with a given sum in a given array. | Here is the code to solve this problem:
```python
def subarrays_with_given_sum(arr, target_sum):
sum_map = {0: 1}
current_sum = 0
count = 0
for i in range(len(arr)):
current_sum += arr[i]
if current_sum - target_sum in sum_map:
count += sum_map[current_sum - target_sum]
... | [
"assert subarrays_with_given_sum([10, 2, -2, -20, 10], -10) == 3",
"assert subarrays_with_given_sum([1, 2, 3], 3) == 2",
"assert subarrays_with_given_sum([9, 4, 20, 3, 10, 5], 33) == 2"
] | You can solve the problem of finding the number of subarrays with a given sum using a dictionary to keep track of the cumulative sums and their frequencies. The idea is to iterate through the array, keep a running sum, and check if there exists a prefix sum that, when subtracted from the current running sum, equals the... | 1,971 | [
{
"from": "human",
"value": "Write a python function to find the number of subarrays with a given sum in a given array."
},
{
"from": "gpt",
"value": "You can solve the problem of finding the number of subarrays with a given sum using a dictionary to keep track of the cumulative sums and their f... |
Write a python function to find the Fibonacci number at the given position using matrix exponentiation. | Here is the code to solve this problem:
```python
def multiply(F, M):
x = F[0][0] * M[0][0] + F[0][1] * M[1][0]
y = F[0][0] * M[0][1] + F[0][1] * M[1][1]
z = F[1][0] * M[0][0] + F[1][1] * M[1][0]
w = F[1][0] * M[0][1] + F[1][1] * M[1][1]
F[0][0] = x
F[0][1] = y
F[1][0] = z
F[... | [
"assert matrix_fibonacci(0) == 0",
"assert matrix_fibonacci(10) == 55",
"assert matrix_fibonacci(1) == 1"
] | Certainly! The Fibonacci sequence can be computed using matrix exponentiation. The Fibonacci numbers can be represented with the following transformation:
\[
\begin{bmatrix}
F(n) \\
F(n-1)
\end{bmatrix}
=
\begin{bmatrix}
1 & 1 \\
1 & 0
\end{bmatrix}^{(n-1)}
\begin{bmatrix}
F(1) \\
F(0)
\end{bmatrix}
\]
Where \(F(1) =... | 1,972 | [
{
"from": "human",
"value": "Write a python function to find the Fibonacci number at the given position using matrix exponentiation."
},
{
"from": "gpt",
"value": "Certainly! The Fibonacci sequence can be computed using matrix exponentiation. The Fibonacci numbers can be represented with the fol... |
Write a function to find the number of times a given word appears in a list of strings. | Here is the code to solve this problem:
```python
def word_count(word_list, word):
count = 0
for w in word_list:
if w == word:
count += 1
return count
``` | [
"assert word_count(['hello', 'world', 'hello', 'python'], 'hello') == 2",
"assert word_count(['cat', 'dog', 'bird', 'fish'], 'bird') == 1",
"assert word_count(['apple', 'banana', 'apple', 'orange'], 'apple') == 2"
] | Certainly! Below is a Python function that counts the occurrences of a given word in a list of strings.
```python
def count_word_occurrences(word, string_list):
"""
Count the occurrences of a given word in a list of strings.
Parameters:
word (str): The word to count.
string_list (list of str): The... | 1,973 | [
{
"from": "human",
"value": "Write a function to find the number of times a given word appears in a list of strings."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that counts the occurrences of a given word in a list of strings.\n\n```python\ndef count_word_occurrences(wor... |
Write a function to find the nth Fibonacci number using matrix exponentiation. | Here is the code to solve this problem:
```python
def fib_matrix(n):
F = [[1, 1], [1, 0]]
if n == 0:
return 0
power(F, n - 1)
return F[0][0]
def multiply(F, M):
x = F[0][0] * M[0][0] + F[0][1] * M[1][0]
y = F[0][0] * M[0][1] + F[0][1] * M[1][1]
z = F[1][0] * M[0][0] + F[1][1] * M[1... | [
"assert fib_matrix(10) == 55",
"assert fib_matrix(0) == 0",
"assert fib_matrix(6) == 8"
] | Certainly! The Fibonacci numbers can be computed efficiently using matrix exponentiation. The key observation is that the Fibonacci sequence can be represented using matrix powers. Specifically, the nth Fibonacci number can be computed using the following relation:
\[
\begin{pmatrix}
F(n) \\
F(n-1)
\end{pmatrix}
=
\be... | 1,974 | [
{
"from": "human",
"value": "Write a function to find the nth Fibonacci number using matrix exponentiation."
},
{
"from": "gpt",
"value": "Certainly! The Fibonacci numbers can be computed efficiently using matrix exponentiation. The key observation is that the Fibonacci sequence can be represent... |
Write a python function to find the minimum number of operations required to transform a given source word into a target word using the following operations:
1. Insert a character
2. Delete a character
3. Replace a character
The function should return the count of minimum operations required. | Here is the code to solve this problem:
```python
def find_min_operations(source, target):
m, n = len(source), len(target)
dp = [[0] * (n+1) for _ in range(m+1)]
for i in range(m+1):
for j in range(n+1):
if i == 0:
dp[i][j] = j
elif j == 0:
d... | [
"assert find_min_operations(\"kitten\", \"sitting\") == 3",
"assert find_min_operations(\"horse\", \"ros\") == 3",
"assert find_min_operations(\"intention\", \"execution\") == 5"
] | You can solve this problem using the dynamic programming approach, which is commonly known as the Edit Distance problem. Here's a Python function that implements this approach:
```python
def min_operations(source, target):
# Create a table to store results of subproblems
m = len(source)
n = len(target)
... | 1,975 | [
{
"from": "human",
"value": "Write a python function to find the minimum number of operations required to transform a given source word into a target word using the following operations:\n1. Insert a character\n2. Delete a character\n3. Replace a character\n\nThe function should return the count of minimum ... |
Write a function to calculate the maximum sum of non-adjacent elements in the given array. You are not allowed to use adjacent elements to calculate the maximum sum. | Here is the code to solve this problem:
```python
def max_non_adjacent_sum(nums):
incl = 0
excl = 0
for num in nums:
new_excl = excl if excl > incl else incl
incl = excl + num
excl = new_excl
return max(excl, incl)
``` | [
"assert max_non_adjacent_sum([3, 2, 5, 10, 7]) == 15",
"assert max_non_adjacent_sum([3, 2, 7, 10]) == 13",
"assert max_non_adjacent_sum([2, 4, 6, 8]) == 12"
] | To solve the problem of calculating the maximum sum of non-adjacent elements in an array, we can use a dynamic programming approach. The idea is to maintain two variables that help us keep track of the maximum sum we can achieve at each step, taking into account whether we include the current element or not.
Here is a... | 1,976 | [
{
"from": "human",
"value": "Write a function to calculate the maximum sum of non-adjacent elements in the given array. You are not allowed to use adjacent elements to calculate the maximum sum."
},
{
"from": "gpt",
"value": "To solve the problem of calculating the maximum sum of non-adjacent el... |
Write a python function to decode a run-length encoded string. Run-length encoding is a form of data compression where sequences of the same character are replaced with a single character and the count of that character. The encoded string will have the format "number[string]" where the number represents the frequency ... | Here is the code to solve this problem:
```python
def decode_string(s):
stack = []
current_num = 0
current_string = ""
for char in s:
if char.isdigit():
current_num = current_num * 10 + int(char)
elif char == '[':
stack.append((current_string, current_num))
... | [
"assert decode_string(\"3[a]2[bc]\") == \"aaabcbc\"",
"assert decode_string(\"3[a2[c]]\") == \"accaccacc\"",
"assert decode_string(\"2[abc]3[cd]ef\") == \"abcabccdcdcdef\""
] | You can decode a run-length encoded string using a stack-based approach. The idea is to traverse the encoded string character by character, identifying numbers (which represent counts) and strings enclosed within brackets (which are the sequences to be repeated). Here's a Python function to perform this decoding:
```p... | 1,977 | [
{
"from": "human",
"value": "Write a python function to decode a run-length encoded string. Run-length encoding is a form of data compression where sequences of the same character are replaced with a single character and the count of that character. The encoded string will have the format \"number[string]\"... |
Write a function to find the number of times a given target element appears in a list. | Here is the code to solve this problem:
```python
def count_target_occurrences(lst, target):
return lst.count(target)
``` | [
"assert count_target_occurrences([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) == 1",
"assert count_target_occurrences([1, 1, 2, 3, 3, 4, 5, 6, 6, 6, 7, 8, 9], 6) == 3",
"assert count_target_occurrences([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 1) == 10"
] | You can achieve this by creating a function in Python that iterates through the list and counts the occurrences of the target element. Here's a simple implementation of such a function:
```python
def count_occurrences(target, lst):
"""Returns the number of times target appears in the list lst."""
count = 0
... | 1,978 | [
{
"from": "human",
"value": "Write a function to find the number of times a given target element appears in a list."
},
{
"from": "gpt",
"value": "You can achieve this by creating a function in Python that iterates through the list and counts the occurrences of the target element. Here's a simpl... |
Write a python function to find the number of islands in a given binary matrix. Here, an island is defined as a group of 1s connected horizontally or vertically. Diagonal connections are not considered as part of the same island. | Here is the code to solve this problem:
```python
def count_islands(matrix):
if not matrix:
return 0
def dfs(i, j):
if i < 0 or i >= len(matrix) or j < 0 or j >= len(matrix[0]) or matrix[i][j] != 1:
return
matrix[i][j] = 0
dfs(i-1, j)
dfs(i+1, j)
dfs... | [
"assert count_islands([[1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 1, 1], [0, 0, 0, 0, 0], [1, 0, 1, 0, 1]]) == 6",
"assert count_islands([[1, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1]]) == 4",
"assert count_islands([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0,... | To solve the problem of counting the number of islands in a binary matrix, we can use a Depth-First Search (DFS) approach. The idea is to traverse each cell in the matrix. If we find a '1', we will perform a DFS to mark all '1's connected to it (i.e., part of the same island) as visited (or change them to '0's). We inc... | 1,979 | [
{
"from": "human",
"value": "Write a python function to find the number of islands in a given binary matrix. Here, an island is defined as a group of 1s connected horizontally or vertically. Diagonal connections are not considered as part of the same island."
},
{
"from": "gpt",
"value": "To sol... |
Create a function that receives a list of integers and returns True if the sum of any two integers in the list equals zero. Otherwise, return False. | Here is the code to solve this problem:
```python
def sum_to_zero(lst):
seen = set()
for num in lst:
if -num in seen:
return True
seen.add(num)
return False
``` | [
"assert sum_to_zero([2, 4, 6, 8]) == False",
"assert sum_to_zero([1, 3, -1, 4]) == True",
"assert sum_to_zero([0, 0, 1, 2]) == True"
] | You can create a function to check if the sum of any two integers in a list equals zero using a set for efficient look-up. Here's a Python function that accomplishes this:
```python
def has_zero_sum_pair(nums):
seen = set()
for num in nums:
if -num in seen:
return True
seen.add(num)... | 1,980 | [
{
"from": "human",
"value": "Create a function that receives a list of integers and returns True if the sum of any two integers in the list equals zero. Otherwise, return False."
},
{
"from": "gpt",
"value": "You can create a function to check if the sum of any two integers in a list equals zero... |
Write a function to find the longest palindromic substring in a given string. | Here is the code to solve this problem:
```python
def longest_palindromic_substring(s: str) -> str:
if len(s) <= 1:
return s
def expand_around_center(left, right):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return s[left... | [
"assert longest_palindromic_substring(\"babad\") == \"bab\"",
"assert longest_palindromic_substring(\"cbbd\") == \"bb\"",
"assert longest_palindromic_substring(\"ac\") == \"a\"",
"assert longest_palindromic_substring(\"a\") == \"a\""
] | You can find the longest palindromic substring in a given string using a variety of methods. One efficient approach is to expand around potential centers of the palindrome. Below is a Python function that implements this approach:
```python
def longest_palindromic_substring(s: str) -> str:
def expand_around_center... | 1,981 | [
{
"from": "human",
"value": "Write a function to find the longest palindromic substring in a given string."
},
{
"from": "gpt",
"value": "You can find the longest palindromic substring in a given string using a variety of methods. One efficient approach is to expand around potential centers of t... |
Write a python function to calculate the sum of all the odd numbers in a list using recursion. | Here is the code to solve this problem:
```python
def sum_of_odd(lst):
if len(lst) == 0:
return 0
else:
if lst[0] % 2 == 1:
return lst[0] + sum_of_odd(lst[1:])
else:
return sum_of_odd(lst[1:])
``` | [
"assert sum_of_odd([1, 3, 5, 7, 9]) == 25",
"assert sum_of_odd([1, 2, 3, 4, 5]) == 9",
"assert sum_of_odd([2, 4, 6, 8]) == 0"
] | Certainly! Below is a Python function that calculates the sum of all the odd numbers in a list using recursion:
```python
def sum_of_odds(numbers):
# Base case: if the list is empty
if not numbers:
return 0
# Get the first element
first = numbers[0]
# Check if the first element is... | 1,982 | [
{
"from": "human",
"value": "Write a python function to calculate the sum of all the odd numbers in a list using recursion."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that calculates the sum of all the odd numbers in a list using recursion:\n\n```python\ndef sum_of_odds... |
Write a function that takes a list of words and returns the longest word. If there are multiple words with the maximum length, return the one that appears first in the list. | Here is the code to solve this problem:
```python
def longest_word(word_list):
max_length = 0
longest_word = ''
for word in word_list:
if len(word) > max_length:
max_length = len(word)
longest_word = word
return longest_word
``` | [
"assert longest_word(['cat', 'dog', 'elephant', 'duck']) == 'elephant'",
"assert longest_word(['one', 'two', 'three', 'four', 'five']) == 'three'",
"assert longest_word(['apple', 'banana', 'cherry', 'date']) == 'banana'"
] | You can accomplish this easily with a function in Python. Below is a function called `find_longest_word` that takes a list of words as input and returns the longest word. If there are multiple longest words, it returns the first one that appears in the list.
```python
def find_longest_word(words):
if not words:
... | 1,983 | [
{
"from": "human",
"value": "Write a function that takes a list of words and returns the longest word. If there are multiple words with the maximum length, return the one that appears first in the list."
},
{
"from": "gpt",
"value": "You can accomplish this easily with a function in Python. Belo... |
Write a function to generate all possible permutations of a given list. | Here is the code to solve this problem:
```python
def all_permutations(lst):
if len(lst) <= 1:
return [lst]
result = []
for i in range(len(lst)):
m = lst[i]
rem_lst = lst[:i] + lst[i+1:]
for p in all_permutations(rem_lst):
result.append([m] + p)
return resu... | [
"assert all_permutations([1, 2, 3]) == [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]",
"assert all_permutations([1]) == [[1]]",
"assert all_permutations(['a', 'b', 'c']) == [['a', 'b', 'c'], ['a', 'c', 'b'], ['b', 'a', 'c'], ['b', 'c', 'a'], ['c', 'a', 'b'], ['c', 'b', 'a']]"
] | Certainly! You can use a recursive approach to generate all possible permutations of a list. Here's a Python function that does just that:
```python
def generate_permutations(lst):
# Base case: if the list is empty or has one element, return it as the only permutation
if len(lst) <= 1:
return [lst]
... | 1,984 | [
{
"from": "human",
"value": "Write a function to generate all possible permutations of a given list."
},
{
"from": "gpt",
"value": "Certainly! You can use a recursive approach to generate all possible permutations of a list. Here's a Python function that does just that:\n\n```python\ndef generat... |
Write a python function that takes a list of integers as input and returns the largest and smallest numbers from the list. | Here is the code to solve this problem:
```python
def find_largest_smallest(numbers):
largest = smallest = numbers[0]
for num in numbers[1:]:
if num > largest:
largest = num
elif num < smallest:
smallest = num
return smallest, largest
``` | [
"assert find_largest_smallest([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (-10, 123)",
"assert find_largest_smallest([1, 2, 3, 4, 5]) == (1, 5)",
"assert find_largest_smallest([0, 0, 0, 0]) == (0, 0)"
] | You can achieve this by writing a simple Python function that uses the built-in functions `max()` and `min()` to find the largest and smallest numbers in a list of integers. Here's how you can do it:
```python
def find_largest_and_smallest(numbers):
if not numbers: # Check if the list is empty
return None... | 1,985 | [
{
"from": "human",
"value": "Write a python function that takes a list of integers as input and returns the largest and smallest numbers from the list."
},
{
"from": "gpt",
"value": "You can achieve this by writing a simple Python function that uses the built-in functions `max()` and `min()` to ... |
Write a function to check if the given list of numbers is sorted in ascending order. | Here is the code to solve this problem:
```python
def is_sorted(nums):
for i in range(len(nums)-1):
if nums[i] > nums[i+1]:
return False
return True
``` | [
"assert is_sorted([5, 4, 3, 2, 1])==False",
"assert is_sorted([1, 2, 3, 4, 5])==True",
"assert is_sorted([1, 3, 2, 4, 5])==False"
] | You can create a function in Python to check if a list of numbers is sorted in ascending order. Here's one way to do it:
```python
def is_sorted_ascending(numbers):
# Iterate through the list and check if each number is less than or equal to the next
for i in range(len(numbers) - 1):
if numbers[i] > nu... | 1,986 | [
{
"from": "human",
"value": "Write a function to check if the given list of numbers is sorted in ascending order."
},
{
"from": "gpt",
"value": "You can create a function in Python to check if a list of numbers is sorted in ascending order. Here's one way to do it:\n\n```python\ndef is_sorted_as... |
Write a python function to find the maximum length of a subarray with equal number of 0's and 1's. | Here is the code to solve this problem:
```python
def max_length_subarray(nums):
ctr = 0
d = {0:0}
maxlen = 0
for i, val in enumerate(nums, 1):
if val==0:
ctr-=1
else:
ctr+=1
if ctr in d:
maxlen = max(maxlen, i-d[ctr])
else:
... | [
"assert max_length_subarray([0,1]) == 2",
"assert max_length_subarray([0,1,0]) == 2",
"assert max_length_subarray([0, 1, 0, 1, 0, 1, 1]) == 6"
] | To find the maximum length of a subarray with an equal number of 0's and 1's, we can use a technique that involves a hash map (dictionary in Python) to store the cumulative frequency difference between the number of 1's and 0's encountered so far while iterating through the array.
The approach is as follows:
1. We ca... | 1,987 | [
{
"from": "human",
"value": "Write a python function to find the maximum length of a subarray with equal number of 0's and 1's."
},
{
"from": "gpt",
"value": "To find the maximum length of a subarray with an equal number of 0's and 1's, we can use a technique that involves a hash map (dictionary... |
Write a function to find the kth smallest element in a given list. | Here is the code to solve this problem:
```python
def find_kth_smallest(arr, k):
arr.sort()
return arr[k-1]
``` | [
"assert find_kth_smallest([1, 2, 3, 4, 5], 3) == 3",
"assert find_kth_smallest([3, 2, 1], 1) == 1",
"assert find_kth_smallest([10, 2, 14, 4, 7, 6], 4) == 7",
"assert find_kth_smallest([1, 2, 3], 2) == 2"
] | Certainly! To find the k-th smallest element in a given list, we can use several methods. One effective way is to use the Quickselect algorithm, which has an average time complexity of O(n). Below is an implementation in Python:
```python
import random
def partition(arr, low, high, pivot_index):
pivot_value = arr... | 1,988 | [
{
"from": "human",
"value": "Write a function to find the kth smallest element in a given list."
},
{
"from": "gpt",
"value": "Certainly! To find the k-th smallest element in a given list, we can use several methods. One effective way is to use the Quickselect algorithm, which has an average tim... |
Write a function to calculate the sum of the squares of elements in a given list of integers. | Here is the code to solve this problem:
```python
def sum_of_squares(numbers):
return sum(x ** 2 for x in numbers)
``` | [
"assert sum_of_squares([10, 20, 30]) == 1400",
"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"
] | Certainly! Below is a Python function that calculates the sum of the squares of elements in a given list of integers.
```python
def sum_of_squares(numbers):
return sum(x**2 for x in numbers)
# Example usage:
sample_list = [1, 2, 3, 4]
result = sum_of_squares(sample_list)
print("Sum of squares:", result)
```
### ... | 1,989 | [
{
"from": "human",
"value": "Write a function to calculate the sum of the squares of elements in a given list of integers."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that calculates the sum of the squares of elements in a given list of integers.\n\n```python\ndef sum_of... |
Write a function that takes a list of strings and returns a new list with the strings sorted by their length in descending order. If two strings have the same length, they should be sorted alphabetically. | Here is the code to solve this problem:
```python
def sort_strings(strings):
return sorted(strings, key=lambda s: (-len(s), s))
# Test cases
assert sort_strings(["apple", "banana", "pear", "orange"]) == ["banana", "orange", "apple", "pear"]
assert sort_strings(["dog", "cat", "elephant", "tiger"]) == ["elephant", ... | [
"assert sort_strings([\"dog\", \"cat\", \"elephant\", \"tiger\"]) == [\"elephant\", \"tiger\", \"cat\", \"dog\"]",
"assert sort_strings([\"hello\", \"world\", \"python\", \"code\"]) == [\"python\", \"hello\", \"world\", \"code\"]",
"assert sort_strings([\"apple\", \"banana\", \"pear\", \"orange\"]) == [\"banana... | You can achieve this by defining a function that uses Python's built-in `sorted()` function along with a custom sorting key. Here's how you can implement the function:
```python
def sort_strings_by_length(strings):
return sorted(strings, key=lambda x: (-len(x), x))
# Example usage:
input_list = ["apple", "banana"... | 1,990 | [
{
"from": "human",
"value": "Write a function that takes a list of strings and returns a new list with the strings sorted by their length in descending order. If two strings have the same length, they should be sorted alphabetically."
},
{
"from": "gpt",
"value": "You can achieve this by definin... |
Write a Python function to find the intersection of two sorted lists without duplicates. | Here is the code to solve this problem:
```python
def intersect_sorted_lists(list1, list2):
result = []
i, j = 0, 0
while i < len(list1) and j < len(list2):
if list1[i] == list2[j]:
if not result or result[-1] != list1[i]: # Avoid duplicates
result.append(list1[i])
... | [
"assert intersect_sorted_lists([1, 3, 4, 6, 8, 10], [2, 3, 5, 6, 8, 10, 11]) == [3, 6, 8, 10]",
"assert intersect_sorted_lists([1, 3, 3, 5, 7, 9, 9], [3, 5, 5, 7, 7, 9, 9, 11]) == [3, 5, 7, 9]",
"assert intersect_sorted_lists([1, 3, 5, 7, 9], [2, 4, 6, 8, 10]) == []"
] | Certainly! You can find the intersection of two sorted lists without duplicates using a simple two-pointer technique. This approach takes advantage of the fact that both lists are sorted, allowing you to iterate through them efficiently.
Here's a Python function to do that:
```python
def intersection_sorted_lists(lis... | 1,991 | [
{
"from": "human",
"value": "Write a Python function to find the intersection of two sorted lists without duplicates."
},
{
"from": "gpt",
"value": "Certainly! You can find the intersection of two sorted lists without duplicates using a simple two-pointer technique. This approach takes advantage... |
Write a python function to find the sum of the digits of a given number in reverse order. | Here is the code to solve this problem:
```python
def reverse_digit_sum(n):
if n < 0:
return "Input is not a positive integer!"
sum = 0
while n > 0:
digit = n % 10
sum += digit
n = n // 10
return sum
``` | [
"assert reverse_digit_sum(98765) == 35",
"assert reverse_digit_sum(1234) == 10",
"assert reverse_digit_sum(0) == 0"
] | You can achieve this by creating a function that takes an integer as input, reverses the digits, and then sums them. Here's a Python function that does just that:
```python
def sum_of_reversed_digits(number):
# Convert the number to its absolute value and then to a string
str_number = str(abs(number))
... | 1,992 | [
{
"from": "human",
"value": "Write a python function to find the sum of the digits of a given number in reverse order."
},
{
"from": "gpt",
"value": "You can achieve this by creating a function that takes an integer as input, reverses the digits, and then sums them. Here's a Python function that... |
Write a function to check if a given number is a Happy Number or not. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly ... | Here is the code to solve this problem:
```python
def is_happy_number(n: int) -> bool:
def get_next(n):
total_sum = 0
while n > 0:
n, digit = divmod(n, 10)
total_sum += digit ** 2
return total_sum
seen = set()
while n != 1 and n not in seen:
seen.add... | [
"assert is_happy_number(2) == False",
"assert is_happy_number(19) == True",
"assert is_happy_number(7) == True"
] | Sure! To determine whether a given number is a happy number, we can create a function that follows the steps outlined in your description. The function will:
1. Replace the number by the sum of the squares of its digits.
2. Keep track of previously seen numbers to detect cycles (if the number starts repeating without ... | 1,993 | [
{
"from": "human",
"value": "Write a function to check if a given number is a Happy Number or not. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (wh... |
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(s):
char_count = {}
for ch in s:
if ch in char_count:
char_count[ch] += 1
else:
char_count[ch] = 1
for ch in s:
if char_count[ch] == 1:
return ch
return None
``` | [
"assert first_non_repeating('python') == 'p'",
"assert first_non_repeating('swiss') == 'w'",
"assert first_non_repeating('level') == 'v'"
] | Certainly! Below is a Python function that finds the first non-repeating character in a given string:
```python
def first_non_repeating_character(s):
# Create a dictionary to count occurrences of each character
char_count = {}
# Count each character in the string
for char in s:
char_count[... | 1,994 | [
{
"from": "human",
"value": "Write a python function to find the first non-repeating character in a given string."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that finds the first non-repeating character in a given string:\n\n```python\ndef first_non_repeating_character(s... |
Write a python function that checks if the given string is a valid parentheses string. A string is valid if all types of parentheses ('()', '[]', '{}') are correctly closed and nested. | Here is the code to solve this problem:
```python
def is_valid_parentheses(s: str) -> bool:
stack = []
map = {")": "(", "]": "[", "}": "{"}
for char in s:
if char in map.values():
stack.append(char)
elif char in map.keys():
if stack == [] or map[char] != stack.p... | [
"assert is_valid_parentheses(\"()[]{}\") == True",
"assert is_valid_parentheses(\"()\") == True",
"assert is_valid_parentheses(\"([)]\") == False",
"assert is_valid_parentheses(\"{[]}\") == True",
"assert is_valid_parentheses(\"(]\") == False"
] | You can check if a string containing different types of parentheses is valid by using a stack data structure. Here is a Python function that implements this logic:
```python
def is_valid_parentheses(s):
# Dictionary to hold matching pairs
matching_parentheses = {')': '(', '}': '{', ']': '['}
stack = []
... | 1,995 | [
{
"from": "human",
"value": "Write a python function that checks if the given string is a valid parentheses string. A string is valid if all types of parentheses ('()', '[]', '{}') are correctly closed and nested."
},
{
"from": "gpt",
"value": "You can check if a string containing different type... |
Write a function to generate all possible permutations of a given string. | Here is the code to solve this problem:
```python
def permutations(string):
if len(string) == 0:
return [""]
result = []
for i in range(len(string)):
char = string[i]
remaining = string[:i] + string[i+1:]
for permutation in permutations(remaining):
result.append(... | [
"assert permutations(\"abc\") == [\"abc\", \"acb\", \"bac\", \"bca\", \"cab\", \"cba\"]",
"assert permutations(\"\") == [\"\"]",
"assert permutations(\"a\") == [\"a\"]"
] | Certainly! Here's a Python function that generates all possible permutations of a given string:
```python
def generate_permutations(s):
if len(s) == 0:
return ['']
permutations = []
for i in range(len(s)):
# Get the current character
current_char = s[i]
# Get the remaining c... | 1,996 | [
{
"from": "human",
"value": "Write a function to generate all possible permutations of a given string."
},
{
"from": "gpt",
"value": "Certainly! Here's a Python function that generates all possible permutations of a given string:\n\n```python\ndef generate_permutations(s):\n if len(s) == 0:\n... |
Write a function to check if a number is a power of two. | Here is the code to solve this problem:
```python
def is_power_of_two(n):
if n == 0:
return False
while n != 1:
if n % 2 != 0:
return False
n = n // 2
return True
``` | [
"assert is_power_of_two(1) == True",
"assert is_power_of_two(16) == True",
"assert is_power_of_two(18) == False",
"assert is_power_of_two(0) == False"
] | Certainly! To check if a number is a power of two, we can use a mathematical property of powers of two: a number \( n \) is a power of two if, when represented in binary, it has exactly one bit set to 1.
This property can be efficiently checked using the expression `(n > 0) and (n & (n - 1) == 0)`. This works because... | 1,997 | [
{
"from": "human",
"value": "Write a function to check if a number is a power of two."
},
{
"from": "gpt",
"value": "Certainly! To check if a number is a power of two, we can use a mathematical property of powers of two: a number \\( n \\) is a power of two if, when represented in binary, it has... |
Write a function to find the mode(s) of the given list of integers. If there are multiple modes, return all of them in a list sorted in ascending order. | Here is the code to solve this problem:
```python
from collections import Counter
def find_modes(nums):
count = Counter(nums)
max_freq = max(count.values())
modes = [num for num, freq in count.items() if freq == max_freq]
return sorted(modes)
``` | [
"assert find_modes([1, 2, 2, 3, 4]) == [2]",
"assert find_modes([1, 2, 3]) == [1, 2, 3]",
"assert find_modes([1, 1, 2, 3, 3]) == [1, 3]"
] | To find the mode(s) of a list of integers, we can follow these steps:
1. Count the frequency of each integer in the list.
2. Identify the highest frequency.
3. Collect all integers that have that highest frequency.
4. Sort the collected integers in ascending order.
Here is a Python function that implements this appro... | 1,998 | [
{
"from": "human",
"value": "Write a function to find the mode(s) of the given list of integers. If there are multiple modes, return all of them in a list sorted in ascending order."
},
{
"from": "gpt",
"value": "To find the mode(s) of a list of integers, we can follow these steps:\n\n1. Count t... |
Write a python function to find the number of times a given number appears in a list. | Here is the code to solve this problem:
```python
def count_number(lst,n) :
count = 0
for i in lst:
if i == n:
count += 1
return count
``` | [
"assert count_number([4,5,6,7,8,8],8) == 2",
"assert count_number([1,2,3,2,4,2],2) == 3",
"assert count_number([1,2,3,4,5,6],7) == 0"
] | You can create a simple Python function to count the occurrences of a specified number in a list using the `count()` method. Here’s a straightforward implementation:
```python
def count_occurrences(lst, num):
return lst.count(num)
```
### Example Usage:
```python
my_list = [1, 2, 3, 4, 2, 2, 5]
number_to_count =... | 1,999 | [
{
"from": "human",
"value": "Write a python function to find the number of times a given number appears in a list."
},
{
"from": "gpt",
"value": "You can create a simple Python function to count the occurrences of a specified number in a list using the `count()` method. Here’s a straightforward ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.