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 python function to find the symmetric difference between two sets of integers. | Here is the code to solve this problem:
```python
def symmetric_difference(set1, set2):
return set1.symmetric_difference(set2)
``` | [
"assert symmetric_difference({10, 20, 30}, {20, 30, 40}) == {10, 40}",
"assert symmetric_difference({1, 2, 3, 4}, {3, 4, 5, 6}) == {1, 2, 5, 6}",
"assert symmetric_difference({1, 2, 3}, {4, 5, 6}) == {1, 2, 3, 4, 5, 6}"
] | You can find the symmetric difference between two sets in Python using the built-in `set` operations. The symmetric difference consists of elements that are in either of the sets but not in their intersection. You can use the `^` operator or the `symmetric_difference()` method to achieve this.
Here is a Python functio... | 12,700 | [
{
"from": "human",
"value": "Write a python function to find the symmetric difference between two sets of integers."
},
{
"from": "gpt",
"value": "You can find the symmetric difference between two sets in Python using the built-in `set` operations. The symmetric difference consists of elements t... |
Write a function that checks if a given list of integers can reach the last index starting from the first index, given that each element in the array represents the maximum jump length from that position. | Here is the code to solve this problem:
```python
def can_reach_end(nums):
length = len(nums)
if(length == 1):
return True
elif(nums[0] == 0):
return False
max_reach = nums[0]
for i in range(1, length):
if i > max_reach:
return False
max_reach = max(max_r... | [
"assert can_reach_end([2,3,1,1,4]) == True",
"assert can_reach_end([3,2,1,0,4]) == False",
"assert can_reach_end([0]) == True",
"assert can_reach_end([2,0,0]) == True"
] | Sure! You can solve the problem of checking whether you can reach the last index of the list from the first index using a greedy algorithm. Here’s a Python function that implements this logic:
```python
def can_reach_end(nums):
if not nums:
return False
max_reachable = 0
n = len(nums)
for i i... | 12,701 | [
{
"from": "human",
"value": "Write a function that checks if a given list of integers can reach the last index starting from the first index, given that each element in the array represents the maximum jump length from that position."
},
{
"from": "gpt",
"value": "Sure! You can solve the problem... |
Write a function that takes a string of digits and returns the smallest and largest number possible by rearranging the digits. For a given string, all digits must be used exactly once to form the numbers.
For example:
- If the input is "3401", the smallest number is "0134" (which is 134 when converted to an integer) a... | Here is the code to solve this problem:
```python
def smallest_largest_number(digits):
# Convert the input string into a list of digits
digit_list = list(digits)
# Sort the list in ascending order to get the smallest number
digit_list.sort()
smallest_number = int(''.join(digit_list))
... | [
"assert smallest_largest_number(\"3401\")==(134,4310)",
"assert smallest_largest_number(\"123\")==(123,321)",
"assert smallest_largest_number(\"001\")==(1,100)"
] | Certainly! You can achieve this by defining a function in Python that handles the rearrangement of the digits. Here's how you can do this:
```python
def rearrange_digits(s):
# Sort the digits to find the smallest and largest arrangements
digits = sorted(s) # Sorts digits in ascending order for smallest number... | 12,702 | [
{
"from": "human",
"value": "Write a function that takes a string of digits and returns the smallest and largest number possible by rearranging the digits. For a given string, all digits must be used exactly once to form the numbers.\n\nFor example:\n- If the input is \"3401\", the smallest number is \"0134... |
Write a python function to find the maximum number of vowels in any substring of given length in a given string. | Here is the code to solve this problem:
```python
def max_vowels(s: str, k: int) -> int:
vowels = "aeiou"
max_count, count = 0, 0
for i in range(len(s)):
if s[i] in vowels:
count += 1
if i >= k and s[i-k] in vowels:
count -= 1
max_count = max(max_count, count... | [
"assert max_vowels(\"abciiidef\", 3) == 3",
"assert max_vowels(\"leetcode\", 3) == 2",
"assert max_vowels(\"aeiou\", 2) == 2"
] | You can solve this problem by using a sliding window approach. The idea is to keep track of the number of vowels in the current substring of the specified length as you iterate over the string.
Here's a Python function that implements this approach:
```python
def max_vowels_in_substring(s: str, length: int) -> int:
... | 12,703 | [
{
"from": "human",
"value": "Write a python function to find the maximum number of vowels in any substring of given length in a given string."
},
{
"from": "gpt",
"value": "You can solve this problem by using a sliding window approach. The idea is to keep track of the number of vowels in the cur... |
Write a function to find the largest square containing only 1's in a binary matrix and return its area. | Here is the code to solve this problem:
```python
def maximalSquare(matrix) -> int:
if not matrix:
return 0
m, n = len(matrix), len(matrix[0])
dp = [[0] * n for _ in range(m)]
maxSide = 0
for i in range(m):
for j in range(n):
if matrix[i][j] == '1':
if i ... | [
"assert maximalSquare([[\"0\",\"0\",\"0\",\"0\"],[\"0\",\"0\",\"0\",\"0\"],[\"0\",\"0\",\"0\",\"0\"],[\"0\",\"0\",\"0\",\"0\"]]) == 0",
"assert maximalSquare([[\"1\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\"]]) == 16",
"assert maximalSquare([[\"1\",\"0\",\"1... | To solve the problem of finding the largest square containing only 1's in a binary matrix and returning its area, we can utilize dynamic programming. The idea is to iterate through the matrix and maintain a 2D array that records the size of the largest square that can be formed at each position.
Here's the Python func... | 12,704 | [
{
"from": "human",
"value": "Write a function to find the largest square containing only 1's in a binary matrix and return its area."
},
{
"from": "gpt",
"value": "To solve the problem of finding the largest square containing only 1's in a binary matrix and returning its area, we can utilize dyn... |
Write a function that takes in two lists, `keys` and `values`, and returns a dictionary created by pairing each element of `keys` with the corresponding element of `values`. If the lengths of `keys` and `values` are not equal, the function should return an error message. | Here is the code to solve this problem:
```python
def create_dictionary(keys, values):
if len(keys) != len(values):
return 'Error: lengths of keys and values do not match'
dictionary = dict(zip(keys, values))
return dictionary
``` | [
"assert create_dictionary(['a', 'b', 'c'], [1, 2, 3]) == {'a': 1, 'b': 2, 'c': 3}",
"assert create_dictionary(['x', 'y', 'z'], [4, 5, 6, 7]) == 'Error: lengths of keys and values do not match'",
"assert create_dictionary(['one', 'two'], [10, 20]) == {'one': 10, 'two': 20}"
] | You can create a function in Python that accomplishes this task using the following code:
```python
def create_dictionary(keys, values):
# Check if the lengths of keys and values are equal
if len(keys) != len(values):
return "Error: The lengths of keys and values are not equal."
# Use a dictio... | 12,705 | [
{
"from": "human",
"value": "Write a function that takes in two lists, `keys` and `values`, and returns a dictionary created by pairing each element of `keys` with the corresponding element of `values`. If the lengths of `keys` and `values` are not equal, the function should return an error message."
},
... |
Write a function that takes a list of integers as input and returns a new list with only the even numbers from the original list, sorted in ascending order. | Here is the code to solve this problem:
```python
def get_sorted_evens(nums):
return sorted([num for num in nums if num % 2 == 0])
assert get_sorted_evens([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [2, 4, 6, 8, 10]
assert get_sorted_evens([11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) == [12, 14, 16, 18, 20]
assert get_sorte... | [
"assert get_sorted_evens([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [2, 4, 6, 8, 10]",
"assert get_sorted_evens([11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) == [12, 14, 16, 18, 20]",
"assert get_sorted_evens([21, 22, 23, 24, 25, 26, 27, 28, 29, 30]) == [22, 24, 26, 28, 30]"
] | You can achieve this by defining a function in Python that filters out the even numbers from the input list and then sorts them in ascending order. Here's a sample implementation of such a function:
```python
def get_sorted_even_numbers(input_list):
# Use list comprehension to filter and create a list of even numb... | 12,706 | [
{
"from": "human",
"value": "Write a function that takes a list of integers as input and returns a new list with only the even numbers from the original list, sorted in ascending order."
},
{
"from": "gpt",
"value": "You can achieve this by defining a function in Python that filters out the even... |
Write a python function to calculate the minimum cost to connect all the sticks into one stick using the given algorithm. The cost of connecting two sticks is equal to the sum of their values. | Here is the code to solve this problem:
```python
import heapq
def connect_sticks(sticks):
heapq.heapify(sticks)
cost = 0
while len(sticks) > 1:
a1 = heapq.heappop(sticks)
a2 = heapq.heappop(sticks)
cost += a1 + a2
heapq.heappush(sticks, a1 + a2)
return cost
``` | [
"assert connect_sticks([5]) == 0",
"assert connect_sticks([1,8,3,5]) == 30",
"assert connect_sticks([2,4,3]) == 14"
] | Certainly! To solve the problem of connecting all the sticks into one stick with the minimum cost, we can use a greedy algorithm. The idea is to always connect the two shortest sticks available. This is efficiently managed using a min-heap (priority queue) where we can repeatedly extract the two smallest values, combin... | 12,707 | [
{
"from": "human",
"value": "Write a python function to calculate the minimum cost to connect all the sticks into one stick using the given algorithm. The cost of connecting two sticks is equal to the sum of their values."
},
{
"from": "gpt",
"value": "Certainly! To solve the problem of connecti... |
Write a function to find the next largest number using the same digits of the given number. | Here is the code to solve this problem:
```python
def next_larger_number(n):
digits = list(str(n))
i = len(digits) - 2
while i >= 0:
if digits[i] < digits[i+1]:
break
i -= 1
if i == -1:
return -1
j = len(digits) - 1
while digits[j] <= digits[i]:
j -= ... | [
"assert next_larger_number(12)==21",
"assert next_larger_number(2017)==2071",
"assert next_larger_number(513)==531"
] | To find the next largest number using the same digits of a given number, you can implement the following algorithm. This algorithm rearranges the digits to form the next permutation in lexicographical order. Here's a Python function that achieves that:
```python
def next_largest_number(n):
# Convert the number to ... | 12,708 | [
{
"from": "human",
"value": "Write a function to find the next largest number using the same digits of the given number."
},
{
"from": "gpt",
"value": "To find the next largest number using the same digits of a given number, you can implement the following algorithm. This algorithm rearranges th... |
Create a python function that takes a list of integers as input and returns a dictionary where the keys are the integers from the input list and the values are the counts of how many times each integer appears in the list. | Here is the code to solve this problem:
```python
def count_integers(lst):
counts = {}
for i in lst:
if i in counts:
counts[i] += 1
else:
counts[i] = 1
return counts
``` | [
"assert count_integers([1, 2, 3, 2, 1, 3, 1, 1, 2, 3, 3, 3, 3]) == {1: 4, 2: 3, 3: 6}",
"assert count_integers([7, 8, 9, 7, 8, 8, 9, 9, 9, 9]) == {7: 2, 8: 3, 9: 5}",
"assert count_integers([4, 5, 6, 4, 5, 6, 6, 6, 6]) == {4: 2, 5: 2, 6: 5}"
] | You can create a Python function to count the occurrences of each integer in a list and return a dictionary using the following code:
```python
def count_integers(input_list):
count_dict = {}
for num in input_list:
if num in count_dict:
count_dict[num] += 1
else:
count_d... | 12,709 | [
{
"from": "human",
"value": "Create a python function that takes a list of integers as input and returns a dictionary where the keys are the integers from the input list and the values are the counts of how many times each integer appears in the list."
},
{
"from": "gpt",
"value": "You can creat... |
Write a function to find the maximum length of a subarray with a sum equal to k from a given list of integers. | Here is the code to solve this problem:
```python
def max_len_subarray_sum(arr, k):
n = len(arr)
sum = 0
res = 0
sumToIndex = {0: -1}
for i in range(n):
sum += arr[i]
if sum - k in sumToIndex:
res = max(res, i - sumToIndex[sum - k])
if sum not in sumToIndex:
... | [
"assert max_len_subarray_sum([10, 5, 2, 7, 1, 9], 15) == 4",
"assert max_len_subarray_sum([-5, 8, -14, 2, 4, 12], -5) == 5",
"assert max_len_subarray_sum([-2, -1, 2, 1], 1) == 2",
"assert max_len_subarray_sum([1, -1, 5, -2, 3], 3) == 4"
] | You can solve the problem of finding the maximum length of a subarray with a sum equal to a specified value \( k \) by using a hash map (dictionary in Python) to store the cumulative sums. Here's how you can implement this in Python:
```python
def max_len_subarray_with_sum_k(arr, k):
# Dictionary to store the cumu... | 12,710 | [
{
"from": "human",
"value": "Write a function to find the maximum length of a subarray with a sum equal to k from a given list of integers."
},
{
"from": "gpt",
"value": "You can solve the problem of finding the maximum length of a subarray with a sum equal to a specified value \\( k \\) by usin... |
Write a function to calculate the sum of all elements in a list that are greater than a given number. | Here is the code to solve this problem:
```python
def sum_greater_than(lst, num):
total = 0
for i in lst:
if i > num:
total += i
return total
``` | [
"assert sum_greater_than([1, 2, 3, 4, 5], 2) == 12",
"assert sum_greater_than([10, 20, 30, 40, 50], 25) == 120",
"assert sum_greater_than([1, 1, 1, 1, 1], 0) == 5"
] | Certainly! You can create a function in Python that takes a list and a threshold number as inputs and returns the sum of all elements in the list that are greater than that number. Here’s how you can implement that:
```python
def sum_greater_than(numbers, threshold):
"""
Calculate the sum of all elements in th... | 12,711 | [
{
"from": "human",
"value": "Write a function to calculate the sum of all elements in a list that are greater than a given number."
},
{
"from": "gpt",
"value": "Certainly! You can create a function in Python that takes a list and a threshold number as inputs and returns the sum of all elements ... |
Write a function to determine if a given sequence of numbers can be obtained by popping elements from a stack, where the stack is initially filled with numbers in ascending order starting from 1.
The function should take in two lists as arguments:
1. A list of numbers pushed onto the stack.
2. A list of numbers popped... | Here is the code to solve this problem:
```python
def validate_stack_sequence(pushed, popped):
stack = []
j = 0
for e in pushed:
stack.append(e)
while stack and popped and stack[-1] == popped[j]:
stack.pop()
j += 1
return j == len(popped)
``` | [
"assert validate_stack_sequence([1,2,3,4,5], [4,5,3,2,1]) == True",
"assert validate_stack_sequence([1,2,3,4,5], [4,3,5,1,2]) == False",
"assert validate_stack_sequence([1,2,3,4,5], [1,2,3,4,5]) == True"
] | To solve the problem of validating if a popped sequence can be obtained from a sequence of numbers pushed onto the stack, we can simulate the stack operations. The stack follows the Last In First Out (LIFO) principle, meaning the last element added to the stack is the first one to be removed.
Here's how you can implem... | 12,712 | [
{
"from": "human",
"value": "Write a function to determine if a given sequence of numbers can be obtained by popping elements from a stack, where the stack is initially filled with numbers in ascending order starting from 1.\n\nThe function should take in two lists as arguments:\n1. A list of numbers pushed... |
Write a function that takes a list of numbers as input and returns a new list containing only the unique numbers from the input list, in the order they first appeared. | Here is the code to solve this problem:
```python
def unique_numbers(numbers):
seen = set()
unique = []
for num in numbers:
if num not in seen:
seen.add(num)
unique.append(num)
return unique
``` | [
"assert unique_numbers([1, 2, 2, 3, 4, 3, 5]) == [1, 2, 3, 4, 5]",
"assert unique_numbers([10, 9, 8, 9, 10, 7, 6]) == [10, 9, 8, 7, 6]",
"assert unique_numbers([100, 200, 200, 100, 300, 400]) == [100, 200, 300, 400]"
] | You can achieve this by defining a function that utilizes a set to track unique numbers while maintaining their order of appearance in the input list. Here's a Python function that does just that:
```python
def unique_numbers(input_list):
unique_list = []
seen = set()
for num in input_list:
if... | 12,713 | [
{
"from": "human",
"value": "Write a function that takes a list of numbers as input and returns a new list containing only the unique numbers from the input list, in the order they first appeared."
},
{
"from": "gpt",
"value": "You can achieve this by defining a function that utilizes a set to t... |
Write a function to find the number of triplets in a given list that their sum is less than a given target number. | Here is the code to solve this problem:
```python
def triplet_sum_less_than_target(nums, target):
n = len(nums)
res = 0
nums = sorted(nums)
for i in range(n - 2):
low, high = i + 1, n - 1
while low < high:
sum = nums[i] + nums[low] + nums[high]
if sum < target:
... | [
"assert triplet_sum_less_than_target([], 0) == 0",
"assert triplet_sum_less_than_target([0], 0) == 0",
"assert triplet_sum_less_than_target([-2, 0, 1, 3], 2) == 2"
] | To count the number of triplets in a list whose sum is less than a given target number, we can use a combination of sorting and a two-pointer approach. Here’s how you can implement this in Python:
```python
def count_triplets_with_sum_less_than(nums, target):
# Sort the input list
nums.sort()
count = 0
... | 12,714 | [
{
"from": "human",
"value": "Write a function to find the number of triplets in a given list that their sum is less than a given target number."
},
{
"from": "gpt",
"value": "To count the number of triplets in a list whose sum is less than a given target number, we can use a combination of sorti... |
Write a function that takes a list of integers as input and returns a new list with only the elements that occur an odd number of times. | Here is the code to solve this problem:
```python
from collections import Counter
def odd_elements(lst):
counts = Counter(lst)
return [num for num in lst if counts[num] % 2 != 0]
``` | [
"assert odd_elements([1, 2, 3, 2, 3, 3, 4]) == [1, 3, 3, 3, 4]",
"assert odd_elements([8, 9, 8, 9, 10]) == [10]",
"assert odd_elements([5, 6, 7, 6, 7, 7]) == [5, 7, 7, 7]"
] | You can achieve this by using a dictionary to count the occurrences of each element in the list and then generating a new list with only those elements that occur an odd number of times. Below is a Python function that implements this logic:
```python
def odd_occurrences(input_list):
# Create a dictionary to count... | 12,715 | [
{
"from": "human",
"value": "Write a function that takes a list of integers as input and returns a new list with only the elements that occur an odd number of times."
},
{
"from": "gpt",
"value": "You can achieve this by using a dictionary to count the occurrences of each element in the list and... |
Write a python function to find the LCM (Least Common Multiple) of three numbers. | Here is the code to solve this problem:
```python
def least_common_multiple(x, y, z):
def lcm_two_numbers(a,b):
if a > b:
greater = a
else:
greater = b
while(True):
if((greater % a == 0) and (greater % b == 0)):
lcm = greater
... | [
"assert least_common_multiple(12, 15, 20) == 60",
"assert least_common_multiple(14, 21, 28) == 84",
"assert least_common_multiple(10, 20, 30) == 60"
] | To find the Least Common Multiple (LCM) of three numbers, we can use the relationship between the LCM and the Greatest Common Divisor (GCD). The LCM of two numbers \( a \) and \( b \) can be calculated using the formula:
\[
\text{LCM}(a, b) = \frac{|a \times b|}{\text{GCD}(a, b)}
\]
To find the LCM of three numbers \... | 12,716 | [
{
"from": "human",
"value": "Write a python function to find the LCM (Least Common Multiple) of three numbers."
},
{
"from": "gpt",
"value": "To find the Least Common Multiple (LCM) of three numbers, we can use the relationship between the LCM and the Greatest Common Divisor (GCD). The LCM of tw... |
Write a function to replace all occurrences of a given value in a list with another value. | Here is the code to solve this problem:
```python
def replace_value_in_list(list1, old_value, new_value):
for i in range(len(list1)):
if list1[i] == old_value:
list1[i] = new_value
return list1
``` | [
"assert replace_value_in_list(['A', 'B', 'C', 'D'], 'B', 'E')==['A', 'E', 'C', 'D']",
"assert replace_value_in_list([3, 2, 2, 3], 3, 0)==[0, 2, 2, 0]",
"assert replace_value_in_list([1, 2, 3, 4, 5], 3, 6)==[1, 2, 6, 4, 5]"
] | Certainly! You can create a function in Python that replaces all occurrences of a specified value in a list with another value. Below is an example of such a function:
```python
def replace_value(input_list, old_value, new_value):
"""
Replace all occurrences of old_value in input_list with new_value.
Para... | 12,717 | [
{
"from": "human",
"value": "Write a function to replace all occurrences of a given value in a list with another value."
},
{
"from": "gpt",
"value": "Certainly! You can create a function in Python that replaces all occurrences of a specified value in a list with another value. Below is an examp... |
Write a python function to replace all the spaces in a given string with a given character. | Here is the code to solve this problem:
```python
def replaceSpaces(a_string, replace_character):
return a_string.replace(' ', replace_character)
``` | [
"assert replaceSpaces(\"Hello World\", \"%20\") == \"Hello%20World\"",
"assert replaceSpaces(\"Code Generation\", \"_\") == \"Code_Generation\"",
"assert replaceSpaces(\" \", \"-\") == \"-\""
] | You can create a Python function to replace all spaces in a given string with a specified character using the `str.replace()` method. Here's a simple implementation of that:
```python
def replace_spaces(input_string, replacement_char):
"""
Replace all spaces in the input string with the specified character.
... | 12,718 | [
{
"from": "human",
"value": "Write a python function to replace all the spaces in a given string with a given character."
},
{
"from": "gpt",
"value": "You can create a Python function to replace all spaces in a given string with a specified character using the `str.replace()` method. Here's a s... |
Write a python function to find the number of trailing zeros in the factorial of a given number. | Here is the code to solve this problem:
```python
def factorial_zeros(n):
zeros = 0
while n >= 5:
n //= 5
zeros += n
return zeros
``` | [
"assert factorial_zeros(5) == 1",
"assert factorial_zeros(10) == 2",
"assert factorial_zeros(25) == 6",
"assert factorial_zeros(50) == 12"
] | To determine the number of trailing zeros in the factorial of a given number \( n \), we can use the fact that trailing zeros are created by pairs of factors of 10. Since 10 can be factored into 2 and 5, and there will always be more factors of 2 than factors of 5 in a factorial, the number of trailing zeros is determi... | 12,719 | [
{
"from": "human",
"value": "Write a python function to find the number of trailing zeros in the factorial of a given number."
},
{
"from": "gpt",
"value": "To determine the number of trailing zeros in the factorial of a given number \\( n \\), we can use the fact that trailing zeros are created... |
Write a function that takes a list of integers as input and returns a new list with only the even numbers from the original list, sorted in ascending order. | Here is the code to solve this problem:
```python
def even_sort(nums):
even_nums = [num for num in nums if num % 2 == 0]
even_nums.sort()
return even_nums
``` | [
"assert even_sort([5, 3, 2, 8, 1, 4]) == [2, 4, 8]",
"assert even_sort([5, 3, 1]) == []",
"assert even_sort([10, 22, 33, 47, 50]) == [10, 22, 50]"
] | Sure! Below is a Python function that takes a list of integers as input, filters out the even numbers, and returns a new list containing those even numbers sorted in ascending order.
```python
def get_sorted_even_numbers(numbers):
# Filter out even numbers and sort them in ascending order
even_numbers = [num f... | 12,720 | [
{
"from": "human",
"value": "Write a function that takes a list of integers as input and returns a new list with only the even numbers from the original list, sorted in ascending order."
},
{
"from": "gpt",
"value": "Sure! Below is a Python function that takes a list of integers as input, filter... |
Write a function to check if a given string can be interpreted as a decimal number. | Here is the code to solve this problem:
```python
import re
def is_decimal(s):
pattern = r'^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$'
if re.match(pattern, s.strip()):
return True
return False
``` | [
"assert is_decimal(\"0123\") == True",
"assert is_decimal(\"-2.3\") == True",
"assert is_decimal(\"2\") == True",
"assert is_decimal(\"0089\") == True",
"assert is_decimal(\"abc\") == False",
"assert is_decimal(\"3.1415\") == True",
"assert is_decimal(\"1a\") == False",
"assert is_decimal(\"e3\") == F... | You can create a Python function to check if a given string can be interpreted as a decimal number by using regular expressions. Here's a function that does just that:
```python
import re
def is_decimal_number(s):
# Define a regular expression pattern for a valid decimal number
pattern = r'^[+-]?(\d+(\.\d*)?|... | 12,721 | [
{
"from": "human",
"value": "Write a function to check if a given string can be interpreted as a decimal number."
},
{
"from": "gpt",
"value": "You can create a Python function to check if a given string can be interpreted as a decimal number by using regular expressions. Here's a function that ... |
Write a function that takes a string `s` and a list of words `words`, and returns the starting indices of all substrings in `s` that are concatenations of every word in `words` exactly once. | Here is the code to solve this problem:
```python
from collections import Counter
def find_concatenated_substrings(s, words):
if not s or not words:
return []
word_len = len(words[0])
word_num = len(words)
total_len = word_len * word_num
if len(s) < total_len:
return []
word_co... | [
"assert find_concatenated_substrings(\"barfoothefoobarman\", [\"foo\", \"bar\"]) == [0, 9]",
"assert find_concatenated_substrings(\"wordgoodgoodgoodbestword\", [\"word\", \"good\", \"best\", \"word\"]) == []",
"assert find_concatenated_substrings(\"barfoofoobarthefoobarman\", [\"bar\", \"foo\", \"the\"]) == [6,... | To solve the problem of finding all starting indices of substrings in a given string `s` that are concatenations of every word in a list `words` exactly once, we can use a sliding window approach with the help of a hashmap (or dictionary) to keep track of word counts.
Here's a step-by-step breakdown of the algorithm:
... | 12,722 | [
{
"from": "human",
"value": "Write a function that takes a string `s` and a list of words `words`, and returns the starting indices of all substrings in `s` that are concatenations of every word in `words` exactly once."
},
{
"from": "gpt",
"value": "To solve the problem of finding all starting ... |
Write a function to find the maximum profit from stock prices with cooldown. Given a list of daily stock prices, calculate the maximum profit that can be made by buying and selling stocks. However, after selling a stock, you cannot buy stock on the next day (i.e., cooldown one day). | Here is the code to solve this problem:
```python
def max_profit_with_cooldown(prices):
if not prices:
return 0
n = len(prices)
sell = [0] * n
buy = [0] * n
buy[0] = -prices[0]
for i in range(1, n):
sell[i] = max(sell[i-1], buy[i-1] + prices[i])
buy[i] = max(buy[i-1], (s... | [
"assert max_profit_with_cooldown([1]) == 0",
"assert max_profit_with_cooldown([1, 2, 3, 0, 2]) == 3",
"assert max_profit_with_cooldown([1, 2, 4, 5, 7]) == 6",
"assert max_profit_with_cooldown([1, 3, 7, 0, 2]) == 6"
] | To solve the problem of finding the maximum profit from stock prices with a cooldown period of one day after selling, we can use dynamic programming. We will keep track of three states:
1. `hold`: The maximum profit we can have while holding a stock.
2. `sold`: The maximum profit we can have while not holding a stock ... | 12,723 | [
{
"from": "human",
"value": "Write a function to find the maximum profit from stock prices with cooldown. Given a list of daily stock prices, calculate the maximum profit that can be made by buying and selling stocks. However, after selling a stock, you cannot buy stock on the next day (i.e., cooldown one d... |
Write a function that takes a list of tuples, where each tuple contains a string and an integer. The function should return a dictionary where the keys are the strings, and the values are the integers squared. | Here is the code to solve this problem:
```python
def tuple_to_dict(t_list):
d = {}
for t in t_list:
d[t[0]] = t[1] ** 2
return d
``` | [
"assert tuple_to_dict([(\"apple\", 2), (\"banana\", 3), (\"cherry\", 4)]) == {\"apple\": 4, \"banana\": 9, \"cherry\": 16}",
"assert tuple_to_dict([(\"dog\", 5), (\"cat\", 6), (\"bird\", 7)]) == {\"dog\": 25, \"cat\": 36, \"bird\": 49}",
"assert tuple_to_dict([(\"orange\", 8), (\"peach\", 9), (\"pear\", 10)]) =... | You can achieve this by defining a function that iterates through the list of tuples, extracts the string and integer from each tuple, squares the integer, and adds the result to a dictionary. Here's how you can implement this:
```python
def tuples_to_squared_dict(tuples_list):
result_dict = {}
for string, int... | 12,724 | [
{
"from": "human",
"value": "Write a function that takes a list of tuples, where each tuple contains a string and an integer. The function should return a dictionary where the keys are the strings, and the values are the integers squared."
},
{
"from": "gpt",
"value": "You can achieve this by de... |
Write a function that takes a list of tuples as input. Each tuple consists of a string and an integer. The function should return a new list of tuples, but in this new list, the tuples should be sorted primarily by the string in lexicographical order, and then by the integer in numerical order. If a tuple contains a st... | Here is the code to solve this problem:
```python
def sort_tuples(lst):
digits = []
non_digits = []
for tup in lst:
if tup[0].isdigit():
digits.append(tup)
else:
non_digits.append(tup)
non_digits.sort(key=lambda x: (x[0], x[1]))
digits.sort(key=lambda x: (x[0... | [
"assert sort_tuples([(\"foo\", 5), (\"bar\", 3), (\"baz\", 7), (\"123\", 99)])==[(\"bar\", 3), (\"baz\", 7), (\"foo\", 5), (\"123\", 99)]",
"assert sort_tuples([(\"apple\", 2), (\"orange\", 3), (\"banana\", 1), (\"404\", 101)])==[(\"apple\", 2), (\"banana\", 1), (\"orange\", 3), (\"404\", 101)]",
"assert sort_t... | You can achieve this by defining a function that sorts the list of tuples based on the specified criteria. The idea is to create a custom sorting key that separates tuples with strings containing digits from those that do not. Here is how you can implement this:
```python
def sort_tuples(tuples_list):
def sort_key... | 12,725 | [
{
"from": "human",
"value": "Write a function that takes a list of tuples as input. Each tuple consists of a string and an integer. The function should return a new list of tuples, but in this new list, the tuples should be sorted primarily by the string in lexicographical order, and then by the integer in ... |
Write a python function that checks if a given string can be rearranged into a palindrome. A palindrome is a word that reads the same backward as forward, e.g., 'radar' or 'level'. | Here is the code to solve this problem:
```python
from collections import Counter
# T=n,S=1
def is_palindrome_rearrange(s):
oddFrequencyCount = 0
for count in Counter(s).values():
oddFrequencyCount += count % 2
if oddFrequencyCount > 1:
return False
return True
``` | [
"assert is_palindrome_rearrange('a') == True",
"assert is_palindrome_rearrange('aabbccc') == True",
"assert is_palindrome_rearrange('aaa') == True",
"assert is_palindrome_rearrange('code') == False",
"assert is_palindrome_rearrange('carerac') == True",
"assert is_palindrome_rearrange('civil') == False",
... | To determine if a given string can be rearranged into a palindrome, we can use the following approach:
A string can be rearranged to form a palindrome if:
- At most one character appears an odd number of times (for strings of odd length).
- All characters appear an even number of times (for strings of even length).
T... | 12,726 | [
{
"from": "human",
"value": "Write a python function that checks if a given string can be rearranged into a palindrome. A palindrome is a word that reads the same backward as forward, e.g., 'radar' or 'level'."
},
{
"from": "gpt",
"value": "To determine if a given string can be rearranged into a... |
Write a function that merges two sorted lists into a new sorted list. | Here is the code to solve this problem:
```python
def merge_two_sorted_lists(list1, list2):
i, j = 0, 0
merged_list = []
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
merged_list.append(list1[i])
i += 1
else:
merged_list.append(list2[j]... | [
"assert merge_two_sorted_lists([1, 3, 5], [2, 4, 6]) == [1, 2, 3, 4, 5, 6]",
"assert merge_two_sorted_lists([1, 2, 3], [4, 5, 6]) == [1, 2, 3, 4, 5, 6]",
"assert merge_two_sorted_lists([1, 3, 5], [2, 6, 8]) == [1, 2, 3, 5, 6, 8]"
] | You can accomplish this by defining a function that takes two sorted lists as input and combines them into a new sorted list. Below is a Python function that does just that:
```python
def merge_sorted_lists(list1, list2):
merged_list = []
i, j = 0, 0
# Traverse both lists and append smaller element to... | 12,727 | [
{
"from": "human",
"value": "Write a function that merges two sorted lists into a new sorted list."
},
{
"from": "gpt",
"value": "You can accomplish this by defining a function that takes two sorted lists as input and combines them into a new sorted list. Below is a Python function that does jus... |
Write a python function that takes a given string and returns a new string that is a mirrored version of the original string. | Here is the code to solve this problem:
```python
def mirror_string(s):
return s[::-1]
``` | [
"assert mirror_string(\"hello\") == \"olleh\"",
"assert mirror_string(\"world\") == \"dlrow\"",
"assert mirror_string(\"python\") == \"nohtyp\""
] | You can create a mirrored version of a string by reversing the order of its characters. In Python, this can be accomplished using slicing. Below is a function that does just that:
```python
def mirror_string(s):
"""
Returns a mirrored version of the input string.
Parameters:
s (str): The string to be ... | 12,728 | [
{
"from": "human",
"value": "Write a python function that takes a given string and returns a new string that is a mirrored version of the original string."
},
{
"from": "gpt",
"value": "You can create a mirrored version of a string by reversing the order of its characters. In Python, this can be... |
Write a function that takes a list of strings and returns a list of all strings that are a substring of another string in the list. The function should return the strings in any order. | Here is the code to solve this problem:
```python
def find_substrings(words):
words = sorted(words, key=len)
result = []
for i in range(len(words)):
for j in range(i + 1, len(words)):
if words[i] in words[j]:
result.append(words[i])
break
return resul... | [
"assert find_substrings([\"leetcode\",\"et\",\"code\"])==[\"et\",\"code\"]",
"assert find_substrings([\"mass\",\"as\",\"hero\",\"superhero\"])==[\"as\",\"hero\"]",
"assert find_substrings([\"blue\",\"green\",\"bu\"])==[]"
] | You can achieve this by creating a function that iterates through each string in the list and checks if it is a substring of any other string in the list. Below is a Python implementation of this approach:
```python
def find_substrings(string_list):
substrings = []
for i in range(len(string_list)):
for... | 12,729 | [
{
"from": "human",
"value": "Write a function that takes a list of strings and returns a list of all strings that are a substring of another string in the list. The function should return the strings in any order."
},
{
"from": "gpt",
"value": "You can achieve this by creating a function that it... |
Write a python function to sort a list of software version strings in ascending order. The version strings are in the format 'x.y.z' where x, y, and z are integers. Some version strings may only have one or two parts. | Here is the code to solve this problem:
```python
from operator import itemgetter
def sort_versions(versions):
# check length if 1 to 100
if (len(versions) < 1) or (len(versions) > 100): return
#check if string
for items in versions:
if not type(items) is str: return
# make input "versi... | [
"assert sort_versions([\"1.10.0\", \"1\", \"1.2\", \"1.2.1\", \"9.9\", \"9.9.9\"]) == [\"1\", \"1.2\", \"1.2.1\", \"1.10.0\", \"9.9\", \"9.9.9\"]",
"assert sort_versions([\"2.0\", \"1.1.1\", \"1.0.0\", \"1\", \"3.2.1\"]) == [\"1\", \"1.0.0\", \"1.1.1\", \"2.0\", \"3.2.1\"]",
"assert sort_versions([\"5.5\", \"5\... | To sort a list of software version strings in ascending order, we can define a Python function that splits each version string into its components (x, y, and z), converts them to integers, and then sorts the list based on these integer tuples.
Here is a Python function that implements this logic:
```python
def sort_v... | 12,730 | [
{
"from": "human",
"value": "Write a python function to sort a list of software version strings in ascending order. The version strings are in the format 'x.y.z' where x, y, and z are integers. Some version strings may only have one or two parts."
},
{
"from": "gpt",
"value": "To sort a list of ... |
Write a function to find the number of occurrences of each character in a string and return a dictionary with the character as the key and the number of occurrences as the value. | Here is the code to solve this problem:
```python
def count_chars(string):
char_dict = {}
for char in string:
if char in char_dict:
char_dict[char] += 1
else:
char_dict[char] = 1
return char_dict
``` | [
"assert count_chars(\"python\") == {'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1}",
"assert count_chars(\"hello\") == {'h': 1, 'e': 1, 'l': 2, 'o': 1}",
"assert count_chars(\"programming\") == {'p': 1, 'r': 2, 'o': 1, 'g': 2, 'a': 1, 'm': 2, 'i': 1, 'n': 1}"
] | You can create a function in Python that counts the occurrences of each character in a given string and returns a dictionary with characters as keys and their counts as values. Here's one way to implement this:
```python
def character_count(s: str) -> dict:
# Create an empty dictionary to store the counts
coun... | 12,731 | [
{
"from": "human",
"value": "Write a function to find the number of occurrences of each character in a string and return a dictionary with the character as the key and the number of occurrences as the value."
},
{
"from": "gpt",
"value": "You can create a function in Python that counts the occur... |
Write a Python function to find the n'th number in the Look-and-Say sequence. The Look-and-Say sequence starts with "1" and each subsequent number is derived by describing the previous number in terms of consecutive digits. For example, starting with "1", the sequence is as follows: 1, 11, 21, 1211, 111221, 312211, 131... | Here is the code to solve this problem:
```python
def look_and_say(n):
s = '1'
for _ in range(n - 1):
s = ''.join(str(len(list(group))) + digit for digit, group in itertools.groupby(s))
return int(s)
import itertools
# Test cases
print(look_and_say(1)) # 1
print(look_and_say(2)) # 11
print(look... | [
"assert look_and_say(1) == 1",
"assert look_and_say(2) == 11",
"assert look_and_say(4) == 1211",
"assert look_and_say(5) == 111221",
"assert look_and_say(3) == 21"
] | The Look-and-Say sequence is a sequence of numbers where each term is generated by describing the previous term. To generate the n-th term in this sequence, we can create a function that performs the following steps:
1. Start with the initial term "1".
2. Iterate to generate each subsequent term by reading the previou... | 12,732 | [
{
"from": "human",
"value": "Write a Python function to find the n'th number in the Look-and-Say sequence. The Look-and-Say sequence starts with \"1\" and each subsequent number is derived by describing the previous number in terms of consecutive digits. For example, starting with \"1\", the sequence is as ... |
Write a function to check if a given string is a valid binary tree serialization. The serialization format is preorder traversal, where each node is either a digit (1-9) or '#' for a null node. The function should return True if the serialization is valid, and False otherwise. | Here is the code to solve this problem:
```python
def isValidBinaryTree(preorder: str) -> bool:
stack = []
preorder = preorder.split(',')
for node in preorder:
while stack and node == '#' and stack[-1] == '#':
stack.pop()
if not stack:
return False
... | [
"assert isValidBinaryTree(\"9,#,#\") == True",
"assert isValidBinaryTree(\"1,#\") == False",
"assert isValidBinaryTree(\"9,3,4,#,#,1,#,#,2,#,6,#,#\") == True",
"assert isValidBinaryTree(\"1,#,#,#\") == False",
"assert isValidBinaryTree(\"9,#,#,1\") == False"
] | To check if a given string is a valid binary tree serialization in preorder format, we can approach the problem by using the concept of a balance between the number of nodes and null nodes ('#'). Here’s how we can do it step by step:
1. Each non-null node consumes one slot in the serialization.
2. Each non-null node a... | 12,733 | [
{
"from": "human",
"value": "Write a function to check if a given string is a valid binary tree serialization. The serialization format is preorder traversal, where each node is either a digit (1-9) or '#' for a null node. The function should return True if the serialization is valid, and False otherwise."
... |
Write a function to convert a given decimal number to a binary string with 'db' prefix and suffix. | Here is the code to solve this problem:
```python
def decimal_to_binary_with_db(decimal_number):
binary_string = bin(decimal_number)[2:]
return "db" + binary_string + "db"
``` | [
"assert decimal_to_binary_with_db(15) == \"db1111db\"",
"assert decimal_to_binary_with_db(32) == \"db100000db\"",
"assert decimal_to_binary_with_db(255) == \"db11111111db\""
] | You can create a function in Python that converts a decimal number to a binary string with 'db' as a prefix and suffix. Here's a simple implementation of such a function:
```python
def decimal_to_binary_with_db_prefix_suffix(decimal_number):
# Check if the input is a valid integer
if not isinstance(decimal_num... | 12,734 | [
{
"from": "human",
"value": "Write a function to convert a given decimal number to a binary string with 'db' prefix and suffix."
},
{
"from": "gpt",
"value": "You can create a function in Python that converts a decimal number to a binary string with 'db' as a prefix and suffix. Here's a simple i... |
Write a function to check if a given string is a valid password. A valid password must satisfy the following conditions:
1. The password must be at least 8 characters long.
2. The password must contain at least one uppercase letter, one lowercase letter, one digit, and one special character.
3. The password must not co... | Here is the code to solve this problem:
```python
import re
def check_password(password):
if len(password) < 8:
return False
if not re.search("[a-z]", password):
return False
if not re.search("[A-Z]", password):
return False
if not re.search("[0-9]", password):
return F... | [
"assert check_password(\"Password123!\") == True",
"assert check_password(\"Passw0rd@\") == True",
"assert check_password(\"Pass123\") == False",
"assert check_password(\"pass@123\") == False",
"assert check_password(\"password\") == False"
] | Sure! Below is a Python function that checks if a given string is a valid password according to the specified conditions.
```python
import re
def is_valid_password(password):
# Check if the password is at least 8 characters long
if len(password) < 8:
return False
# Check if the password conta... | 12,735 | [
{
"from": "human",
"value": "Write a function to check if a given string is a valid password. A valid password must satisfy the following conditions:\n1. The password must be at least 8 characters long.\n2. The password must contain at least one uppercase letter, one lowercase letter, one digit, and one spe... |
Write a function to find the number of unique paths in a grid from the top-left corner to the bottom-right corner. Movement is restricted to right and down only. | Here is the code to solve this problem:
```python
def find_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 find_unique_paths(3, 2) == 3",
"assert find_unique_paths(3, 3) == 6",
"assert find_unique_paths(5, 5) == 70"
] | To find the number of unique paths in a grid from the top-left corner (0, 0) to the bottom-right corner (m-1, n-1) where movement is restricted to right and down, you can use a combinatorial approach or a dynamic programming approach.
Here, I will provide a Python function using the dynamic programming approach. The ... | 12,736 | [
{
"from": "human",
"value": "Write a function to find the number of unique paths in a grid from the top-left corner to the bottom-right corner. Movement is restricted to right and down only."
},
{
"from": "gpt",
"value": "To find the number of unique paths in a grid from the top-left corner (0, ... |
Write a python function to calculate the number of possible decodings of a given digit sequence. A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1, 'B' -> 2, ..., 'Z' -> 26. Given a non-empty string containing only digits, determine the total number of ways to decod... | Here is the code to solve this problem:
```python
def count_decodings(s):
if not s or s[0] == '0':
return 0
n = len(s)
dp = [0] * (n + 1)
dp[0], dp[1] = 1, 1
for i in range(2, n + 1):
if s[i-1] > '0':
dp[i] = dp[i-1]
if s[i-2] == '1' or (s[i-2] == '2' and s[i-1] ... | [
"assert count_decodings(\"226\") == 3",
"assert count_decodings(\"06\") == 0",
"assert count_decodings(\"12\") == 2",
"assert count_decodings(\"0\") == 0"
] | You can solve this problem using dynamic programming. The idea is to keep track of the number of ways to decode the string up to each position. Here’s a step-by-step approach and the corresponding Python function to achieve this:
1. **Initialization**: Create an array `dp` where `dp[i]` will represent the number of wa... | 12,737 | [
{
"from": "human",
"value": "Write a python function to calculate the number of possible decodings of a given digit sequence. A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1, 'B' -> 2, ..., 'Z' -> 26. Given a non-empty string containing only digits, de... |
Write a function that reverses a list in place. Do not allocate extra memory for a new list. | Here is the code to solve this problem:
```python
def reverseList(lst):
left = 0
right = len(lst) - 1
while left < right:
lst[left], lst[right] = lst[right], lst[left]
left += 1
right -= 1
return lst
``` | [
"assert reverseList([1,2,3,4,5]) == [5,4,3,2,1]",
"assert reverseList([10,20,30,40]) == [40,30,20,10]",
"assert reverseList([\"a\",\"b\",\"c\"]) == [\"c\",\"b\",\"a\"]"
] | Certainly! Below is a Python function that reverses a list in place, without allocating extra memory for a new list. This function uses a two-pointer approach to swap the elements from the start and the end of the list until it reaches the middle.
```python
def reverse_list(lst):
left = 0
right = len(lst) - 1
... | 12,738 | [
{
"from": "human",
"value": "Write a function that reverses a list in place. Do not allocate extra memory for a new list."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that reverses a list in place, without allocating extra memory for a new list. This function uses a two-p... |
Write a python function to find the number of ways to reach the last cell of a grid from the first cell using only allowed moves. | Here is the code to solve this problem:
```python
def grid_ways(N, M):
if N == 1 or M == 1:
return 1
return grid_ways(N-1, M) + grid_ways(N, M-1)
``` | [
"assert grid_ways(1, 10) == 1",
"assert grid_ways(2, 3) == 3",
"assert grid_ways(3, 3) == 6"
] | To solve the problem of finding the number of ways to reach the last cell of a grid from the first cell using only allowed moves, we can use dynamic programming. The allowed moves typically involve moving either right or down in the grid.
Here is a Python function that accomplishes this task:
```python
def unique_pa... | 12,739 | [
{
"from": "human",
"value": "Write a python function to find the number of ways to reach the last cell of a grid from the first cell using only allowed moves."
},
{
"from": "gpt",
"value": "To solve the problem of finding the number of ways to reach the last cell of a grid from the first cell us... |
Write a python function that takes a list of integers and returns a new list with the even numbers from the original list, sorted in ascending order. | Here is the code to solve this problem:
```python
def even_sort(nums):
even_nums = [num for num in nums if num % 2 == 0]
even_nums.sort()
return even_nums
``` | [
"assert even_sort([13, 11, 9, 7, 5, 3, 1]) == []",
"assert even_sort([4, 2, 3, 7, 8, 9, 1]) == [2, 4, 8]",
"assert even_sort([12, 10, 11, 8, 7, 6]) == [6, 8, 10, 12]"
] | You can create a Python function to filter out the even numbers from a list of integers and return them sorted in ascending order. Here’s how you can do it:
```python
def get_sorted_even_numbers(numbers):
# Filter even numbers from the input list
even_numbers = [num for num in numbers if num % 2 == 0]
# So... | 12,740 | [
{
"from": "human",
"value": "Write a python function that takes a list of integers and returns a new list with the even numbers from the original list, sorted in ascending order."
},
{
"from": "gpt",
"value": "You can create a Python function to filter out the even numbers from a list of integer... |
Write a function to find the shortest path between two nodes in a graph using Breadth-First Search (BFS). | Here is the code to solve this problem:
```python
from collections import deque
def shortest_path_bfs(graph, start, end):
queue = deque([(start, [start])])
visited = set()
while queue:
(node, path) = queue.popleft()
if node not in visited:
if node == end:
return... | [
"assert shortest_path_bfs({0: [1], 1: [2], 2: [3], 3: [4]}, 0, 4) == [0, 1, 2, 3, 4]",
"assert shortest_path_bfs({0: [1, 2], 1: [2], 2: [3], 3: [1, 2]}, 0, 1) == [0, 1]",
"assert shortest_path_bfs({0: [1, 2], 1: [2], 2: [3], 3: [1, 2]}, 0, 3) == [0, 2, 3]"
] | Certainly! Here is a Python implementation of a function that uses Breadth-First Search (BFS) to find the shortest path between two nodes in an unweighted graph. The graph is represented using an adjacency list.
```python
from collections import deque
def bfs_shortest_path(graph, start, goal):
"""
Find the sh... | 12,741 | [
{
"from": "human",
"value": "Write a function to find the shortest path between two nodes in a graph using Breadth-First Search (BFS)."
},
{
"from": "gpt",
"value": "Certainly! Here is a Python implementation of a function that uses Breadth-First Search (BFS) to find the shortest path between tw... |
Write a python function that takes a string as input and returns the string with its digits sorted in ascending order. | Here is the code to solve this problem:
```python
def sort_digits(s):
digits = sorted([c for c in s if c.isdigit()])
return ''.join([c if not c.isdigit() else digits.pop(0) for c in s])
``` | [
"assert sort_digits(\"564321\") == \"123456\"",
"assert sort_digits(\"abc123\") == \"abc123\"",
"assert sort_digits(\"a3b2c1\") == \"a1b2c3\""
] | You can achieve this by defining a function that extracts the digits from the input string, sorts them, and then reconstructs the string with the sorted digits. Here’s a sample implementation:
```python
def sort_digits_in_string(input_string):
# Extract digits from the input string
digits = [char for char in i... | 12,742 | [
{
"from": "human",
"value": "Write a python function that takes a string as input and returns the string with its digits sorted in ascending order."
},
{
"from": "gpt",
"value": "You can achieve this by defining a function that extracts the digits from the input string, sorts them, and then reco... |
Write a python function to determine if a given string can be segmented into a space-separated sequence of one or more dictionary words. | Here is the code to solve this problem:
```python
def can_segment(s, wordDict):
wordSet = set(wordDict)
dp = [False] * (len(s) + 1)
dp[0] = True
for i in range(1, len(s) + 1):
for j in range(i):
if dp[j] and s[j:i] in wordSet:
dp[i] = True
break
r... | [
"assert can_segment(\"catsandog\", [\"cats\", \"dog\", \"sand\", \"and\", \"cat\"]) == False",
"assert can_segment(\"leetcode\", [\"leet\", \"code\"]) == True",
"assert can_segment(\"applepenapple\", [\"apple\", \"pen\"]) == True"
] | To determine if a given string can be segmented into a space-separated sequence of one or more dictionary words, we can use a recursive approach or dynamic programming. A common and efficient method for this problem is to use dynamic programming to keep track of possible segmentations of the string.
Here's a Python fu... | 12,743 | [
{
"from": "human",
"value": "Write a python function to determine if a given string can be segmented into a space-separated sequence of one or more dictionary words."
},
{
"from": "gpt",
"value": "To determine if a given string can be segmented into a space-separated sequence of one or more dict... |
Write a function that takes in a string and returns the number of vowels in it. The vowels are 'a', 'e', 'i', 'o', 'u'. The string can contain both uppercase and lowercase letters. | Here is the code to solve this problem:
```python
def vowel_count(str):
vowels = ['a', 'e', 'i', 'o', 'u']
count = 0
for char in str:
if char.lower() in vowels:
count += 1
return count
``` | [
"assert vowel_count('Hello World') == 3",
"assert vowel_count('abcdefghijklmnopqrstuvwxyz') == 5",
"assert vowel_count('AEIOU') == 5",
"assert vowel_count('Python') == 1"
] | You can create a function in Python to count the number of vowels in a given string. Here is a simple implementation:
```python
def count_vowels(s):
# Define the set of vowels
vowels = "aeiouAEIOU"
# Initialize a counter
count = 0
# Iterate through each character in the string
for cha... | 12,744 | [
{
"from": "human",
"value": "Write a function that takes in a string and returns the number of vowels in it. The vowels are 'a', 'e', 'i', 'o', 'u'. The string can contain both uppercase and lowercase letters."
},
{
"from": "gpt",
"value": "You can create a function in Python to count the number... |
Write a python function to find the Longest Common Subsequence (LCS) of two sequences. | Here is the code to solve this problem:
```python
def LongestCommonSubsequence(X, Y):
m = len(X)
n = len(Y)
L = [[None]*(n + 1) for i in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
L[i][j] = 0
elif X[i-1] == Y[j-1]:
... | [
"assert LongestCommonSubsequence(\"ABCBDAB\", \"BDCAB\") == 4",
"assert LongestCommonSubsequence(\"XMJYAUZ\", \"MZJAWXU\") == 4",
"assert LongestCommonSubsequence(\"AGGTAB\", \"GXTXAYB\") == 4"
] | Certainly! The Longest Common Subsequence (LCS) problem is a well-known problem in computer science. The LCS of two sequences is the longest subsequence that appears in both sequences in the same order.
Here's a Python function that uses dynamic programming to find the LCS of two sequences:
```python
def longest_com... | 12,745 | [
{
"from": "human",
"value": "Write a python function to find the Longest Common Subsequence (LCS) of two sequences."
},
{
"from": "gpt",
"value": "Certainly! The Longest Common Subsequence (LCS) problem is a well-known problem in computer science. The LCS of two sequences is the longest subseque... |
Write a python function to find the largest unique number in a list of integers. | Here is the code to solve this problem:
```python
def largest_unique_number(nums):
dict1={}
for i in nums:
dict1[i]=dict1.get(i,0)+1
list1=list(dict1.keys())
list1.sort(reverse=True)
for i in list1:
if dict1[i]==1:
return i
return -1
``` | [
"assert largest_unique_number([2, 2, 2, 2, 2, 2]) == -1",
"assert largest_unique_number([1, 2, 3, 4, 5]) == 5",
"assert largest_unique_number([5, 7, 3, 9, 4, 9, 7, 3, 2]) == 5"
] | Certainly! You can create a function that first filters out duplicates from the list to keep only unique numbers, and then finds the maximum from that filtered list. Here's a simple implementation of such a function:
```python
def largest_unique_number(numbers):
# Create a set to find unique numbers
unique_num... | 12,746 | [
{
"from": "human",
"value": "Write a python function to find the largest unique number in a list of integers."
},
{
"from": "gpt",
"value": "Certainly! You can create a function that first filters out duplicates from the list to keep only unique numbers, and then finds the maximum from that filt... |
Create a function that takes a string as input and returns a new string with all the repeated characters removed. The order of the characters in the original string should be preserved in the output. | Here is the code to solve this problem:
```python
def remove_repeated_characters(input_string):
result = ''
for char in input_string:
if input_string.count(char) == 1:
result += char
return ''.join(sorted(set(input_string), key=input_string.index))
# Simplified and optimized version
de... | [
"assert remove_repeated_characters(\"programming\") == \"progamin\"",
"assert remove_repeated_characters(\"hello\") == \"helo\"",
"assert remove_repeated_characters(\"python\") == \"python\""
] | You can achieve this by creating a function in Python that uses a set to track characters that have already been seen, and a list to collect the unique characters in their original order. Here’s a simple implementation of such a function:
```python
def remove_repeated_characters(input_string):
seen = set()
res... | 12,747 | [
{
"from": "human",
"value": "Create a function that takes a string as input and returns a new string with all the repeated characters removed. The order of the characters in the original string should be preserved in the output."
},
{
"from": "gpt",
"value": "You can achieve this by creating a f... |
Write a python function to find the number of unique characters in a given string. | Here is the code to solve this problem:
```python
def unique_ctr(str):
unique_chars = set(str)
return len(unique_chars)
``` | [
"assert unique_ctr('abc') == 3",
"assert unique_ctr('aabbcc') == 3",
"assert unique_ctr('Python') == 6"
] | You can create a Python function to find the number of unique characters in a given string by using a set to store the characters. Here's how you can do it:
```python
def count_unique_characters(input_string):
# Use a set to store unique characters
unique_characters = set(input_string)
# Return the nu... | 12,748 | [
{
"from": "human",
"value": "Write a python function to find the number of unique characters in a given string."
},
{
"from": "gpt",
"value": "You can create a Python function to find the number of unique characters in a given string by using a set to store the characters. Here's how you can do ... |
Write a python function to check if a list of integers can be divided into two groups such that the sum of one group is a multiple of a given integer k. | Here is the code to solve this problem:
```python
from collections import Counter
def can_divide_into_groups(nums, k):
freq = Counter()
for val in nums:
freq[val % k] += 1
if freq[0] % 2 == 1:
return False
del freq[0]
for remainder in freq:
if freq[remainder] != freq[k - re... | [
"assert can_divide_into_groups([1, 2, 3, 4, 5, 6], 10) == False",
"assert can_divide_into_groups([1, 2, 3, 4, 5, 6], 7) == True",
"assert can_divide_into_groups([-10, 10], 2) == True",
"assert can_divide_into_groups([1, 2, 3, 4, 5, 10, 6, 7, 8, 9], 5) == True",
"assert can_divide_into_groups([-1, 1, -2, 2, ... | To determine if a list of integers can be divided into two groups such that the sum of one group is a multiple of a given integer \( k \), we can utilize a brute-force approach or a more efficient method leveraging dynamic programming.
Here's a Python function that implements a dynamic programming solution to tackle t... | 12,749 | [
{
"from": "human",
"value": "Write a python function to check if a list of integers can be divided into two groups such that the sum of one group is a multiple of a given integer k."
},
{
"from": "gpt",
"value": "To determine if a list of integers can be divided into two groups such that the sum... |
Write a python function to check whether the given sentence is a pangram or not. 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 check_pangram(sentence):
alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in alphabet:
if char not in sentence.lower():
return False
return True
``` | [
"assert check_pangram(\"Hello world\") == False",
"assert check_pangram(\"The quick brown fox jumps over the lazy dog\") == True",
"assert check_pangram(\"Pack my box with five dozen liquor jugs\") == True"
] | Certainly! Below is a Python function that checks whether a given sentence is a pangram or not. The function converts the sentence to lowercase to ensure the check is case-insensitive, and then it uses a set to keep track of the letters of the alphabet that have been seen.
```python
def is_pangram(sentence):
# Def... | 12,750 | [
{
"from": "human",
"value": "Write a python function to check whether the given sentence is a pangram or not. 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 whether a given ... |
Write a python function to find the number of islands in a given grid. An island is surrounded by water and is 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 number_of_islands(grid):
if not grid:
return 0
def dfs(i, j):
if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j] == '0':
return
grid[i][j] = '0'
dfs(i+1, j)
dfs(i-1, j)
dfs(i, j+1)
... | [
"assert number_of_islands([[\"1\",\"1\",\"1\",\"1\",\"0\"],[\"1\",\"1\",\"0\",\"1\",\"0\"],[\"1\",\"1\",\"0\",\"0\",\"0\"],[\"0\",\"0\",\"0\",\"0\",\"0\"]]) == 1",
"assert number_of_islands([[\"1\",\"1\",\"0\",\"0\",\"0\"],[\"1\",\"1\",\"0\",\"0\",\"0\"],[\"0\",\"0\",\"1\",\"0\",\"0\"],[\"0\",\"0\",\"0\",\"1\",\"... | To find the number of islands in a given grid, we can use Depth First Search (DFS) to explore the grid. An island is represented by '1' (land) and water is represented by '0'. When we find a '1', we will increment our island count and perform a DFS to mark all connected '1's as visited.
Here is a Python function that ... | 12,751 | [
{
"from": "human",
"value": "Write a python function to find the number of islands in a given grid. An island is surrounded by water and is 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 check if a number is a Happy number. 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 in a cycle wh... | Here is the code to solve this problem:
```python
def check_happy_number(num):
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 num not in seen:
seen.add(num)
num... | [
"assert check_happy_number(2) == False",
"assert check_happy_number(7) == True",
"assert check_happy_number(19) == True"
] | To determine if a number is a Happy number, we can write a function that follows the defined process. We'll keep track of the numbers we've seen to detect cycles, and we'll check if we eventually reach 1. Here's a Python implementation of the function:
```python
def is_happy(n):
def get_next(num):
return s... | 12,752 | [
{
"from": "human",
"value": "Write a function to check if a number is a Happy number. 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 s... |
Create a function that finds the number of occurrences of a specific digit in a given integer array. The function should return the maximum number of occurrences of any digit (0-9) found in any number within the array. | Here is the code to solve this problem:
```python
from collections import defaultdict
def max_digit_occurrence(A):
str_A = [str(a) for a in A]
dict_occurrence = defaultdict(int)
for num in str_A:
for digit in num:
dict_occurrence[digit] += 1
return max(dict_occurrence.values()) if ... | [
"assert max_digit_occurrence([223, 4567, 1233])==3",
"assert max_digit_occurrence([123, 456, 789])==1",
"assert max_digit_occurrence([111, 22, 333, 4444])==4"
] | Here's a Python function that finds the maximum occurrences of any digit (0-9) in a given integer array. The function iterates over each number in the array, counts the occurrences of each digit in that number, and keeps track of the maximum found.
```python
def max_digit_occurrences(arr):
from collections import ... | 12,753 | [
{
"from": "human",
"value": "Create a function that finds the number of occurrences of a specific digit in a given integer array. The function should return the maximum number of occurrences of any digit (0-9) found in any number within the array."
},
{
"from": "gpt",
"value": "Here's a Python f... |
Write a python function to remove all elements from a list that are less than a specified minimum value. | Here is the code to solve this problem:
```python
def filter_list(numbers, min_val):
return [num for num in numbers if num >= min_val]
``` | [
"assert filter_list([100, 200, 300, 400, 500], 500) == [500]",
"assert filter_list([1, 2, 3, 4, 5], 3) == [3, 4, 5]",
"assert filter_list([10, 20, 30, 40, 50], 25) == [30, 40, 50]"
] | You can create a Python function that takes a list and a minimum value as inputs and returns a new list containing only the elements that are greater than or equal to the specified minimum value. Here's one way to implement this function:
```python
def remove_elements_below_minimum(lst, min_value):
"""Remove all e... | 12,754 | [
{
"from": "human",
"value": "Write a python function to remove all elements from a list that are less than a specified minimum value."
},
{
"from": "gpt",
"value": "You can create a Python function that takes a list and a minimum value as inputs and returns a new list containing only the element... |
Write a python function to check for the unique characters in a given string. | Here is the code to solve this problem:
```python
def check_unique_characters(str):
char_set = [False] * 256
for i in str:
val = ord(i)
if char_set[val]:
return False
char_set[val] = True
return True
``` | [
"assert check_unique_characters(\"abcdefg\") == True",
"assert check_unique_characters(\"hello\") == False",
"assert check_unique_characters(\"world\") == True"
] | You can create a Python function to check for unique characters in a given string by using a set to keep track of the characters you've seen so far. Here's a simple implementation:
```python
def has_unique_characters(input_string):
# Convert the input string to lowercase to ensure case insensitivity
input_stri... | 12,755 | [
{
"from": "human",
"value": "Write a python function to check for the unique characters in a given string."
},
{
"from": "gpt",
"value": "You can create a Python function to check for unique characters in a given string by using a set to keep track of the characters you've seen so far. Here's a ... |
Write a function to find the n-th triangular number. | Here is the code to solve this problem:
```python
def find_tri_num(n):
return n*(n + 1)//2
``` | [
"assert find_tri_num(6) == 21",
"assert find_tri_num(5) == 15",
"assert find_tri_num(4) == 10"
] | A triangular number is defined as the sum of the first n natural numbers. The n-th triangular number can be calculated using the formula:
\[
T(n) = \frac{n(n + 1)}{2}
\]
Here is a Python function that computes the n-th triangular number:
```python
def triangular_number(n):
if n < 1:
raise ValueError("n m... | 12,756 | [
{
"from": "human",
"value": "Write a function to find the n-th triangular number."
},
{
"from": "gpt",
"value": "A triangular number is defined as the sum of the first n natural numbers. The n-th triangular number can be calculated using the formula:\n\n\\[\nT(n) = \\frac{n(n + 1)}{2}\n\\]\n\nHe... |
Write a function to reverse the case of each character in a string. | Here is the code to solve this problem:
```python
def reverse_case(str1):
result = ""
for char in str1:
if char.isupper():
result += char.lower()
else:
result += char.upper()
return result
``` | [
"assert reverse_case(\"Hello\")==\"hELLO\"",
"assert reverse_case(\"Python3.9\")==\"pYTHON3.9\"",
"assert reverse_case(\"CoDe\")==\"cOdE\""
] | Certainly! You can reverse the case of each character in a string using Python. Below is a simple function that accomplishes this:
```python
def reverse_case(s):
# Use a list comprehension to iterate through each character
# and use the swapcase method to reverse the case
return ''.join(char.swapcase() for... | 12,757 | [
{
"from": "human",
"value": "Write a function to reverse the case of each character in a string."
},
{
"from": "gpt",
"value": "Certainly! You can reverse the case of each character in a string using Python. Below is a simple function that accomplishes this:\n\n```python\ndef reverse_case(s):\n ... |
Write a python function to check if a string is an anagram of a palindrome. | Here is the code to solve this problem:
```python
def check_anagram_palindrome(s):
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
odd_count = 0
for count in char_count.values():
if count % 2 != 0:
... | [
"assert check_anagram_palindrome(\"aabbcc\") == True",
"assert check_anagram_palindrome(\"aabb\") == True",
"assert check_anagram_palindrome(\"abc\") == False"
] | To determine if a string is an anagram of a palindrome, we need to assess the character frequencies in the string. A string can form a palindrome if at most one of its characters has an odd count (this accounts for the middle character in case of strings with an odd length).
Here's a Python function that implements t... | 12,758 | [
{
"from": "human",
"value": "Write a python function to check if a string is an anagram of a palindrome."
},
{
"from": "gpt",
"value": "To determine if a string is an anagram of a palindrome, we need to assess the character frequencies in the string. A string can form a palindrome if at most one... |
Write a function that takes a list of numbers and a target number, then returns the index of the first occurrence of the target number in the list. If the target number is not found, return -1. | Here is the code to solve this problem:
```python
def find_target_index(arr, target):
try:
return arr.index(target)
except ValueError:
return -1
``` | [
"assert find_target_index([1, 2, 3, 4, 5], 3)==2",
"assert find_target_index([1, 2, 3, 4, 5], 6)==-1",
"assert find_target_index([10, 20, 30, 40, 50], 40)==3"
] | Certainly! Below is a Python function that accomplishes the task of finding the index of the first occurrence of a target number in a list. If the target number is not present in the list, it returns -1.
```python
def find_first_occurrence(numbers, target):
for index, number in enumerate(numbers):
if numbe... | 12,759 | [
{
"from": "human",
"value": "Write a function that takes a list of numbers and a target number, then returns the index of the first occurrence of the target number in the list. If the target number is not found, return -1."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that... |
Write a python function that checks if a string is an anagram of a palindrome.
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.
A palindrome is a word, phrase, number, or other sequences of characters which reads the... | Here is the code to solve this problem:
```python
def is_anagram_palindrome(s):
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
odd_counts = 0
for count in char_count.values():
if count % 2 != 0:
... | [
"assert is_anagram_palindrome(\"carrace\") == True",
"assert is_anagram_palindrome(\"aabbcc\") == True",
"assert is_anagram_palindrome(\"abc\") == False",
"assert is_anagram_palindrome(\"aabbc\") == True",
"assert is_anagram_palindrome(\"hello\") == False"
] | To determine if a string is an anagram of a palindrome, we need to check the frequency of each character in the string. A string can be rearranged to form a palindrome if:
1. For strings of even length, all characters must occur an even number of times.
2. For strings of odd length, all characters except one must occu... | 12,760 | [
{
"from": "human",
"value": "Write a python function that checks if a string is an anagram of a palindrome.\n\nAn 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.\n\nA palindrome is a word, phrase, number, or ... |
Write a function that takes a list of integers and returns a new list with the integers sorted in descending order. However, even numbers should be placed before odd numbers while maintaining their sorted order. | Here is the code to solve this problem:
```python
def even_before_odd_sort(lst):
evens = sorted([i for i in lst if i % 2 == 0], reverse=True)
odds = sorted([i for i in lst if i % 2 != 0], reverse=True)
return evens + odds
``` | [
"assert even_before_odd_sort([7, 8, 1, 3, 4, 2]) == [8, 4, 2, 7, 3, 1]",
"assert even_before_odd_sort([10, 21, 4, 45, 66, 93]) == [66, 10, 4, 93, 45, 21]",
"assert even_before_odd_sort([5, 3, 2, 8, 1, 4]) == [8, 4, 2, 5, 3, 1]"
] | Certainly! Below is a Python function that takes a list of integers, sorts the even numbers in descending order, and then sorts the odd numbers in descending order as well. Finally, it combines them such that all even numbers come before the odd numbers.
```python
def sort_even_odd_desc(lst):
# Separate even and o... | 12,761 | [
{
"from": "human",
"value": "Write a function that takes a list of integers and returns a new list with the integers sorted in descending order. However, even numbers should be placed before odd numbers while maintaining their sorted order."
},
{
"from": "gpt",
"value": "Certainly! Below is a Py... |
Write a python function to find the product of all elements in a list. | Here is the code to solve this problem:
```python
def product(lst):
result = 1
for num in lst:
result *= num
return result
``` | [
"assert product([1, 2, 3, 4])==24",
"assert product([1, 2, 3])==6",
"assert product([4, 5, 6])==120"
] | Certainly! You can find the product of all elements in a list using a simple Python function. Here’s one way to do it using a loop:
```python
def product_of_elements(lst):
product = 1
for element in lst:
product *= element
return product
# Example usage:
numbers = [1, 2, 3, 4]
result = product_of_... | 12,762 | [
{
"from": "human",
"value": "Write a python function to find the product of all elements in a list."
},
{
"from": "gpt",
"value": "Certainly! You can find the product of all elements in a list using a simple Python function. Here’s one way to do it using a loop:\n\n```python\ndef product_of_elem... |
Write a function to convert a given string to an integer. The string represents a decimal number, which may include a negative sign '-' at the beginning. If the string cannot be converted into a valid integer, return 0. | Here is the code to solve this problem:
```python
def string_to_integer(s):
try:
return int(s)
except ValueError:
return 0
``` | [
"assert string_to_integer('-456') == -456",
"assert string_to_integer('0') == 0",
"assert string_to_integer('123') == 123",
"assert string_to_integer('') == 0",
"assert string_to_integer('abc') == 0",
"assert string_to_integer('123abc') == 0"
] | Certainly! Below is a Python function that implements the conversion of a string to an integer, handling the cases where the string may include a negative sign. If the conversion is not possible, it returns 0.
```python
def string_to_integer(s):
# Strip leading and trailing whitespace
s = s.strip()
# ... | 12,763 | [
{
"from": "human",
"value": "Write a function to convert a given string to an integer. The string represents a decimal number, which may include a negative sign '-' at the beginning. If the string cannot be converted into a valid integer, return 0."
},
{
"from": "gpt",
"value": "Certainly! Below... |
Write a function that takes a string as an argument and returns a new string where every character is repeated twice. | Here is the code to solve this problem:
```python
def double_letters(string):
result = ''
for char in string:
result += char * 2
return result
``` | [
"assert double_letters('hello') == 'hheelllloo'",
"assert double_letters('!@#') == '!!@@##'",
"assert double_letters('123') == '112233'"
] | You can create a function in Python that takes a string as input and returns a new string with each character repeated twice. Here’s a simple implementation of that function:
```python
def repeat_characters(input_string):
return ''.join(char * 2 for char in input_string)
# Example usage:
result = repeat_character... | 12,764 | [
{
"from": "human",
"value": "Write a function that takes a string as an argument and returns a new string where every character is repeated twice."
},
{
"from": "gpt",
"value": "You can create a function in Python that takes a string as input and returns a new string with each character repeated... |
Write a function to find the longest balanced parentheses string from the given string. | Here is the code to solve this problem:
```python
def longest_balanced_parentheses(s: str) -> int:
max_len = 0
stack = [-1]
for i, p in enumerate(s):
if p == '(':
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
... | [
"assert longest_balanced_parentheses(\"\") == 0",
"assert longest_balanced_parentheses(\"(()())\") == 6",
"assert longest_balanced_parentheses(\")()())\") == 4"
] | To find the longest balanced parentheses substring from a given string, you can use a stack-based approach or a dynamic programming method. However, using a stack is often more intuitive and efficient for this problem.
Here's a Python function that implements this approach:
```python
def longest_balanced_parentheses(... | 12,765 | [
{
"from": "human",
"value": "Write a function to find the longest balanced parentheses string from the given string."
},
{
"from": "gpt",
"value": "To find the longest balanced parentheses substring from a given string, you can use a stack-based approach or a dynamic programming method. However,... |
Write a python function to convert a given string to uppercase without using the built-in `upper()` function. | Here is the code to solve this problem:
```python
def to_upper(s):
upper_str = ""
for char in s:
if ord('a') <= ord(char) <= ord('z'):
upper_str += chr(ord(char) - 32)
else:
upper_str += char
return upper_str
``` | [
"assert to_upper(\"python\") == \"PYTHON\"",
"assert to_upper(\"hello\") == \"HELLO\"",
"assert to_upper(\"world\") == \"WORLD\""
] | You can achieve this by iterating through each character in the string and converting it to uppercase based on its ASCII value. Here's a function that does that:
```python
def to_uppercase(input_string):
uppercase_string = ""
for char in input_string:
# Check if the character is a lowercase letter
... | 12,766 | [
{
"from": "human",
"value": "Write a python function to convert a given string to uppercase without using the built-in `upper()` function."
},
{
"from": "gpt",
"value": "You can achieve this by iterating through each character in the string and converting it to uppercase based on its ASCII value... |
Write a function to rearrange the elements of a list such that all even elements appear before all odd elements. | Here is the code to solve this problem:
```python
def even_odd_rearrange(nums):
even_nums = [num for num in nums if num % 2 == 0]
odd_nums = [num for num in nums if num % 2 != 0]
result = even_nums + odd_nums
return result
``` | [
"assert even_odd_rearrange([7, 8, 9, 10, 11, 12, 13, 14]) == [8, 10, 12, 14, 7, 9, 11, 13]",
"assert even_odd_rearrange([1, 2, 3, 4, 5, 6]) == [2, 4, 6, 1, 3, 5]",
"assert even_odd_rearrange([16, 15, 14, 13, 12, 11, 10, 9, 8, 7]) == [16, 14, 12, 10, 8, 15, 13, 11, 9, 7]"
] | You can accomplish this by defining a function in Python that rearranges the elements of a list so that all even numbers come before all odd numbers. Here's a simple implementation of such a function:
```python
def rearrange_even_odd(lst):
# Create two lists to hold even and odd numbers
evens = []
odds = [... | 12,767 | [
{
"from": "human",
"value": "Write a function to rearrange the elements of a list such that all even elements appear before all odd elements."
},
{
"from": "gpt",
"value": "You can accomplish this by defining a function in Python that rearranges the elements of a list so that all even numbers co... |
Write a function that checks if a given string can be formed by rearranging the characters of another string. The function should return True if the string can be formed, and False otherwise. | Here is the code to solve this problem:
```python
def can_form_string(str1, str2):
return sorted(str1) == sorted(str2)
``` | [
"assert can_form_string('world', 'dlrow') == True",
"assert can_form_string('hello', 'lleho') == True",
"assert can_form_string('data', 'atat') == False",
"assert can_form_string('python', 'typhon') == True",
"assert can_form_string('java', 'avaj') == True"
] | You can create a function in Python that checks if one string can be formed by rearranging the characters of another string by comparing the character counts of both strings. Here is a simple implementation of this:
```python
def can_form_string(s1, s2):
# Remove spaces and convert both strings to lowercase for co... | 12,768 | [
{
"from": "human",
"value": "Write a function that checks if a given string can be formed by rearranging the characters of another string. The function should return True if the string can be formed, and False otherwise."
},
{
"from": "gpt",
"value": "You can create a function in Python that che... |
Write a function that takes a list of numbers and returns a new list with the numbers sorted in ascending order using the quicksort algorithm. | Here is the code to solve this problem:
```python
def quicksort(nums):
if len(nums) <= 1:
return nums
else:
pivot = nums[0]
less = [i for i in nums[1:] if i <= pivot]
greater = [i for i in nums[1:] if i > pivot]
return quicksort(less) + [pivot] + quicksort(greater)
``` | [
"assert quicksort([3, 6, 8, 10, 1, 2, 1]) == [1, 1, 2, 3, 6, 8, 10]",
"assert quicksort([5, 1, 4, 2, 8]) == [1, 2, 4, 5, 8]",
"assert quicksort([15, 3, 9, 12, 2, 8, 10]) == [2, 3, 8, 9, 10, 12, 15]"
] | Certainly! Here's a Python function that implements the quicksort algorithm to sort a list of numbers in ascending order:
```python
def quicksort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[len(arr) // 2] # Choose the middle element as pivot
left = [x for x in arr if x < pivot... | 12,769 | [
{
"from": "human",
"value": "Write a function that takes a list of numbers and returns a new list with the numbers sorted in ascending order using the quicksort algorithm."
},
{
"from": "gpt",
"value": "Certainly! Here's a Python function that implements the quicksort algorithm to sort a list of... |
Write a function to find the maximum rectangular area in a histogram. The histogram is represented as a list of non-negative integers, where each element represents the height of a bar in the histogram. The width of each bar is 1. Your function should return the maximum area of rectangle in the histogram. | Here is the code to solve this problem:
```python
def maxHistogramArea(heights):
stack = list()
max_area = 0
index = 0
while index < len(heights):
if (not stack) or (heights[stack[-1]] <= heights[index]):
stack.append(index)
index += 1
else:
top_of_st... | [
"assert maxHistogramArea([2,1,5,6,2,3])==10",
"assert maxHistogramArea([2,4])==4",
"assert maxHistogramArea([1,2,3,4,5])==9"
] | You can solve the problem of finding the maximum rectangular area in a histogram using a stack-based approach. Here's a Python function that implements this algorithm:
```python
def largest_rectangle_area(heights):
# Initialize a stack and a variable to store the maximum area
stack = []
max_area = 0
# ... | 12,770 | [
{
"from": "human",
"value": "Write a function to find the maximum rectangular area in a histogram. The histogram is represented as a list of non-negative integers, where each element represents the height of a bar in the histogram. The width of each bar is 1. Your function should return the maximum area of ... |
Write a python function to find the maximum length of a pair chain from a list of pairs. A pair chain is a sequence of pairs where the second element of each pair is less than the first element of the next pair. The function should return the length of the longest possible pair chain. | Here is the code to solve this problem:
```python
def findLongestPairChain(pairs):
# Sort the pairs based on the second element of each pair
pairs.sort(key=lambda x: x[1])
end = pairs[0][1]
res = 1
for i in range(1, len(pairs)):
c, d = pairs[i]
if c > end:
res += 1
... | [
"assert findLongestPairChain([[1,2],[2,3],[3,4]]) == 2",
"assert findLongestPairChain([[1,2],[7,8],[4,5]]) == 3",
"assert findLongestPairChain([[1,4],[2,3],[3,4]]) == 1"
] | To solve the problem of finding the maximum length of a pair chain from a list of pairs, we can use a dynamic programming approach similar to the Longest Increasing Subsequence problem. Here’s how we can implement this in Python:
1. First, we need to sort the list of pairs based on the first element of each pair (and ... | 12,771 | [
{
"from": "human",
"value": "Write a python function to find the maximum length of a pair chain from a list of pairs. A pair chain is a sequence of pairs where the second element of each pair is less than the first element of the next pair. The function should return the length of the longest possible pair ... |
Write a python function to find the first repeating element in a given list of numbers. | Here is the code to solve this problem:
```python
def first_repeating(arr):
seen = set()
for i in arr:
if i in seen:
return i
else:
seen.add(i)
return -1
``` | [
"assert first_repeating([6,7,8,9,6]) == 6",
"assert first_repeating([1,2,3,2,1]) == 2",
"assert first_repeating([4,5,6,7,8]) == -1"
] | Certainly! You can find the first repeating element in a list by keeping track of the elements you've seen as you iterate through the list. Here's a simple Python function that accomplishes this:
```python
def first_repeating_element(numbers):
seen = set()
for number in numbers:
if number in seen:
... | 12,772 | [
{
"from": "human",
"value": "Write a python function to find the first repeating element in a given list of numbers."
},
{
"from": "gpt",
"value": "Certainly! You can find the first repeating element in a list by keeping track of the elements you've seen as you iterate through the list. Here's a... |
Write a function to find the longest palindrome substring in a given string. | Here is the code to solve this problem:
```python
def longest_palindrome_substring(s):
if len(s) < 2:
return s
start = 0
max_len = 1
def expand_around_center(left, right):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
r... | [
"assert longest_palindrome_substring(\"babad\") == \"bab\"",
"assert longest_palindrome_substring(\"ac\") == \"a\"",
"assert longest_palindrome_substring(\"a\") == \"a\""
] | Sure! Here's a Python function to find the longest palindromic substring in a given string using a method known as "expand around center." This method is efficient and has a time complexity of O(n^2).
```python
def longest_palindrome(s: str) -> str:
if len(s) == 0:
return ""
start, end = 0, 0
... | 12,773 | [
{
"from": "human",
"value": "Write a function to find the longest palindrome substring in a given string."
},
{
"from": "gpt",
"value": "Sure! Here's a Python function to find the longest palindromic substring in a given string using a method known as \"expand around center.\" This method is eff... |
Write a python function to find the number of times a specific word appears in a list of strings. | Here is the code to solve this problem:
```python
def count_word_in_list(lst, word):
count = 0
for w in lst:
if w == word:
count += 1
return count
``` | [
"assert count_word_in_list([\"hello\", \"world\", \"hello\"], \"hello\") == 2",
"assert count_word_in_list([\"python\", \"java\", \"python\"], \"python\") == 2",
"assert count_word_in_list([\"one\", \"two\", \"three\"], \"four\") == 0"
] | Certainly! You can create a function that takes a list of strings and a specific word, then counts how many times that word appears in the list. Here's a simple implementation in Python:
```python
def count_word_occurrences(strings_list, target_word):
# Initialize a counter for the occurrences
count = 0
... | 12,774 | [
{
"from": "human",
"value": "Write a python function to find the number of times a specific word appears in a list of strings."
},
{
"from": "gpt",
"value": "Certainly! You can create a function that takes a list of strings and a specific word, then counts how many times that word appears in the... |
Write a python function that converts a given string into a string where each character is replaced by a character that is 'n' places down the alphabet. If the string reaches the end of the alphabet, it should wrap around to the beginning. | Here is the code to solve this problem:
```python
import string
def rotate_string(s,n):
a=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
A=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
re... | [
"assert rotate_string('c d',5) == 'h i'",
"assert rotate_string('Hello, World!',13) == 'Uryyb, Jbeyq!'",
"assert rotate_string('A F z',5) == 'F K e'"
] | You can achieve this by implementing a simple Caesar cipher function in Python. Here's a function named `caesar_cipher` that takes a string and an integer `n` as inputs and returns the converted string where each character is shifted `n` positions down the alphabet. The function takes care of wrapping around the alphab... | 12,775 | [
{
"from": "human",
"value": "Write a python function that converts a given string into a string where each character is replaced by a character that is 'n' places down the alphabet. If the string reaches the end of the alphabet, it should wrap around to the beginning."
},
{
"from": "gpt",
"value... |
Write a python function to check if a given array is a valid mountain array.
A valid mountain array is defined as follows:
- The array has at least 3 elements.
- There exists some i with 0 < i < arr.length - 1 such that:
- arr[0] < arr[1] < ... arr[i-1] < arr[i]
- arr[i] > arr[i+1] > ... > arr[arr.length - 1] | Here is the code to solve this problem:
```python
def is_valid_mountain_array(A):
n = len(A)
if n < 3:
return False
i = 1
while i < n and A[i] > A[i - 1]:
i += 1
if i == 1 or i >= n or A[i] == A[i - 1]:
return False
while i < n and A[i] < A[i - 1]:
i += 1
... | [
"assert is_valid_mountain_array([2,1]) == False",
"assert is_valid_mountain_array([3,5,5]) == False",
"assert is_valid_mountain_array([0,3,2,1]) == True"
] | To determine if a given array is a valid mountain array, we can create a function that checks the following conditions:
1. The array must contain at least 3 elements.
2. We must find an index `i` such that:
- The elements rise strictly from the beginning of the array to index `i`.
- The elements fall strictly fr... | 12,776 | [
{
"from": "human",
"value": "Write a python function to check if a given array is a valid mountain array.\n\nA valid mountain array is defined as follows:\n- The array has at least 3 elements.\n- There exists some i with 0 < i < arr.length - 1 such that:\n - arr[0] < arr[1] < ... arr[i-1] < arr[i]\n - arr... |
Write a python function to find the number of palindromic substrings in a given string. | Here is the code to solve this problem:
```python
def countPalindromicSubstrings(s):
count = 0
n = len(s)
for i in range(n):
count += 1
left = i -1
right = i + 1
while right < n and s[right] == s[i]:
count += 1
right += 1
... | [
"assert countPalindromicSubstrings(\"abc\") == 3",
"assert countPalindromicSubstrings(\"aaa\") == 6",
"assert countPalindromicSubstrings(\"racecar\") == 10"
] | You can use a Python function to find the number of palindromic substrings in a given string by expanding around potential centers of the palindromes. Below is a Python function that accomplishes this:
```python
def count_palindromic_substrings(s: str) -> int:
def expand_around_center(left: int, right: int) -> int... | 12,777 | [
{
"from": "human",
"value": "Write a python function to find the number of palindromic substrings in a given string."
},
{
"from": "gpt",
"value": "You can use a Python function to find the number of palindromic substrings in a given string by expanding around potential centers of the palindrome... |
Write a function named `calculate_hypotenuse` that takes two integer arguments `side_a` and `side_b` representing the lengths of the two sides of a right-angled triangle. The function should return the length of the hypotenuse, rounded to 2 decimal places. | Here is the code to solve this problem:
```python
import math
def calculate_hypotenuse(side_a, side_b):
hypotenuse = math.sqrt(side_a**2 + side_b**2)
return round(hypotenuse, 2)
``` | [
"assert calculate_hypotenuse(5, 12) == 13.00",
"assert calculate_hypotenuse(3, 4) == 5.00",
"assert calculate_hypotenuse(8, 15) == 17.00"
] | You can calculate the hypotenuse of a right-angled triangle using the Pythagorean theorem, which states that the square of the hypotenuse (c) is equal to the sum of the squares of the other two sides (a and b). The formula is:
\[ c = \sqrt{a^2 + b^2} \]
Here's how you can implement the `calculate_hypotenuse` function... | 12,778 | [
{
"from": "human",
"value": "Write a function named `calculate_hypotenuse` that takes two integer arguments `side_a` and `side_b` representing the lengths of the two sides of a right-angled triangle. The function should return the length of the hypotenuse, rounded to 2 decimal places."
},
{
"from": ... |
Write a function that takes a list of integers as input and returns a new list with only the prime numbers from the original list. | Here is the code to solve this problem:
```python
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
def filter_prime(nums):
return [num for num in nums if is_prime(num)]
``` | [
"assert filter_prime([21, 22, 23, 24, 25, 26, 27, 28, 29, 30]) == [23, 29]",
"assert filter_prime([11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) == [11, 13, 17, 19]",
"assert filter_prime([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [2, 3, 5, 7]"
] | Certainly! Below is a Python function that filters a list of integers and returns a new list containing only the prime numbers.
```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:
return False
... | 12,779 | [
{
"from": "human",
"value": "Write a function that takes a list of integers as input and returns a new list with only the prime numbers from the original list."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that filters a list of integers and returns a new list containing o... |
Write a python function that takes a list of integers as input and returns a new list containing only the even numbers from the input list, in the same order they appear. | Here is the code to solve this problem:
```python
def filter_even(nums):
return [num for num in nums if num % 2 == 0]
``` | [
"assert filter_even([10, 23, 36, 47, 58]) == [10, 36, 58]",
"assert filter_even([11, 22, 33, 44, 55]) == [22, 44]",
"assert filter_even([1, 2, 3, 4, 5, 6]) == [2, 4, 6]"
] | Certainly! You can achieve this by using a list comprehension in Python. Below is a function that takes a list of integers as input and returns a new list containing only the even numbers, preserving their order:
```python
def filter_even_numbers(input_list):
return [num for num in input_list if num % 2 == 0]
# E... | 12,780 | [
{
"from": "human",
"value": "Write a python function that takes a list of integers as input and returns a new list containing only the even numbers from the input list, in the same order they appear."
},
{
"from": "gpt",
"value": "Certainly! You can achieve this by using a list comprehension in ... |
Write a function to merge two sorted lists into a single sorted list. | Here is the code to solve this problem:
```python
from typing import List
def mergeTwoLists(l1: List[int], l2: List[int]) -> List[int]:
if not l1:
return l2
if not l2:
return l1
result = []
i, j = 0, 0
while i < len(l1) and j < len(l2):
if l1[i] <= l2[j]:
result... | [
"assert mergeTwoLists([1,2,4],[1,3,4]) == [1,1,2,3,4,4]",
"assert mergeTwoLists([],[]) == []",
"assert mergeTwoLists([1,3,5],[2,4,6]) == [1,2,3,4,5,6]"
] | Certainly! Here’s a function in Python that takes two sorted lists as input and merges them into a single sorted list:
```python
def merge_sorted_lists(list1, list2):
merged_list = []
i, j = 0, 0
# Traverse both lists and merge them
while i < len(list1) and j < len(list2):
if list1[i] < li... | 12,781 | [
{
"from": "human",
"value": "Write a function to merge two sorted lists into a single sorted list."
},
{
"from": "gpt",
"value": "Certainly! Here’s a function in Python that takes two sorted lists as input and merges them into a single sorted list:\n\n```python\ndef merge_sorted_lists(list1, lis... |
Write a python function to find the largest possible square sub-matrix with all 1s in a binary matrix of size n x m. | Here is the code to solve this problem:
```python
def find_largest_square(matrix):
n = len(matrix)
m = len(matrix[0])
dp = [[0] * m for _ in range(n)]
max_square = 0
for i in range(n):
for j in range(m):
if matrix[i][j] == 1:
if i == 0 or j == 0:
... | [
"assert find_largest_square([[1, 1, 1], [1, 1, 1], [1, 1, 1]]) == 9",
"assert find_largest_square([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) == 0",
"assert find_largest_square([[1, 0, 1], [0, 1, 1], [1, 1, 1]]) == 4"
] | To solve the problem of finding the largest possible square sub-matrix with all 1s in a binary matrix, we can use dynamic programming. The idea is to create a 2D array (let's call it `dp`) where `dp[i][j]` will hold the size of the largest square sub-matrix that ends at position (i, j).
Here's the detailed approach:
... | 12,782 | [
{
"from": "human",
"value": "Write a python function to find the largest possible square sub-matrix with all 1s in a binary matrix of size n x m."
},
{
"from": "gpt",
"value": "To solve the problem of finding the largest possible square sub-matrix with all 1s in a binary matrix, we can use dynam... |
Write a python function that performs bitwise addition of two integers without using the '+' operator. | Here is the code to solve this problem:
```python
def bitwise_addition(a, b):
# 32 bits integer max
MAX = 0x100000000
# get last 32 bits
INT_MAX = 0x7FFFFFFF
while b != 0:
# ^ get different bits and & gets double 1s, << moves carry
a, b = (a ^ b) % MAX, ((a & b) << 1) % MAX
# if... | [
"assert bitwise_addition(10, 1) == 11",
"assert bitwise_addition(2, 3) == 5",
"assert bitwise_addition(0, 0) == 0",
"assert bitwise_addition(5, 0) == 5"
] | Certainly! You can perform bitwise addition of two integers without using the `+` operator by using bitwise operations. The main idea is to use XOR to add bits without carrying and AND to find where there are carries. Then, you can shift the carry left and repeat the process until there are no carries left.
Here’s a P... | 12,783 | [
{
"from": "human",
"value": "Write a python function that performs bitwise addition of two integers without using the '+' operator."
},
{
"from": "gpt",
"value": "Certainly! You can perform bitwise addition of two integers without using the `+` operator by using bitwise operations. The main idea... |
Write a python function to find the minimum absolute difference between any two elements in a list. The list contains n unique integers. | Here is the code to solve this problem:
```python
def minAbsDifference(arr):
arr.sort()
min_diff = float('inf')
for i in range(1, len(arr)):
diff = abs(arr[i] - arr[i-1])
min_diff = min(min_diff, diff)
return min_diff
``` | [
"assert minAbsDifference([4,2,1,3]) == 1",
"assert minAbsDifference([3,8,-10,23,19,-4,-14,27]) == 4",
"assert minAbsDifference([1,5,0,10,14]) == 1"
] | You can find the minimum absolute difference between any two elements in a list of unique integers by first sorting the list and then iterating through it to check the differences between consecutive elements. Since the integers are unique, the absolute differences will also be unique and sorted. Here’s a Python functi... | 12,784 | [
{
"from": "human",
"value": "Write a python function to find the minimum absolute difference between any two elements in a list. The list contains n unique integers."
},
{
"from": "gpt",
"value": "You can find the minimum absolute difference between any two elements in a list of unique integers ... |
Write a function that takes two lists as parameters, and returns a list where each element is the maximum value of the corresponding elements in the two lists. | Here is the code to solve this problem:
```python
def max_elements(list1, list2):
result = []
for i in range(len(list1)):
result.append(max(list1[i], list2[i]))
return result
``` | [
"assert max_elements([5, 6, 7], [7, 6, 5]) == [7, 6, 7]",
"assert max_elements([1, 2, 3], [2, 1, 4]) == [2, 2, 4]",
"assert max_elements([10, 20, 30], [15, 25, 35]) == [15, 25, 35]"
] | Certainly! You can create a function in Python to achieve this. Below is a sample implementation that takes two lists and returns a new list containing the maximum values from corresponding elements.
```python
def max_of_lists(list1, list2):
"""
Returns a list containing the maximum value of the corresponding ... | 12,785 | [
{
"from": "human",
"value": "Write a function that takes two lists as parameters, and returns a list where each element is the maximum value of the corresponding elements in the two lists."
},
{
"from": "gpt",
"value": "Certainly! You can create a function in Python to achieve this. Below is a s... |
Write a Python function that creates a dictionary from a given list of strings. The key of each dictionary entry should be the string and the value should be the number of occurrences of that string in the list. | Here is the code to solve this problem:
```python
def create_dict(lst):
result = {}
for word in lst:
if word in result:
result[word] += 1
else:
result[word] = 1
return result
``` | [
"assert create_dict([\"python\", \"java\", \"javascript\", \"python\", \"java\"]) == {\"python\": 2, \"java\": 2, \"javascript\": 1}",
"assert create_dict([\"apple\", \"banana\", \"apple\", \"orange\", \"banana\", \"apple\"]) == {\"apple\": 3, \"banana\": 2, \"orange\": 1}",
"assert create_dict([\"red\", \"blue... | You can create a Python function that takes a list of strings and constructs a dictionary to count the occurrences of each string. Here's a simple implementation using a dictionary comprehension:
```python
def count_occurrences(strings):
# Using a dictionary comprehension to count occurrences
return {string: s... | 12,786 | [
{
"from": "human",
"value": "Write a Python function that creates a dictionary from a given list of strings. The key of each dictionary entry should be the string and the value should be the number of occurrences of that string in the list."
},
{
"from": "gpt",
"value": "You can create a Python ... |
Write a python function to find the first non-repeating character in a given string. | Here is the code to solve this problem:
```python
from collections import OrderedDict
def non_repeating_char(s):
count = OrderedDict()
for char in s:
count[char] = count.get(char, 0) + 1
for char in s:
if count[char] == 1:
return char
return ''
``` | [
"assert non_repeating_char(\"leetcode\") == 'l'",
"assert non_repeating_char(\"aabb\") == ''",
"assert non_repeating_char(\"loveleetcode\") == 'v'"
] | Certainly! You can find the first non-repeating character in a string by using a dictionary to count the occurrences of each character, and then iterating through the string to find the first character that has a count of 1. Here's a Python function that accomplishes this:
```python
def first_non_repeating_character(s... | 12,787 | [
{
"from": "human",
"value": "Write a python function to find the first non-repeating character in a given string."
},
{
"from": "gpt",
"value": "Certainly! You can find the first non-repeating character in a string by using a dictionary to count the occurrences of each character, and then iterat... |
Write a function to calculate the area of a triangle given the coordinates of its three vertices.
The function should take six parameters, representing the x and y coordinates of the three vertices: `(x1, y1)`, `(x2, y2)`, and `(x3, y3)`. It should return the area of the triangle formed by these points.
**Formula for... | Here is the code to solve this problem:
```python
def calculate_triangle_area(x1, y1, x2, y2, x3, y3):
area = 0.5 * abs(x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2))
return area
``` | [
"assert calculate_triangle_area(1, 1, 3, 1, 2, 4) == 3.0 ",
"assert calculate_triangle_area(0, 0, 0, 0, 0, 0) == 0.0",
"assert calculate_triangle_area(0, 0, 4, 0, 2, 3) == 6.0 "
] | You can calculate the area of a triangle given the coordinates of its three vertices using the formula you've provided. Here is a Python function that implements this calculation:
```python
def triangle_area(x1, y1, x2, y2, x3, y3):
area = 0.5 * abs(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2))
return area... | 12,788 | [
{
"from": "human",
"value": "Write a function to calculate the area of a triangle given the coordinates of its three vertices.\n\nThe function should take six parameters, representing the x and y coordinates of the three vertices: `(x1, y1)`, `(x2, y2)`, and `(x3, y3)`. It should return the area of the tria... |
Write a python function to convert a given number from base 10 to a specified base. | Here is the code to solve this problem:
```python
def convert_base(num, to_base=10):
converted_string, modstring = "", ""
currentnum = num
if not 1 < to_base < 37:
return 0
base_value = 0
while(currentnum > 0):
mod = currentnum % to_base
currentnum = currentnum // to_base
... | [
"assert convert_base(8, 3) == '22'",
"assert convert_base(7, 2) == '111'",
"assert convert_base(8, 2) == '1000'"
] | You can convert a number from base 10 to a specified base using a function in Python. Below is a simple implementation that takes a decimal number and the base to which you want to convert it:
```python
def convert_to_base(n, base):
if n < 0:
return '-' + convert_to_base(-n, base)
elif n == 0:
... | 12,789 | [
{
"from": "human",
"value": "Write a python function to convert a given number from base 10 to a specified base."
},
{
"from": "gpt",
"value": "You can convert a number from base 10 to a specified base using a function in Python. Below is a simple implementation that takes a decimal number and t... |
Write a function that checks if a given string is a palindrome or not using recursion. | Here is the code to solve this problem:
```python
def is_palindrome_recursive(s):
if len(s) <= 1:
return True
if s[0] != s[-1]:
return False
return is_palindrome_recursive(s[1:-1])
``` | [
"assert is_palindrome_recursive(\"level\") == True",
"assert is_palindrome_recursive(\"racecar\") == True",
"assert is_palindrome_recursive(\"radar\") == True",
"assert is_palindrome_recursive(\"python\") == False"
] | Sure! A palindrome is a string that reads the same backward as forward. To check if a string is a palindrome using recursion, you can write a function that compares the first and last characters of the string. If they are the same, the function should recursively check the substring that excludes these two characters. ... | 12,790 | [
{
"from": "human",
"value": "Write a function that checks if a given string is a palindrome or not using recursion."
},
{
"from": "gpt",
"value": "Sure! A palindrome is a string that reads the same backward as forward. To check if a string is a palindrome using recursion, you can write a functio... |
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 get_First_Non_Repeating_Character(string):
char_count = {}
for char in string:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
for char in string:
if char_count[char] == 1:
... | [
"assert get_First_Non_Repeating_Character(\"abcdcaf\") == \"b\"",
"assert get_First_Non_Repeating_Character(\"aabbcc\") == None",
"assert get_First_Non_Repeating_Character(\"aabbccx\") == \"x\""
] | You can find the first non-repeating character in a given string by using a dictionary to count occurrences of each character and then iterating through the string to identify the first character that has a count of one. Here's a Python function that does that:
```python
def first_non_repeating_character(s: str) -> st... | 12,791 | [
{
"from": "human",
"value": "Write a python function to find the first non-repeating character in a given string."
},
{
"from": "gpt",
"value": "You can find the first non-repeating character in a given string by using a dictionary to count occurrences of each character and then iterating throug... |
Write a function that converts a given number into its English words representation. The function should handle numbers up to 999,999,999,999 (one billion, nine hundred ninety-nine million, nine hundred ninety-nine thousand, nine hundred ninety-nine). | Here is the code to solve this problem:
```python
def number_to_words(num):
def one(num):
switcher = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine... | [
"assert number_to_words(123) == \"one hundred twenty three\"",
"assert number_to_words(1234567) == \"one million two hundred thirty four thousand five hundred sixty seven\"",
"assert number_to_words(12345) == \"twelve thousand three hundred forty five\"",
"assert number_to_words(1234567890) == \"one billion t... | To convert a number into its English words representation, we can break down the problem into manageable parts. We'll define the function that handles numbers below a thousand, and then build on that for larger numbers like millions and billions. Below is a Python function that achieves this:
```python
def number_to_w... | 12,792 | [
{
"from": "human",
"value": "Write a function that converts a given number into its English words representation. The function should handle numbers up to 999,999,999,999 (one billion, nine hundred ninety-nine million, nine hundred ninety-nine thousand, nine hundred ninety-nine)."
},
{
"from": "gpt"... |
Write a function to find the longest sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of a given positive integer. | Here is the code to solve this problem:
```python
def longest_zeros(N):
binary = bin(N)[2:]
max_gap, current_gap = 0, 0
found_one = False
for bit in binary:
if bit == '1':
if found_one and current_gap > max_gap:
max_gap = current_gap
current_gap = 0
... | [
"assert longest_zeros(32) == 0",
"assert longest_zeros(9) == 2",
"assert longest_zeros(1041) == 5"
] | To solve the problem of finding the longest sequence of consecutive zeros that is surrounded by ones in the binary representation of a given positive integer, we can follow these steps:
1. Convert the integer to its binary representation.
2. Split the binary string on the character '1' to isolate the segments of zeros... | 12,793 | [
{
"from": "human",
"value": "Write a function to find the longest sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of a given positive integer."
},
{
"from": "gpt",
"value": "To solve the problem of finding the longest sequence of consecutive zer... |
Write a python function to rearrange the elements of a list so that all the even numbers come before all the odd numbers. | Here is the code to solve this problem:
```python
def even_odd_rearrange(list):
evens = [x for x in list if x % 2 == 0]
odds = [x for x in list if x % 2 != 0]
return evens + odds
``` | [
"assert even_odd_rearrange([1,2,3,4,5,6]) == [2,4,6,1,3,5]",
"assert even_odd_rearrange([1,3,5,7]) == [1,3,5,7]",
"assert even_odd_rearrange([11,22,33,44,55,66]) == [22,44,66,11,33,55]"
] | You can achieve this by defining a Python function that separates the even and odd numbers from the input list and then concatenates them together. Here's a simple implementation of that:
```python
def rearrange_even_odd(numbers):
# Separate even and odd numbers using list comprehension
even_numbers = [num for... | 12,794 | [
{
"from": "human",
"value": "Write a python function to rearrange the elements of a list so that all the even numbers come before all the odd numbers."
},
{
"from": "gpt",
"value": "You can achieve this by defining a Python function that separates the even and odd numbers from the input list and... |
Write a python function to find the number of distinct occurrences of a character in a string. | Here is the code to solve this problem:
```python
def distinct_occurrences(string, char):
return string.count(char)
``` | [
"assert distinct_occurrences('hello', 'l') == 2",
"assert distinct_occurrences('programming', 'm') == 2",
"assert distinct_occurrences('world', 'd') == 1"
] | Certainly! You can write a Python function to count the number of distinct occurrences of a character in a string using a loop or using string methods. Here’s a concise way to do it using a set to keep track of the distinct positions where the character occurs:
```python
def distinct_occurrences(string, char):
# E... | 12,795 | [
{
"from": "human",
"value": "Write a python function to find the number of distinct occurrences of a character in a string."
},
{
"from": "gpt",
"value": "Certainly! You can write a Python function to count the number of distinct occurrences of a character in a string using a loop or using strin... |
Write a function to check if a number is a power of three. Return True if the number is a power of three, otherwise return False. | Here is the code to solve this problem:
```python
def isPowerOfThree(n: int) -> bool:
if n <= 0:
return False
while n % 3 == 0:
n /= 3
return n == 1
``` | [
"assert isPowerOfThree(27) == True",
"assert isPowerOfThree(0) == False",
"assert isPowerOfThree(9) == True",
"assert isPowerOfThree(45) == False",
"assert isPowerOfThree(81) == True"
] | You can check if a number is a power of three using a simple function. One way to do this is by continuously dividing the number by 3 and checking if the result eventually equals 1. Here’s a Python function that implements this logic:
```python
def is_power_of_three(n: int) -> bool:
if n <= 0:
return False... | 12,796 | [
{
"from": "human",
"value": "Write a function to check if a number is a power of three. Return True if the number is a power of three, otherwise return False."
},
{
"from": "gpt",
"value": "You can check if a number is a power of three using a simple function. One way to do this is by continuous... |
Write a Python function to convert a given string to lowercase and remove any non-alphabetic characters. | Here is the code to solve this problem:
```python
def lowercase_clean(s):
result = ''
for char in s:
if char.isalpha():
result += char.lower()
return result
``` | [
"assert lowercase_clean('HELLO!') == 'hello'",
"assert lowercase_clean('WORLD?') == 'world'",
"assert lowercase_clean('Python123') == 'python'"
] | You can achieve this by using Python's built-in string methods along with regular expressions. Here’s a simple function that converts a given string to lowercase and removes any non-alphabetic characters:
```python
import re
def clean_string(input_string):
# Convert to lowercase
lowercase_string = input_strin... | 12,797 | [
{
"from": "human",
"value": "Write a Python function to convert a given string to lowercase and remove any non-alphabetic characters."
},
{
"from": "gpt",
"value": "You can achieve this by using Python's built-in string methods along with regular expressions. Here’s a simple function that conver... |
Write a python function to find the product of all elements in a list that are greater than a given threshold. | Here is the code to solve this problem:
```python
def product_above_threshold(list1, threshold):
result = 1
for num in list1:
if num > threshold:
result *= num
return result
``` | [
"assert product_above_threshold([10, 20, 30, 40, 50], 25) == 60000",
"assert product_above_threshold([3, 6, 9, 12, 15], 10) == 180",
"assert product_above_threshold([1, 2, 3, 4, 5, 6, 7, 8, 9], 5) == 3024"
] | Certainly! Below is a Python function that takes a list and a threshold value as input, then calculates the product of all elements in the list that are greater than the threshold.
Here's the function:
```python
def product_of_elements_above_threshold(lst, threshold):
product = 1
has_elements = False
fo... | 12,798 | [
{
"from": "human",
"value": "Write a python function to find the product of all elements in a list that are greater than a given threshold."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that takes a list and a threshold value as input, then calculates the product of all el... |
Write a python function that calculates the number of unique substrings in a given string. | Here is the code to solve this problem:
```python
def unique_substrings(s):
substrings = set()
for i in range(len(s)):
for j in range(i+1, len(s)+1):
substrings.add(s[i:j])
return len(substrings)
``` | [
"assert unique_substrings(\"abc\") == 6",
"assert unique_substrings(\"aaa\") == 3",
"assert unique_substrings(\"abcd\") == 10"
] | To calculate the number of unique substrings in a given string, we can utilize the concept of Suffix Arrays and Longest Common Prefix (LCP) arrays. This approach is efficient in terms of both time and space, allowing us to handle larger strings effectively.
Here's a Python function that implements this using Suffix Ar... | 12,799 | [
{
"from": "human",
"value": "Write a python function that calculates the number of unique substrings in a given string."
},
{
"from": "gpt",
"value": "To calculate the number of unique substrings in a given string, we can utilize the concept of Suffix Arrays and Longest Common Prefix (LCP) array... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.