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 minimum number of operations required to convert a given string into a palindrome by either inserting or deleting a character. | Here is the code to solve this problem:
```python
def minOperationsPalindrome(s):
n = len(s)
dp = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
dp[i][i] = 1
for j in range(i + 1, n):
if s[i] == s[j]:
dp[i][j] = dp[i + 1][j - 1] + 2
e... | [
"assert minOperationsPalindrome(\"abc\") == 2",
"assert minOperationsPalindrome(\"abcbaa\") == 1",
"assert minOperationsPalindrome(\"abccba\") == 0"
] | To convert a given string into a palindrome using the minimum number of operations (insertions or deletions), we can leverage the concept of the longest palindromic subsequence (LPS). The idea is that the difference between the length of the string and the length of its longest palindromic subsequence gives us the mini... | 19,400 | [
{
"from": "human",
"value": "Write a python function to find the minimum number of operations required to convert a given string into a palindrome by either inserting or deleting a character."
},
{
"from": "gpt",
"value": "To convert a given string into a palindrome using the minimum number of o... |
Write a function that takes a list of numbers and a target number. The function should return the closest number to the target number in the list. If there are two numbers equally close to the target, return the smaller one. | Here is the code to solve this problem:
```python
def closest_number(numbers, target):
if not numbers:
return None
closest = numbers[0]
for num in numbers:
if abs(target - num) < abs(target - closest) or (abs(target - num) == abs(target - closest) and num < closest):
closest = n... | [
"assert closest_number([1, 2, 3, 4, 5], 2.5) == 2",
"assert closest_number([1, 2, 3, 4, 5], 6) == 5",
"assert closest_number([1, 2, 3, 4, 5], 3.5) == 3",
"assert closest_number([1, 2, 3, 4, 5], -1) == 1"
] | Certainly! Below is a Python function that implements the task you described. It takes a list of numbers and a target number as input, and returns the closest number to the target from the list. If there are two equally close numbers, it returns the smaller one.
```python
def closest_number(numbers, target):
if no... | 19,401 | [
{
"from": "human",
"value": "Write a function that takes a list of numbers and a target number. The function should return the closest number to the target number in the list. If there are two numbers equally close to the target, return the smaller one."
},
{
"from": "gpt",
"value": "Certainly! ... |
Write a function that takes two strings and checks if the second string is a long-pressed version of the first string. A long-pressed string is a string in which some characters are repeated consecutively. | Here is the code to solve this problem:
```python
def isLongPressedName(name: str, typed: str) -> bool:
name_index, typed_index = 0, 0
while name_index < len(name) and typed_index < len(typed):
if name[name_index] == typed[typed_index]:
name_index += 1
typed_index += 1
e... | [
"assert isLongPressedName(\"alex\", \"aaleex\") == True",
"assert isLongPressedName(\"laiden\", \"laiden\") == True",
"assert isLongPressedName(\"saeed\", \"ssaaedd\") == False"
] | To check if the second string is a long-pressed version of the first string, we can compare the two strings while considering that consecutive characters in the second string can correspond to the same character from the first string.
Here's a Python function to perform this check:
```python
def is_long_pressed(s: s... | 19,402 | [
{
"from": "human",
"value": "Write a function that takes two strings and checks if the second string is a long-pressed version of the first string. A long-pressed string is a string in which some characters are repeated consecutively."
},
{
"from": "gpt",
"value": "To check if the second string ... |
Write a function to find the minimum number of operations required to convert a string into a palindrome. An operation is defined as inserting a character into the string. | Here is the code to solve this problem:
```python
def min_palindrome_operations(s):
n = len(s)
dp = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
dp[i][i] = 0
for j in range(i + 1, n):
if s[i] == s[j]:
dp[i][j] = dp[i + 1][j - 1]
else:
... | [
"assert min_palindrome_operations(\"aabb\") == 2",
"assert min_palindrome_operations(\"abcd\") == 3",
"assert min_palindrome_operations(\"abba\") == 0"
] | To solve the problem of finding the minimum number of operations required to convert a string into a palindrome using insertions, we can leverage the relationship between the string and its longest palindromic subsequence.
### Steps to Solve the Problem
1. Calculate the length of the longest palindromic subsequence (... | 19,403 | [
{
"from": "human",
"value": "Write a function to find the minimum number of operations required to convert a string into a palindrome. An operation is defined as inserting a character into the string."
},
{
"from": "gpt",
"value": "To solve the problem of finding the minimum number of operations... |
Write a function to check if the array has a contiguous subarray of size at least 2 that sums up to a multiple of k. | Here is the code to solve this problem:
```python
def checkSubarraySum(nums, k):
hashmap = {}
curr_sum = 0
for i in range(len(nums)):
curr_sum += nums[i]
if curr_sum % k in hashmap:
if i - hashmap[curr_sum % k] > 1:
return True
else:
hashmap[... | [
"assert checkSubarraySum([23,2,4,6,7], 6) == True",
"assert checkSubarraySum([23,2,6,4,7], 13) == False",
"assert checkSubarraySum([23,2,6,4,7], 6) == True"
] | To determine if a given array has a contiguous subarray of size at least 2 that sums up to a multiple of `k`, we can utilize a hash map to keep track of the cumulative sums and their corresponding indices. The approach involves calculating the cumulative sum modulo `k` and checking for indices where the same cumulative... | 19,404 | [
{
"from": "human",
"value": "Write a function to check if the array has a contiguous subarray of size at least 2 that sums up to a multiple of k."
},
{
"from": "gpt",
"value": "To determine if a given array has a contiguous subarray of size at least 2 that sums up to a multiple of `k`, we can ut... |
Write a function that calculates the number of unique paths from the top-left corner to the bottom-right corner of a grid, given that some obstacles are present on the grid.
The function should take a 2D list of integers as input, where 0 represents an empty cell and 1 represents an obstacle. The function should retur... | Here is the code to solve this problem:
```python
def unique_paths_with_obstacles(obstacleGrid):
row = len(obstacleGrid)
col = len(obstacleGrid[0])
dp = [[1] * col for _ in range(row)]
for i in range(0, row):
for j in range(0, col):
if obstacleGrid[i][j]:
dp[i][j] =... | [
"assert unique_paths_with_obstacles([[0,1],[0,0]])==1",
"assert unique_paths_with_obstacles([[0,0],[1,1],[0,0]])==0",
"assert unique_paths_with_obstacles([[0,0,0],[0,1,0],[0,0,0]])==2"
] | To solve the problem of finding the number of unique paths in a grid with obstacles, we can use dynamic programming. We'll create a 2D list (dp) that keeps track of the number of unique paths to each cell in the grid.
If a cell contains an obstacle (represented by 1), then there are 0 paths to that cell. If it's an e... | 19,405 | [
{
"from": "human",
"value": "Write a function that calculates the number of unique paths from the top-left corner to the bottom-right corner of a grid, given that some obstacles are present on the grid.\n\nThe function should take a 2D list of integers as input, where 0 represents an empty cell and 1 repres... |
Write a function to find the maximum length of a word chain in a list of words, where a word can be formed by deleting some characters of another word in the list. | Here is the code to solve this problem:
```python
def longest_word_chain(words):
words.sort(key=len)
dp=[1]*(len(words))
def combine(s1,s2):
if(len(s1)+1!=len(s2)):
return False
i=0
j=0
count=0
while(i<len(s1)):
if(s1[i]==s2[j] and j<len(s2)):... | [
"assert longest_word_chain([\"a\", \"b\", \"ba\", \"bca\", \"bda\", \"bdca\"]) == 4",
"assert longest_word_chain([\"xbc\", \"pcxbcf\", \"xb\", \"cxbc\", \"pcxbc\"]) == 5",
"assert longest_word_chain([\"abcd\", \"dbqca\"]) == 1"
] | To find the maximum length of a word chain in a list of words, where a word can be formed by deleting some characters of another word, we can utilize a dynamic programming approach. The idea is to sort the words by length and then use a list to track the longest chain ending at each word.
Here's a Python function that... | 19,406 | [
{
"from": "human",
"value": "Write a function to find the maximum length of a word chain in a list of words, where a word can be formed by deleting some characters of another word in the list."
},
{
"from": "gpt",
"value": "To find the maximum length of a word chain in a list of words, where a w... |
Write a python function to find the largest 3-digit number in a string where all digits are the same. | Here is the code to solve this problem:
```python
def largest_good_integer(num: str) -> str:
ans: str = ''
for i in range(2, len(num)):
if num[i] == num[i - 1] == num[i - 2]:
ans = max(ans, num[i])
return ans * 3 if ans else ''
``` | [
"assert largest_good_integer(\"2300019\") == \"000\"",
"assert largest_good_integer(\"6777133339\") == \"777\"",
"assert largest_good_integer(\"42352338\") == \"\""
] | You can achieve this by creating a function that scans through the input string, looks for 3-digit numbers, and checks if all digits in the number are the same. Here's how you can implement this in Python:
```python
def largest_same_digit_number(s):
largest_number = None
# Scan through the string to find ... | 19,407 | [
{
"from": "human",
"value": "Write a python function to find the largest 3-digit number in a string where all digits are the same."
},
{
"from": "gpt",
"value": "You can achieve this by creating a function that scans through the input string, looks for 3-digit numbers, and checks if all digits i... |
Write a function to get the nth digit of Champernowne's constant. Champernowne's constant is a transcendental real constant whose decimal expansion has important properties in number theory. It is constructed by concatenating the positive integers:
```
C10 = 0.12345678910111213141516...
``` | Here is the code to solve this problem:
```python
def get_nth_digit(n):
if n < 10:
return n
digit_length = 1
while n > digit_length * 9 * 10 ** (digit_length - 1):
n -= digit_length * 9 * 10 ** (digit_length - 1)
digit_length += 1
number = 10 ** (digit_length - 1) + (n - 1) // d... | [
"assert get_nth_digit(1)==1",
"assert get_nth_digit(11)==0",
"assert get_nth_digit(100)==5",
"assert get_nth_digit(15)==2"
] | Certainly! To find the nth digit of Champernowne's constant, you can follow these steps in the implementation:
1. Determine how many digits long the numbers are that contribute to the sequence up to `n`.
2. Count how many digits are contributed by 1-digit numbers, 2-digit numbers, and so on, until you find the range t... | 19,408 | [
{
"from": "human",
"value": "Write a function to get the nth digit of Champernowne's constant. Champernowne's constant is a transcendental real constant whose decimal expansion has important properties in number theory. It is constructed by concatenating the positive integers:\n```\nC10 = 0.1234567891011121... |
Write a python function to find the unique elements in a list and return them in sorted order. | Here is the code to solve this problem:
```python
def sorted_unique(list1):
return sorted(set(list1))
``` | [
"assert sorted_unique([4,5,6,6,5,4]) == [4,5,6]",
"assert sorted_unique([10,20,30,30,20,10]) == [10,20,30]",
"assert sorted_unique([1,2,3,3,2,1]) == [1,2,3]"
] | Certainly! You can achieve this using a combination of the `set` data structure to find unique elements and the `sorted` function to sort them. Here’s a Python function that does just that:
```python
def unique_sorted_elements(input_list):
# Convert the list to a set to get unique elements
unique_elements = se... | 19,409 | [
{
"from": "human",
"value": "Write a python function to find the unique elements in a list and return them in sorted order."
},
{
"from": "gpt",
"value": "Certainly! You can achieve this using a combination of the `set` data structure to find unique elements and the `sorted` function to sort the... |
Write a Python function that calculates the shortest path in a grid from the top-left corner to the bottom-right corner. The grid is represented as a list of lists, where each cell contains a non-negative integer representing the cost to traverse that cell. You can only move right or down. | Here is the code to solve this problem:
```python
def min_path_sum(grid):
m, n = len(grid), len(grid[0])
for i in range(1, m):
grid[i][0] += grid[i-1][0]
for j in range(1, n):
grid[0][j] += grid[0][j-1]
for i in range(1, m):
for j in range(1, n):
grid[i][j] += min(gr... | [
"assert min_path_sum([[1]]) == 1",
"assert min_path_sum([[1,3,1],[1,5,1],[4,2,1]]) == 7",
"assert min_path_sum([[1,2,3],[4,5,6]]) == 12"
] | To calculate the shortest path in a grid from the top-left corner to the bottom-right corner, where each cell contains a non-negative integer cost to traverse that cell, we can use dynamic programming. The idea is to build a cost matrix that keeps track of the minimum cost to reach each cell.
Here's how the function c... | 19,410 | [
{
"from": "human",
"value": "Write a Python function that calculates the shortest path in a grid from the top-left corner to the bottom-right corner. The grid is represented as a list of lists, where each cell contains a non-negative integer representing the cost to traverse that cell. You can only move rig... |
Write a function to replace all occurrences of a specified element in a list with a new value. | Here is the code to solve this problem:
```python
def replace_element_in_list(arr, old_val, new_val):
return [new_val if x == old_val else x for x in arr]
print(replace_element_in_list([1, 3, 5, 7, 9, 3], 3, 10)) # [1, 10, 5, 7, 9, 10]
print(replace_element_in_list([10, 20, 30, 40], 50, 60)) # [10, 20, 30, 40]
pr... | [
"assert replace_element_in_list([1, 2, 3, 4, 5], 5, 6) == [1, 2, 3, 4, 6]",
"assert replace_element_in_list([10, 20, 30, 40], 50, 60) == [10, 20, 30, 40]",
"assert replace_element_in_list([1, 3, 5, 7, 9, 3], 3, 10) == [1, 10, 5, 7, 9, 10]"
] | Certainly! Below is a Python function that replaces all occurrences of a specified element in a list with a new value. The function takes three arguments: the original list, the element to be replaced, and the new value to replace it with.
```python
def replace_element(original_list, target, new_value):
"""
Re... | 19,411 | [
{
"from": "human",
"value": "Write a function to replace all occurrences of a specified element in a list with a new value."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that replaces all occurrences of a specified element in a list with a new value. The function takes thr... |
Write a Python function that checks if a given string can be segmented into space-separated words such that every word is in the given dictionary. | Here is the code to solve this problem:
```python
def wordBreak(s, 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 wordDict:
dp[i] = True
break
return dp[len(s)]
wordDict ... | [
"assert wordBreak(\"leetcode\", [\"leet\", \"code\"]) == True",
"assert wordBreak(\"catsandog\", [\"cats\", \"dog\", \"sand\", \"and\", \"cat\"]) == False",
"assert wordBreak(\"applepenapple\", [\"apple\", \"pen\"]) == True"
] | Certainly! You can solve the problem of checking whether a string can be segmented into space-separated words that exist in a given dictionary using a dynamic programming approach. Here’s a Python function to accomplish that:
```python
def word_break(s: str, word_dict: set) -> bool:
# Create a DP array of size len... | 19,412 | [
{
"from": "human",
"value": "Write a Python function that checks if a given string can be segmented into space-separated words such that every word is in the given dictionary."
},
{
"from": "gpt",
"value": "Certainly! You can solve the problem of checking whether a string can be segmented into s... |
Write a function to calculate the sum of the first 'n' even numbers. | Here is the code to solve this problem:
```python
def even_sum(n):
return n * (n + 1)
``` | [
"assert even_sum(0) == 0",
"assert even_sum(5) == 30",
"assert even_sum(1) == 2"
] | You can calculate the sum of the first 'n' even numbers using a simple mathematical formula or by writing a function to iterate and sum them.
Here's a Python function that does it both ways:
### Method 1: Using the formula
The sum of the first 'n' even numbers can be calculated using the formula:
\[ \text{Sum} = n \... | 19,413 | [
{
"from": "human",
"value": "Write a function to calculate the sum of the first 'n' even numbers."
},
{
"from": "gpt",
"value": "You can calculate the sum of the first 'n' even numbers using a simple mathematical formula or by writing a function to iterate and sum them. \n\nHere's a Python funct... |
Write a function to check if a given triangle can form a valid Pythagorean triplet. A Pythagorean triplet consists of three positive integers a, b, and c, such that a^2 + b^2 = c^2. The triangle is represented as a list of tuples, where each tuple contains the lengths of the sides of a triangle. | Here is the code to solve this problem:
```python
def is_pythagorean_triplet(triangles):
result = []
for triangle in triangles:
a, b, c = sorted(triangle)
if a**2 + b**2 == c**2:
result.append(True)
else:
result.append(False)
return all(result)
``` | [
"assert is_pythagorean_triplet([(3, 4, 5)]) == True",
"assert is_pythagorean_triplet([(5, 12, 13), (7, 24, 25)]) == True",
"assert is_pythagorean_triplet([(1, 2, 3)]) == False",
"assert is_pythagorean_triplet([(8, 15, 17), (9, 40, 41)]) == True",
"assert is_pythagorean_triplet([(10, 24, 26)]) == True"
] | To determine if a triangle can form a valid Pythagorean triplet, we must verify if the lengths of its sides can satisfy the equation \( a^2 + b^2 = c^2 \) for some permutation of the sides. Here’s how you can write a function to check this in Python.
```python
def is_pythagorean_triplet(sides):
# Extract the sides... | 19,414 | [
{
"from": "human",
"value": "Write a function to check if a given triangle can form a valid Pythagorean triplet. A Pythagorean triplet consists of three positive integers a, b, and c, such that a^2 + b^2 = c^2. The triangle is represented as a list of tuples, where each tuple contains the lengths of the sid... |
Write a function that takes a list of numbers and returns a dictionary of squares and cubes for each number using dictionary comprehension. | Here is the code to solve this problem:
```python
def num_operations(nums):
return {num: {'square': num**2, 'cube': num**3} for num in nums}
``` | [
"assert num_operations([2,4,6,8]) == {2: {'square': 4, 'cube': 8}, 4: {'square': 16, 'cube': 64}, 6: {'square': 36, 'cube': 216}, 8: {'square': 64, 'cube': 512}}",
"assert num_operations([5,10,15,20]) == {5: {'square': 25, 'cube': 125}, 10: {'square': 100, 'cube': 1000}, 15: {'square': 225, 'cube': 3375}, 20: {'s... | You can create a function that takes a list of numbers and returns a dictionary with each number as the key and a tuple of its square and cube as the value. Here's how you can do that using dictionary comprehension:
```python
def squares_and_cubes(numbers):
return {num: (num ** 2, num ** 3) for num in numbers}
# ... | 19,415 | [
{
"from": "human",
"value": "Write a function that takes a list of numbers and returns a dictionary of squares and cubes for each number using dictionary comprehension."
},
{
"from": "gpt",
"value": "You can create a function that takes a list of numbers and returns a dictionary with each number... |
Write a function to check if a string is a palindrome, ignoring case and non-alphanumeric characters.
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). | Here is the code to solve this problem:
```python
import re
def is_palindrome_enhanced(s: str) -> bool:
# Remove non-alphanumeric characters and convert to lowercase
cleaned_s = re.sub(r'[^A-Za-z0-9]', '', s).lower()
# Check if the cleaned string is a palindrome
return cleaned_s == cleaned_s[::-1]
``` | [
"assert is_palindrome_enhanced(\"A man, a plan, a canal: Panama\") == True",
"assert is_palindrome_enhanced(\"No lemon, no melon\") == True",
"assert is_palindrome_enhanced(\"Hello, World!\") == False"
] | Certainly! Below is a Python function that checks if a given string is a palindrome by ignoring case and non-alphanumeric characters.
```python
import re
def is_palindrome(s: str) -> bool:
# Use regex to remove non-alphanumeric characters and convert to lower case
cleaned_string = re.sub(r'[^a-zA-Z0-9]', '',... | 19,416 | [
{
"from": "human",
"value": "Write a function to check if a string is a palindrome, ignoring case and non-alphanumeric characters.\n\nA palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization)."
},
{... |
Write a function that checks if a given string is a palindrome, considering only alphanumeric characters and ignoring cases. | Here is the code to solve this problem:
```python
def is_alphanumeric_palindrome(s):
alphanumeric_s = [char.lower() for char in s if char.isalnum()]
return alphanumeric_s == alphanumeric_s[::-1]
``` | [
"assert is_alphanumeric_palindrome(\"race a car\") == False",
"assert is_alphanumeric_palindrome(\" \") == True",
"assert is_alphanumeric_palindrome(\"A man, a plan, a canal: Panama\") == True"
] | Certainly! Below is a Python function that checks if a given string is a palindrome, considering only alphanumeric characters and ignoring cases.
```python
def is_palindrome(s: str) -> bool:
# Filter out alphanumeric characters and convert to lowercase
filtered_chars = [char.lower() for char in s if char.isaln... | 19,417 | [
{
"from": "human",
"value": "Write a function that checks if a given string is a palindrome, considering only alphanumeric characters and ignoring cases."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that checks if a given string is a palindrome, considering only alphanume... |
Write a python function that converts a list of strings into a dictionary where the keys are the strings and the values are the lengths of these strings. | Here is the code to solve this problem:
```python
def str_list_to_dict(lst):
return {word: len(word) for word in lst}
``` | [
"assert str_list_to_dict(['apple', 'banana', 'cherry']) == {'apple': 5, 'banana': 6, 'cherry': 6}",
"assert str_list_to_dict(['123', '4567', '89']) == {'123': 3, '4567': 4, '89': 2}",
"assert str_list_to_dict(['hello', 'world', 'python']) == {'hello': 5, 'world': 5, 'python': 6}"
] | You can create a Python function that takes a list of strings as input and returns a dictionary where each string is a key and the corresponding value is the length of that string. Here's how you can implement this:
```python
def list_to_length_dict(string_list):
return {s: len(s) for s in string_list}
# Example ... | 19,418 | [
{
"from": "human",
"value": "Write a python function that converts a list of strings into a dictionary where the keys are the strings and the values are the lengths of these strings."
},
{
"from": "gpt",
"value": "You can create a Python function that takes a list of strings as input and returns... |
Write a python function to find the minimum number of changes required to convert a given string into a palindrome. A palindrome is a word, phrase, number, or other sequences of characters that reads the same backward as forward. | Here is the code to solve this problem:
```python
def min_changes_to_palindrome(s):
left = 0
right = len(s) - 1
changes = 0
while left < right:
if s[left] != s[right]:
changes += 1
left += 1
right -= 1
return changes
``` | [
"assert min_changes_to_palindrome(\"abc\") == 1",
"assert min_changes_to_palindrome(\"abccba\") == 0",
"assert min_changes_to_palindrome(\"abcde\") == 2"
] | To determine the minimum number of changes required to convert a given string into a palindrome, we can use a two-pointer approach. We will compare characters from both ends of the string and count how many characters need to be changed to make the string symmetrical.
Here is a Python function that implements this log... | 19,419 | [
{
"from": "human",
"value": "Write a python function to find the minimum number of changes required to convert a given string into a palindrome. A palindrome is a word, phrase, number, or other sequences of characters that reads the same backward as forward."
},
{
"from": "gpt",
"value": "To det... |
Write a function to find the shortest path from the top-left corner to the bottom-right corner in a 2D grid. You can move in four directions: up, down, left, and right. Each cell in the grid contains a non-negative integer that represents the cost to move through that cell. The goal is to find the path with the minimum... | Here is the code to solve this problem:
```python
from typing import List
def min_path(grid: List[List[int]]) -> int:
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
dp = [[float('inf')] * cols for _ in range(rows)]
dp[0][0] = grid[0][0]
for row in range(rows):
for col... | [
"assert min_path([[1,2,3],[4,5,6]])==12",
"assert min_path([[1,3,1],[1,5,1],[4,2,1]])==7",
"assert min_path([[1]])==1"
] | To find the shortest path from the top-left corner to the bottom-right corner in a 2D grid where each cell has a movement cost, we can use Dijkstra's algorithm or a priority queue approach. This is a well-known problem and can be tackled effectively with a priority queue.
Here's an implementation of this solution in P... | 19,420 | [
{
"from": "human",
"value": "Write a function to find the shortest path from the top-left corner to the bottom-right corner in a 2D grid. You can move in four directions: up, down, left, and right. Each cell in the grid contains a non-negative integer that represents the cost to move through that cell. The ... |
Write a function to calculate the factorial of a number using recursion. | Here is the code to solve this problem:
```python
def Recursive_Factorial(n):
if n==0:
return 1
else:
return n * Recursive_Factorial(n-1)
``` | [
"assert Recursive_Factorial(3)==6",
"assert Recursive_Factorial(5)==120",
"assert Recursive_Factorial(7)==5040"
] | Certainly! Below is a Python function that calculates the factorial of a number using recursion:
```python
def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case: n! = n * (n-1)!
else:
return n * factorial(n - 1)
# Example usage:
number =... | 19,421 | [
{
"from": "human",
"value": "Write a function to calculate the factorial of a number using recursion."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that calculates the factorial of a number using recursion:\n\n```python\ndef factorial(n):\n # Base case: factorial of 0 o... |
Write a python function to find the maximum sum of a subarray with the length of exactly k. | Here is the code to solve this problem:
```python
def max_k_subarray_sum(arr, k):
max_sum = 0
window_sum = 0
window_start = 0
for window_end in range(len(arr)):
window_sum += arr[window_end] # add the next element
# slide the window, we don't need to slide if we've not hit the required... | [
"assert max_k_subarray_sum([1,2,3,4,5], 2) == 9",
"assert max_k_subarray_sum([2,1,5,1,3,2], 3) == 9",
"assert max_k_subarray_sum([2,3,4,1,5], 1) == 5"
] | Certainly! You can solve the problem of finding the maximum sum of a subarray of length exactly \( k \) using a sliding window technique. Here's a Python function that implements this approach:
```python
def max_sum_subarray(arr, k):
if len(arr) < k or k <= 0:
return "Invalid input: k should be less than o... | 19,422 | [
{
"from": "human",
"value": "Write a python function to find the maximum sum of a subarray with the length of exactly k."
},
{
"from": "gpt",
"value": "Certainly! You can solve the problem of finding the maximum sum of a subarray of length exactly \\( k \\) using a sliding window technique. Here... |
Write a python function to remove all empty lists from a given list of lists. | Here is the code to solve this problem:
```python
def remove_empty_lists(lst):
return [sublist for sublist in lst if sublist != []]
``` | [
"assert remove_empty_lists([[1,2],[],[3,4],[],[],[5]]) == [[1, 2], [3, 4], [5]]",
"assert remove_empty_lists([[],[],[]]) == []",
"assert remove_empty_lists([[],[],[],[1]]) == [[1]]"
] | You can create a Python function to remove all empty lists from a given list of lists by using a list comprehension. Here’s a simple implementation:
```python
def remove_empty_lists(lists):
return [lst for lst in lists if lst] # Only include non-empty lists
# Example usage:
example_lists = [[], [1, 2, 3], [], [4... | 19,423 | [
{
"from": "human",
"value": "Write a python function to remove all empty lists from a given list of lists."
},
{
"from": "gpt",
"value": "You can create a Python function to remove all empty lists from a given list of lists by using a list comprehension. Here’s a simple implementation:\n\n```pyt... |
Write a python function `reverse_string_words(sentence: str) -> str` that takes a sentence as input and returns a new sentence where the order of the words is reversed but the order of characters within each word remains the same. | Here is the code to solve this problem:
```python
def reverse_string_words(sentence: str) -> str:
words = sentence.split()
return ' '.join(reversed(words))
``` | [
"assert reverse_string_words(\"Hello World\") == \"World Hello\"",
"assert reverse_string_words(\"Python is fun\") == \"fun is Python\"",
"assert reverse_string_words(\"\") == \"\""
] | Certainly! Here's a Python function that reverses the order of words in a given sentence while maintaining the order of characters within each word:
```python
def reverse_string_words(sentence: str) -> str:
# Split the sentence into words
words = sentence.split()
# Reverse the order of words
reversed_w... | 19,424 | [
{
"from": "human",
"value": "Write a python function `reverse_string_words(sentence: str) -> str` that takes a sentence as input and returns a new sentence where the order of the words is reversed but the order of characters within each word remains the same."
},
{
"from": "gpt",
"value": "Certa... |
Write a python function that takes a list of integers as an argument and returns a list of the squares of all the even numbers in the list. | Here is the code to solve this problem:
```python
def square_even_numbers(numbers):
return [num**2 for num in numbers if num % 2 == 0]
``` | [
"assert square_even_numbers([1, 2, 3, 4, 5, 6]) == [4, 16, 36]",
"assert square_even_numbers([9, 11, 13]) == []",
"assert square_even_numbers([10, 3, 7, 2]) == [100, 4]"
] | Certainly! Here’s a Python function that takes a list of integers as an argument and returns a list containing the squares of all the even numbers from that list:
```python
def square_even_numbers(nums):
return [x ** 2 for x in nums if x % 2 == 0]
# Example usage:
# nums = [1, 2, 3, 4, 5, 6]
# result = square_eve... | 19,425 | [
{
"from": "human",
"value": "Write a python function that takes a list of integers as an argument and returns a list of the squares of all the even numbers in the list."
},
{
"from": "gpt",
"value": "Certainly! Here’s a Python function that takes a list of integers as an argument and returns a l... |
Write a function to remove duplicate characters from a given string while preserving the original order of characters. | Here is the code to solve this problem:
```python
def remove_duplicate(input_string):
result = []
seen = set()
for char in input_string:
if char not in seen:
result.append(char)
seen.add(char)
return ''.join(result)
``` | [
"assert remove_duplicate(\"programming\") == \"progamin\"",
"assert remove_duplicate(\"python\") == \"python\"",
"assert remove_duplicate(\"aaaabbbbcccc\") == \"abc\""
] | You can create a function in Python that removes duplicate characters from a string while preserving the order of their first appearance. Here's a simple implementation:
```python
def remove_duplicates(input_string):
seen = set()
output = []
for char in input_string:
if char not in seen:
... | 19,426 | [
{
"from": "human",
"value": "Write a function to remove duplicate characters from a given string while preserving the original order of characters."
},
{
"from": "gpt",
"value": "You can create a function in Python that removes duplicate characters from a string while preserving the order of the... |
Write a function that takes a list of integers as input and returns the list sorted in descending order using the bubble sort algorithm. | Here is the code to solve this problem:
```python
def bubble_sort_desc(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] < arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
``` | [
"assert bubble_sort_desc([5, 3, 8, 4, 2]) == [8, 5, 4, 3, 2]",
"assert bubble_sort_desc([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]",
"assert bubble_sort_desc([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]"
] | Certainly! Below is a Python function that implements the bubble sort algorithm to sort a list of integers in descending order.
```python
def bubble_sort_descending(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in ra... | 19,427 | [
{
"from": "human",
"value": "Write a function that takes a list of integers as input and returns the list sorted in descending order using the bubble sort algorithm."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that implements the bubble sort algorithm to sort a list of i... |
Write a function to find the smallest subarray sum in a list of integers. | Here is the code to solve this problem:
```python
def smallest_subarray_sum(nums):
min_sum = nums[0]
current_sum = nums[0]
for num in nums[1:]:
current_sum = min(num, current_sum + num)
min_sum = min(min_sum, current_sum)
return min_sum
``` | [
"assert smallest_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == -5",
"assert smallest_subarray_sum([1, 2, 3, 4, 5]) == 1",
"assert smallest_subarray_sum([-1, -2, -3, -4, -5]) == -15"
] | Certainly! Below is a Python function that finds the smallest subarray sum in a list of integers. The approach uses a modified version of Kadane's algorithm to keep track of the smallest subarray sum while iterating through the list.
Here’s the implementation:
```python
def smallest_subarray_sum(nums):
if not num... | 19,428 | [
{
"from": "human",
"value": "Write a function to find the smallest subarray sum in a list of integers."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that finds the smallest subarray sum in a list of integers. The approach uses a modified version of Kadane's algorithm to ke... |
Write a function that takes a list of strings and returns True if all strings in the list are unique, False otherwise. | Here is the code to solve this problem:
```python
def are_all_strings_unique(strings):
return len(set(strings)) == len(strings)
``` | [
"assert are_all_strings_unique([\"apple\", \"banana\", \"apple\"]) == False",
"assert are_all_strings_unique([\"apple\", \"banana\", \"cherry\"]) == True",
"assert are_all_strings_unique([\"a\", \"b\", \"c\", \"d\", \"e\"]) == True",
"assert are_all_strings_unique([\"apple\", \"banana\", \"cherry\", \"apple\"... | You can achieve this by writing a function that utilizes a set to track the unique strings. Here’s a Python function to do that:
```python
def are_strings_unique(strings):
# Use a set to track unique strings
unique_strings = set()
for string in strings:
# Check if the string is already in the ... | 19,429 | [
{
"from": "human",
"value": "Write a function that takes a list of strings and returns True if all strings in the list are unique, False otherwise."
},
{
"from": "gpt",
"value": "You can achieve this by writing a function that utilizes a set to track the unique strings. Here’s a Python function ... |
Write a function to find the number of subarrays in a given array which have a given sum. | Here is the code to solve this problem:
```python
def num_subarrays_with_sum(nums, target):
count = 0
current_sum = 0
sum_dict = {0: 1}
for num in nums:
current_sum += num
if current_sum - target in sum_dict:
count += sum_dict[current_sum - target]
if current_sum in... | [
"assert num_subarrays_with_sum([1,1,1,1,1], 3) == 3",
"assert num_subarrays_with_sum([0,0,0,0,0], 0) == 15",
"assert num_subarrays_with_sum([1,0,1,0,1], 2) == 4"
] | To find the number of subarrays in a given array that have a specific sum, we can utilize a hashmap (or dictionary) to store the cumulative sums of the elements while traversing the array. This allows us to efficiently count the number of subarrays that sum to the desired value.
Here's a Python function that accomplis... | 19,430 | [
{
"from": "human",
"value": "Write a function to find the number of subarrays in a given array which have a given sum."
},
{
"from": "gpt",
"value": "To find the number of subarrays in a given array that have a specific sum, we can utilize a hashmap (or dictionary) to store the cumulative sums o... |
Write a function to find the median of a list of integers using the QuickSelect algorithm. | Here is the code to solve this problem:
```python
import random
def QuickSelect(nums,k):
## select kth element in nums
small,large,pivot = [],[],[]
pivot_num = nums[random.randint(0,len(nums)-1)]
for num in nums:
if num < pivot_num:
small.append(num)
elif num == pivot_num:
... | [
"assert QuickMedian([3, 4, 2, 5, 7, 9, 10, 14, 11, 5, 7])==7",
"assert QuickMedian([1, 2, 3, 4])==2.5",
"assert QuickMedian([1, 2, 3, 4, 5])==3"
] | Certainly! The QuickSelect algorithm is an efficient algorithm for finding the k-th smallest (or largest) element in an unordered list. To find the median, we can utilize this method. The median is defined as the middle value of a sorted list; if the list has an odd number of elements, it's the middle element, and if i... | 19,431 | [
{
"from": "human",
"value": "Write a function to find the median of a list of integers using the QuickSelect algorithm."
},
{
"from": "gpt",
"value": "Certainly! The QuickSelect algorithm is an efficient algorithm for finding the k-th smallest (or largest) element in an unordered list. To find t... |
Write a python function to find the last index of a given element in a list. | Here is the code to solve this problem:
```python
def find_last_index(arr, target):
last_index = -1
for i in range(len(arr)):
if arr[i] == target:
last_index = i
return last_index
``` | [
"assert find_last_index([1, 2, 3, 4, 5], 6) == -1",
"assert find_last_index([1, 2, 3, 4, 4, 4, 4], 4) == 6",
"assert find_last_index([1, 2, 3, 2, 5], 2) == 3"
] | You can create a Python function that finds the last index of a given element in a list by using the `rfind()` method of the list, or by iterating from the end to the beginning. Here is a simple implementation using a for loop:
```python
def find_last_index(lst, element):
"""Returns the last index of a given eleme... | 19,432 | [
{
"from": "human",
"value": "Write a python function to find the last index of a given element in a list."
},
{
"from": "gpt",
"value": "You can create a Python function that finds the last index of a given element in a list by using the `rfind()` method of the list, or by iterating from the end... |
Write a python function to check if a given string is a palindrome or not. | Here is the code to solve this problem:
```python
def palindrome_checker(s):
return s == s[::-1]
``` | [
"assert palindrome_checker(\"python\") == False",
"assert palindrome_checker(\"racecar\") == True",
"assert palindrome_checker(\"123456\") == False",
"assert palindrome_checker(\"madam\") == True",
"assert palindrome_checker(\"12321\") == True"
] | Certainly! A palindrome is a string that reads the same forwards and backwards. Here’s a Python function to check if a given string is a palindrome:
```python
def is_palindrome(s):
# Remove any non-alphanumeric characters and convert to lowercase
cleaned_string = ''.join(char.lower() for char in s if char.isal... | 19,433 | [
{
"from": "human",
"value": "Write a python function to check if a given string is a palindrome or not."
},
{
"from": "gpt",
"value": "Certainly! A palindrome is a string that reads the same forwards and backwards. Here’s a Python function to check if a given string is a palindrome:\n\n```python... |
Write a python function to find the middle element of a given list. If the list has an even number of elements, return the two middle elements. | Here is the code to solve this problem:
```python
def find_middle(lst):
n = len(lst)
middle = n // 2
if n % 2 == 0:
return lst[middle-1:middle+1]
else:
return lst[middle]
``` | [
"assert find_middle([1,2,3,4,5]) == 3",
"assert find_middle([1,2,3,4]) == [2,3]",
"assert find_middle([1,2,3,4,5,6]) == [3,4]"
] | You can achieve this by creating a function that checks the length of the list and calculates the middle index or indices accordingly. Here is a Python function that does just that:
```python
def find_middle_element(lst):
if not lst: # Check if the list is empty
return None # Return None for an empty lis... | 19,434 | [
{
"from": "human",
"value": "Write a python function to find the middle element of a given list. If the list has an even number of elements, return the two middle elements."
},
{
"from": "gpt",
"value": "You can achieve this by creating a function that checks the length of the list and calculate... |
Write a python function to find the nth number in the Tribonacci sequence, where each number is the sum of the three preceding ones, starting from 0, 1, 1. | Here is the code to solve this problem:
```python
def find_tribonacci(n):
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
a, b, c = 0, 1, 1
for _ in range(3, n + 1):
a, b, c = b, c, a + b + c
return c
``` | [
"assert find_tribonacci(5) == 7",
"assert find_tribonacci(4) == 4",
"assert find_tribonacci(6) == 13"
] | Sure! The Tribonacci sequence starts with the numbers 0, 1, and 1, and each subsequent number is the sum of the three preceding numbers. Here's a Python function to find the nth number in the Tribonacci sequence:
```python
def tribonacci(n):
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
... | 19,435 | [
{
"from": "human",
"value": "Write a python function to find the nth number in the Tribonacci sequence, where each number is the sum of the three preceding ones, starting from 0, 1, 1."
},
{
"from": "gpt",
"value": "Sure! The Tribonacci sequence starts with the numbers 0, 1, and 1, and each subs... |
Write a function to find the middle node of a singly linked list. | Here is the code to solve this problem:
```python
class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
def find_middle_node(values):
if not values:
return None
head = ListNode(values[0])
current = head
for value in values[1:]:
... | [
"assert find_middle_node([1, 2, 3, 4, 5, 6]) == 4",
"assert find_middle_node([1, 2, 3, 4, 5]) == 3",
"assert find_middle_node([1]) == 1"
] | To find the middle node of a singly linked list, you can use the "two-pointer" technique, often referred to as the "tortoise and hare" algorithm. This approach involves using two pointers that traverse the list at different speeds. Specifically, one pointer moves one step at a time (the slow pointer), while the other m... | 19,436 | [
{
"from": "human",
"value": "Write a function to find the middle node of a singly linked list."
},
{
"from": "gpt",
"value": "To find the middle node of a singly linked list, you can use the \"two-pointer\" technique, often referred to as the \"tortoise and hare\" algorithm. This approach involv... |
Write a function to return the sum of two matrices of the same dimensions. | Here is the code to solve this problem:
```python
def matrix_sum(matrix1, matrix2):
result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix1[0])):
row.append(matrix1[i][j] + matrix2[i][j])
result.append(row)
return result
``` | [
"assert matrix_sum([[1, 2], [3, 4]], [[5, 6], [7, 8]]) == [[6, 8], [10, 12]]",
"assert matrix_sum([[1, -1], [1, -1]], [[-1, 1], [-1, 1]]) == [[0, 0], [0, 0]]",
"assert matrix_sum([[10, 20], [30, 40]], [[5, 15], [25, 35]]) == [[15, 35], [55, 75]]"
] | To perform the sum of two matrices of the same dimensions, you can create a function in Python that takes two matrices (represented as lists of lists) and returns their sum. Here’s an example implementation:
```python
def add_matrices(matrix_a, matrix_b):
# Check if the dimensions of both matrices are the same
... | 19,437 | [
{
"from": "human",
"value": "Write a function to return the sum of two matrices of the same dimensions."
},
{
"from": "gpt",
"value": "To perform the sum of two matrices of the same dimensions, you can create a function in Python that takes two matrices (represented as lists of lists) and return... |
Write a python function to check if a given string is a valid palindrome ignoring case and non-alphanumeric characters. | Here is the code to solve this problem:
```python
import re
def is_Valid_Palindrome(s: str) -> bool:
s = re.sub(r'[^a-zA-Z0-9]', '', s).lower()
return s == s[::-1]
``` | [
"assert is_Valid_Palindrome(\"A man, a plan, a canal: Panama\") == True",
"assert is_Valid_Palindrome(\" \") == True",
"assert is_Valid_Palindrome(\"race a car\") == False"
] | You can create a Python function to check if a given string is a valid palindrome by ignoring case and non-alphanumeric characters. Below is a sample implementation for this task:
```python
import re
def is_valid_palindrome(s: str) -> bool:
# Use regex to filter out non-alphanumeric characters and convert to lowe... | 19,438 | [
{
"from": "human",
"value": "Write a python function to check if a given string is a valid palindrome ignoring case and non-alphanumeric characters."
},
{
"from": "gpt",
"value": "You can create a Python function to check if a given string is a valid palindrome by ignoring case and non-alphanume... |
Write a function that calculates the roots of a quadratic equation ax^2 + bx + c = 0 using the quadratic formula. If the discriminant (b^2 - 4ac) is less than 0 (indicating complex roots), return a pair of complex numbers. If the discriminant is 0 or greater, return a pair of real numbers. | Here is the code to solve this problem:
```python
import math
def quadratic_roots(a, b, c):
discriminant = b**2 - 4*a*c
if discriminant >= 0:
root1 = (-b + math.sqrt(discriminant)) / (2*a)
root2 = (-b - math.sqrt(discriminant)) / (2*a)
return (root1, root2)
else:
real_part =... | [
"assert quadratic_roots(1, 2, 5) == ((-1+2j), (-1-2j))",
"assert quadratic_roots(1, -3, 2) == (2.0, 1.0)",
"assert quadratic_roots(2, 4, 2) == (-1.0, -1.0)",
"assert quadratic_roots(1, 0, -4) == (2.0, -2.0)"
] | You can implement a function to calculate the roots of a quadratic equation using the quadratic formula as follows:
The quadratic formula states that for a quadratic equation of the form \( ax^2 + bx + c = 0 \), the roots can be calculated using:
\[
x = \frac{-b \pm \sqrt{D}}{2a}
\]
where \( D \) is the discriminant... | 19,439 | [
{
"from": "human",
"value": "Write a function that calculates the roots of a quadratic equation ax^2 + bx + c = 0 using the quadratic formula. If the discriminant (b^2 - 4ac) is less than 0 (indicating complex roots), return a pair of complex numbers. If the discriminant is 0 or greater, return a pair of re... |
Write a python function to find the sum of the largest and second largest unique numbers in a given array. | Here is the code to solve this problem:
```python
def find_sum(arr):
unique_nums = list(set(arr))
unique_nums.sort()
if len(unique_nums) >= 2:
return unique_nums[-1] + unique_nums[-2]
else:
return unique_nums[0] * 2
``` | [
"assert find_sum([10,20,20,30,40]) == 70",
"assert find_sum([1,2,3,4,5]) == 9",
"assert find_sum([5,5,5,5,5]) == 10"
] | Certainly! To find the sum of the largest and second largest unique numbers in a given array, you can follow these steps:
1. Convert the array to a set to remove duplicates.
2. Sort the set in descending order.
3. Check if there are at least two unique numbers.
4. Sum the largest and second largest numbers.
Here’s a ... | 19,440 | [
{
"from": "human",
"value": "Write a python function to find the sum of the largest and second largest unique numbers in a given array."
},
{
"from": "gpt",
"value": "Certainly! To find the sum of the largest and second largest unique numbers in a given array, you can follow these steps:\n\n1. C... |
Write a Python function to generate all possible combinations of phone keypad letters for a given string of digits. | Here is the code to solve this problem:
```python
from typing import List
def letter_combinations(digits: str) -> List[str]:
dic = {'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
'6': ['m', 'n', 'o'],
'7': ['p', 'q', '... | [
"assert letter_combinations(\"\") == []",
"assert letter_combinations(\"23\") == [\"ad\", \"ae\", \"af\", \"bd\", \"be\", \"bf\", \"cd\", \"ce\", \"cf\"]",
"assert letter_combinations(\"2\") == [\"a\", \"b\", \"c\"]"
] | To generate all possible combinations of letters corresponding to a string of digits on a phone keypad, you can use a backtracking approach. Each digit maps to a set of letters based on the traditional phone keypad layout:
- 2: "abc"
- 3: "def"
- 4: "ghi"
- 5: "jkl"
- 6: "mno"
- 7: "pqrs"
- 8: "tuv"
- 9: "wxyz"
Here'... | 19,441 | [
{
"from": "human",
"value": "Write a Python function to generate all possible combinations of phone keypad letters for a given string of digits."
},
{
"from": "gpt",
"value": "To generate all possible combinations of letters corresponding to a string of digits on a phone keypad, you can use a ba... |
Write a function that finds the maximum product of two adjacent elements in a list. | Here is the code to solve this problem:
```python
def adjacent_product(numbers):
max_product = numbers[0] * numbers[1]
for i in range(1, len(numbers) - 1):
product = numbers[i] * numbers[i + 1]
if product > max_product:
max_product = product
return max_product
``` | [
"assert adjacent_product([3, 6, -2, -5, 7, 3]) == 21",
"assert adjacent_product([5, 1, 2, 3, 1, 4]) == 6",
"assert adjacent_product([-1, -2, -3, -4]) == 12"
] | Certainly! Below is a Python function that takes a list of numbers as input and returns the maximum product of two adjacent elements in that list.
```python
def max_adjacent_product(lst):
if len(lst) < 2:
raise ValueError("List must contain at least two elements")
max_product = float('-inf') # Start ... | 19,442 | [
{
"from": "human",
"value": "Write a function that finds the maximum product of two adjacent elements in a list."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that takes a list of numbers as input and returns the maximum product of two adjacent elements in that list.\n\n``... |
Write a Python function to check if a given list of numbers contains a Pythagorean triplet. A Pythagorean triplet consists of three positive integers a, b, and c, such that a^2 + b^2 = c^2. | Here is the code to solve this problem:
```python
def check_pythagorean_triplet(nums):
nums_squared = [x**2 for x in nums]
nums_squared.sort()
for i in range(len(nums_squared) - 2):
if nums_squared[i] + nums_squared[i+1] == nums_squared[i+2]:
return True
return False
``` | [
"assert check_pythagorean_triplet([10, 4, 6]) == False",
"assert check_pythagorean_triplet([3, 5, 12, 5, 13]) == True",
"assert check_pythagorean_triplet([8, 15, 17]) == True"
] | Certainly! You can define a Python function to check for the presence of a Pythagorean triplet in a given list of numbers as follows:
```python
def has_pythagorean_triplet(numbers):
# We can use a set to store squares of the numbers for quick lookup
squares = {x ** 2 for x in numbers}
# Check for ever... | 19,443 | [
{
"from": "human",
"value": "Write a Python function to check if a given list of numbers contains a Pythagorean triplet. A Pythagorean triplet consists of three positive integers a, b, and c, such that a^2 + b^2 = c^2."
},
{
"from": "gpt",
"value": "Certainly! You can define a Python function to... |
Write a python function to find the longest palindrome substring from the given string. | Here is the code to solve this problem:
```python
def find_Longest_Palindrome(s: str) -> str:
if len(s) == 0:
return 0
max_len = 1
start = 0
for i in range(len(s)):
if i - max_len >= 1 and s[i - max_len - 1: i + 1] == s[i - max_len - 1: i + 1][::-1]:
start = i - max_len - 1
... | [
"assert find_Longest_Palindrome(\"babad\") == \"bab\"",
"assert find_Longest_Palindrome(\"a\") == \"a\"",
"assert find_Longest_Palindrome(\"cbbd\") == \"bb\""
] | To find the longest palindromic substring in a given string, you can use a method that expands around potential centers of the palindrome. Here’s a Python function that implements this approach:
```python
def longest_palindrome(s: str) -> str:
if not s or len(s) < 1:
return ""
start, end = 0, 0
f... | 19,444 | [
{
"from": "human",
"value": "Write a python function to find the longest palindrome substring from the given string."
},
{
"from": "gpt",
"value": "To find the longest palindromic substring in a given string, you can use a method that expands around potential centers of the palindrome. Here’s a ... |
Write a function that takes a list of integers as an input and returns the length of the longest zigzag subsequence in the list. A zigzag sequence is defined as a sequence where the differences between successive numbers strictly alternate between positive and negative. | Here is the code to solve this problem:
```python
def longestZigzag(nums):
if len(nums) < 2:
return len(nums)
up = [1] * len(nums)
down = [1] * len(nums)
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
up[i] = down[i - 1] + 1
elif nums[i] < nums[i - 1]:
... | [
"assert longestZigzag([1, 2, 3, 4, 5, 6, 7, 8, 9]) == 2",
"assert longestZigzag([1, 7, 4, 9, 2, 5]) == 6",
"assert longestZigzag([10, 22, 9, 33, 21, 50, 41, 60, 80]) == 8"
] | To solve the problem of finding the length of the longest zigzag subsequence in a list of integers, we can use a dynamic programming approach. A zigzag sequence alternates between increasing and decreasing. We'll maintain two lists (or values) that track the lengths of the longest zigzag subsequences ending at each pos... | 19,445 | [
{
"from": "human",
"value": "Write a function that takes a list of integers as an input and returns the length of the longest zigzag subsequence in the list. A zigzag sequence is defined as a sequence where the differences between successive numbers strictly alternate between positive and negative."
},
... |
Write a python function to find all the unique quadruplets in the array which gives the sum of the target. | Here is the code to solve this problem:
```python
def find_quadruplets(nums, target):
n = len(nums)
quads = []
nums.sort()
for i in range(n):
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n):
if j > i + 1 and nums[j] == nums[j - 1]:
... | [
"assert find_quadruplets([-3, -2, -1, 0, 0, 1, 2, 3], 0) == [[-3, -2, 2, 3], [-3, -1, 1, 3], [-3, 0, 0, 3], [-3, 0, 1, 2], [-2, -1, 0, 3], [-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]",
"assert find_quadruplets([1, 0, -1, 0, -2, 2], 0) == [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]",
"assert find_quadruplet... | To find all unique quadruplets in an array that sum up to a given target, we can use a combination of sorting the array and using a two-pointer technique. Here's a Python function that implements this approach:
```python
def four_sum(nums, target):
nums.sort() # Sort the array to make it easier to manage duplicat... | 19,446 | [
{
"from": "human",
"value": "Write a python function to find all the unique quadruplets in the array which gives the sum of the target."
},
{
"from": "gpt",
"value": "To find all unique quadruplets in an array that sum up to a given target, we can use a combination of sorting the array and using... |
Write a python function to check if a string is an anagram of a palindrome. | Here is the code to solve this problem:
```python
from collections import Counter
def is_palindrome_anagram(s: str) -> bool:
s = Counter(s)
odd_counts = 0
for value in s.values():
if value % 2 != 0:
odd_counts += 1
if odd_counts > 1:
return False
return True
``` | [
"assert is_palindrome_anagram(\"hello\") == False",
"assert is_palindrome_anagram(\"carrace\") == True",
"assert is_palindrome_anagram(\"aabbcc\") == True"
] | To determine if a string is an anagram of a palindrome, we need to consider the characteristics of palindromes. A palindrome reads the same forward and backward, which means that for a string to be an anagram of a palindrome, the character counts must adhere to certain rules:
1. If the string has an even length, all c... | 19,447 | [
{
"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 consider the characteristics of palindromes. A palindrome reads the same forward and backward... |
Write a function to find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. | Here is the code to solve this problem:
```python
from typing import List
def combine_sum(k: int, n: int) -> List[List[int]]:
def dfs(k, n, start, path, res):
if k < 0 or n < 0:
return
if k == 0 and n == 0:
res.append(path)
return
for i in range(start,... | [
"assert combine_sum(3, 7) == [[1, 2, 4]]",
"assert combine_sum(3, 9) == [[1, 2, 6], [1, 3, 5], [2, 3, 4]]",
"assert combine_sum(4, 1) == []"
] | You can solve the problem of finding all unique combinations of `k` numbers that add up to `n`, using only numbers from 1 to 9, by using a backtracking approach. Below is a Python function that implements this algorithm:
```python
def combinationSum3(k, n):
def backtrack(start, path, remaining_k, remaining_n):
... | 19,448 | [
{
"from": "human",
"value": "Write a function to find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers."
},
{
"from": "gpt",
"value": "You can solve the problem of finding all ... |
Write a function to find the maximum number of coins you can pick up from the piles of coins arranged in a line. You can't pick up two adjacent piles of coins. | Here is the code to solve this problem:
```python
def pick_coins(coins):
pick = skip = 0
for coin in coins:
new_pick = skip + coin
new_skip = max(pick, skip)
pick, skip = new_pick, new_skip
return max(pick, skip)
``` | [
"assert pick_coins([2, 7, 9, 3, 1]) == 12",
"assert pick_coins([5, 5, 10, 100, 10, 5]) == 110",
"assert pick_coins([1, 2, 3, 2]) == 4"
] | To solve the problem of finding the maximum number of coins you can pick up from the piles while ensuring you do not pick coins from two adjacent piles, we can approach it using dynamic programming.
Here's the breakdown of the solution:
1. **Define the Problem**: Let’s denote the number of piles of coins as `n` and t... | 19,449 | [
{
"from": "human",
"value": "Write a function to find the maximum number of coins you can pick up from the piles of coins arranged in a line. You can't pick up two adjacent piles of coins."
},
{
"from": "gpt",
"value": "To solve the problem of finding the maximum number of coins you can pick up ... |
Write a function that takes a list of strings and returns a list of strings with the first letter of each string capitalized. | Here is the code to solve this problem:
```python
def capitalize_first_letter(lst):
return [word.capitalize() for word in lst]
``` | [
"assert capitalize_first_letter([\"python\", \"java\", \"c++\"]) == [\"Python\", \"Java\", \"C++\"]",
"assert capitalize_first_letter([\"hadoop\", \"spark\", \"hive\"]) == [\"Hadoop\", \"Spark\", \"Hive\"]",
"assert capitalize_first_letter([\"bigdata\", \"analytics\", \"ai\"]) == [\"Bigdata\", \"Analytics\", \"... | You can achieve this by defining a function that uses Python's built-in string method `.capitalize()`, which capitalizes the first letter of a string and converts the rest to lowercase. Here’s how you can implement this function:
```python
def capitalize_first_letters(strings):
# Use a list comprehension to capita... | 19,450 | [
{
"from": "human",
"value": "Write a function that takes a list of strings and returns a list of strings with the first letter of each string capitalized."
},
{
"from": "gpt",
"value": "You can achieve this by defining a function that uses Python's built-in string method `.capitalize()`, which c... |
Write a function to count the frequency of words in a given list of strings. | Here is the code to solve this problem:
```python
def word_freq(words):
freq = {}
for word in words:
if word in freq:
freq[word] += 1
else:
freq[word] = 1
return freq
``` | [
"assert word_freq([\"apple\", \"banana\", \"apple\", \"orange\", \"banana\", \"apple\"]) == {\"apple\": 3, \"banana\": 2, \"orange\": 1}",
"assert word_freq([\"python\", \"java\", \"python\", \"c++\", \"java\", \"python\"]) == {\"python\": 3, \"java\": 2, \"c++\": 1}",
"assert word_freq([\"red\", \"green\", \"b... | Certainly! You can count the frequency of words in a given list of strings using Python. Below is a function that takes a list of strings as input and returns a dictionary with the words as keys and their frequencies as values.
```python
from collections import Counter
import re
def count_word_frequency(strings_list)... | 19,451 | [
{
"from": "human",
"value": "Write a function to count the frequency of words in a given list of strings."
},
{
"from": "gpt",
"value": "Certainly! You can count the frequency of words in a given list of strings using Python. Below is a function that takes a list of strings as input and returns ... |
Write a python function to find the first duplicate number in an array of integers. If there is no duplicate, return -1. | Here is the code to solve this problem:
```python
def first_duplicate(arr):
checked_numbers = set()
for num in arr:
if num in checked_numbers:
return num
checked_numbers.add(num)
return -1
``` | [
"assert first_duplicate([1, 2, 3, 2, 1]) == 2",
"assert first_duplicate([1, 2, 3, 4, 5]) == -1",
"assert first_duplicate([3, 1, 3, 4, 2]) == 3"
] | You can find the first duplicate number in an array of integers using a Python function. One effective way to do this is by using a set to keep track of the numbers you've seen as you iterate through the array. Here's a function that implements this approach:
```python
def first_duplicate(arr):
seen = set() # To ... | 19,452 | [
{
"from": "human",
"value": "Write a python function to find the first duplicate number in an array of integers. If there is no duplicate, return -1."
},
{
"from": "gpt",
"value": "You can find the first duplicate number in an array of integers using a Python function. One effective way to do th... |
Write a python function that checks if a given string is a palindrome ignoring case, spaces, and punctuation. | Here is the code to solve this problem:
```python
import re
def is_palindrome_ignore_cases(s: str) -> bool:
s = re.sub(r'[\W_]', '', s.lower())
return s == s[::-1]
``` | [
"assert is_palindrome_ignore_cases('A man, a plan, a canal: Panama') == True",
"assert is_palindrome_ignore_cases('race a car') == False",
"assert is_palindrome_ignore_cases('Was it a car or a cat I saw?') == True"
] | To determine if a given string is a palindrome while ignoring case, spaces, and punctuation, you can follow these steps:
1. Normalize the string by converting it to lower case.
2. Remove any characters that are not alphanumeric.
3. Check if the resulting string is the same when read forwards and backwards.
Here’s a P... | 19,453 | [
{
"from": "human",
"value": "Write a python function that checks if a given string is a palindrome ignoring case, spaces, and punctuation."
},
{
"from": "gpt",
"value": "To determine if a given string is a palindrome while ignoring case, spaces, and punctuation, you can follow these steps:\n\n1.... |
Write a function to find the maximum length of a mountain in an array of integers. A mountain is defined as a subarray where the values increase up to a peak and then decrease. The function should return the length of the longest mountain found in the array. | Here is the code to solve this problem:
```python
def longest_mountain(arr):
n = len(arr)
longest = 0
i = 1
while i < n - 1:
is_peak = arr[i - 1] < arr[i] > arr[i + 1]
if not is_peak:
i += 1
continue
left = i - 2
right = i + 2
while left >... | [
"assert longest_mountain([0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0]) == 11",
"assert longest_mountain([2, 2, 2]) == 0",
"assert longest_mountain([2, 1, 4, 7, 3, 2, 5]) == 5"
] | To solve the problem of finding the maximum length of a mountain in an array of integers, we can use a simple algorithm that scans through the array while keeping track of potential mountain peaks.
Here's how we can define a function to achieve this:
1. We iterate through the array, checking for a valid peak where t... | 19,454 | [
{
"from": "human",
"value": "Write a function to find the maximum length of a mountain in an array of integers. A mountain is defined as a subarray where the values increase up to a peak and then decrease. The function should return the length of the longest mountain found in the array."
},
{
"from"... |
Write a function to find the largest possible number that can be formed by rearranging the digits of a given number. | Here is the code to solve this problem:
```python
def largest_possible_number(n):
str_num = str(n)
arr = list(str_num)
arr.sort(reverse=True)
return int(''.join(arr))
``` | [
"assert largest_possible_number(9827) == 9872",
"assert largest_possible_number(123) == 321",
"assert largest_possible_number(3401) == 4310"
] | You can create a function in Python to find the largest possible number that can be formed by rearranging the digits of a given integer. Here’s a simple implementation:
```python
def largest_rearrangement(n):
# Convert the number to a string to access its digits
digit_str = str(n)
# Convert the string... | 19,455 | [
{
"from": "human",
"value": "Write a function to find the largest possible number that can be formed by rearranging the digits of a given number."
},
{
"from": "gpt",
"value": "You can create a function in Python to find the largest possible number that can be formed by rearranging the digits of... |
Implement a function in Python that finds the greatest common divisor (GCD) of two positive integers using the Euclidean algorithm. The function should take two integers as input and return the GCD as output. The Euclidean algorithm states that the GCD of two numbers does not change if the larger number is replaced by ... | Here is the code to solve this problem:
```python
def euclidean_gcd(a, b):
while b:
a, b = b, a % b
return a
``` | [
"assert euclidean_gcd(48, 18) == 6",
"assert euclidean_gcd(40, 60) == 20",
"assert euclidean_gcd(56, 98) == 14"
] | Certainly! Here is a Python function that implements the Euclidean algorithm to find the greatest common divisor (GCD) of two positive integers:
```python
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
# Example usage:
num1 = 56
num2 = 98
result = gcd(num1, num2)
print(f"The GCD of {num1} and {... | 19,456 | [
{
"from": "human",
"value": "Implement a function in Python that finds the greatest common divisor (GCD) of two positive integers using the Euclidean algorithm. The function should take two integers as input and return the GCD as output. The Euclidean algorithm states that the GCD of two numbers does not ch... |
Write a python function to find the smallest number that can be formed with the given digits. | Here is the code to solve this problem:
```python
def find_Min_Num(arr,n) :
arr.sort()
num = arr[0]
for i in range(1,n) :
num = num * 10 + arr[i]
return num
``` | [
"assert find_Min_Num([1,2,3,9],4) == 1239",
"assert find_Min_Num([1,2,3],3) == 123",
"assert find_Min_Num([4,5,6,1],4) == 1456"
] | You can create a Python function that takes a list of digits as input and returns the smallest number that can be formed using those digits. Here’s a simple implementation of the function:
```python
def smallest_number(digits):
# Convert the list of digits to strings
str_digits = list(map(str, digits))
... | 19,457 | [
{
"from": "human",
"value": "Write a python function to find the smallest number that can be formed with the given digits."
},
{
"from": "gpt",
"value": "You can create a Python function that takes a list of digits as input and returns the smallest number that can be formed using those digits. H... |
Write a function to find the majority elements in an array. An element is said to be a majority element if it appears more than n/3 times (where n is the size of the array). | Here is the code to solve this problem:
```python
from collections import defaultdict
def find_majority_elements(nums):
N = len(nums)//3
store = defaultdict(float)
result = []
for num in nums:
store[num] += 1
if(store[num] > N):
store[num] = float("-inf")
resul... | [
"assert find_majority_elements([3, 2, 3])==[3]",
"assert find_majority_elements([1, 2, 3, 4])==[]",
"assert find_majority_elements([1, 1, 1, 3, 3, 2, 2, 2])==[1, 2]"
] | To find the majority element(s) in an array where an element is considered a majority if it appears more than `n/3` times, we can use the Boyer-Moore Voting Algorithm. This algorithm is efficient and can find majority elements in linear time and constant space.
Here's an implementation of this algorithm in Python:
``... | 19,458 | [
{
"from": "human",
"value": "Write a function to find the majority elements in an array. An element is said to be a majority element if it appears more than n/3 times (where n is the size of the array)."
},
{
"from": "gpt",
"value": "To find the majority element(s) in an array where an element i... |
Write a function to calculate the binomial coefficient of given n and k. The binomial coefficient is defined as the number of ways to choose k elements out of n elements without considering the order. It is often represented as "n choose k" or C(n, k). | Here is the code to solve this problem:
```python
def binomial_coefficient(n, k):
if k > n:
return 0
if k == 0 or k == n:
return 1
c = [[0 for x in range(k+1)] for x in range(n+1)]
for i in range(n+1):
for j in range(min(i, k)+1):
if j == 0 or j == i:
... | [
"assert binomial_coefficient(5, 2) == 10",
"assert binomial_coefficient(10, 3) == 120",
"assert binomial_coefficient(6, 6) == 1"
] | To calculate the binomial coefficient, commonly represented as \( C(n, k) \) or "n choose k", you can use the formula:
\[
C(n, k) = \frac{n!}{k! \cdot (n - k)!}
\]
where \( n! \) (n factorial) is the product of all positive integers up to \( n \).
Here's a Python function to calculate the binomial coefficient using ... | 19,459 | [
{
"from": "human",
"value": "Write a function to calculate the binomial coefficient of given n and k. The binomial coefficient is defined as the number of ways to choose k elements out of n elements without considering the order. It is often represented as \"n choose k\" or C(n, k)."
},
{
"from": "g... |
Write a function to find the largest product that can be obtained from a contiguous subarray within a given array of integers. | Here is the code to solve this problem:
```python
def largest_product_subarray(nums):
if not nums:
return 0
max_product = min_product = result = nums[0]
for num in nums[1:]:
choices = (num, num * max_product, num * min_product)
max_product = max(choices)
min_product = min(... | [
"assert largest_product_subarray([-2,-3,-4]) == 12",
"assert largest_product_subarray([2,3,-2,4]) == 6",
"assert largest_product_subarray([-2,0,-1]) == 0"
] | Certainly! To find the largest product that can be obtained from a contiguous subarray within a given array of integers, you can follow these steps:
1. Initialize three variables:
- `max_product` to keep track of the maximum product found so far.
- `min_product` to keep track of the minimum product (in case ther... | 19,460 | [
{
"from": "human",
"value": "Write a function to find the largest product that can be obtained from a contiguous subarray within a given array of integers."
},
{
"from": "gpt",
"value": "Certainly! To find the largest product that can be obtained from a contiguous subarray within a given array o... |
Write a function that checks if a given string matches a regular expression pattern. The function should return True if the string matches the pattern, and False otherwise. The regular expression pattern will contain lowercase letters, '.', and '*'. The '.' matches any single character, while the '*' matches zero or mo... | Here is the code to solve this problem:
```python
def is_match(s: str, p: str) -> bool:
dp = [[False] * (len(p) + 1) for _ in range(len(s) + 1)]
dp[-1][-1] = True
for i in range(len(s), -1, -1):
for j in range(len(p) - 1, -1, -1):
first_match = i < len(s) and p[j] in {s[i], '.'}
... | [
"assert is_match(\"aa\", \"a\") == False",
"assert is_match(\"aa\", \"a*\") == True",
"assert is_match(\"ab\", \".*\") == True",
"assert is_match(\"aab\", \"c*a*b\") == True",
"assert is_match(\"mississippi\", \"mis*is*p*.\") == False"
] | To check if a given string matches a regular expression pattern with the specified syntax, you can use the `re` module in Python. Specifically, you can utilize the `re.fullmatch()` function, which checks if the entire string matches the pattern. Below is a function that implements this:
```python
import re
def is_mat... | 19,461 | [
{
"from": "human",
"value": "Write a function that checks if a given string matches a regular expression pattern. The function should return True if the string matches the pattern, and False otherwise. The regular expression pattern will contain lowercase letters, '.', and '*'. The '.' matches any single ch... |
Write a python function to calculate the sum of the elements in a list using recursion. | Here is the code to solve this problem:
```python
def recursive_sum(nums):
if len(nums) == 0:
return 0
else:
return nums[0] + recursive_sum(nums[1:])
``` | [
"assert recursive_sum([100]) == 100",
"assert recursive_sum([10, 20, 30]) == 60",
"assert recursive_sum([1, 2, 3, 4]) == 10"
] | Certainly! You can calculate the sum of the elements in a list using recursion in Python by defining a function that adds the first element of the list to the sum of the remaining elements. Here's how you can implement this:
```python
def recursive_sum(lst):
# Base case: if the list is empty, return 0
if not l... | 19,462 | [
{
"from": "human",
"value": "Write a python function to calculate the sum of the elements in a list using recursion."
},
{
"from": "gpt",
"value": "Certainly! You can calculate the sum of the elements in a list using recursion in Python by defining a function that adds the first element of the l... |
Write a python function that takes a list of integers and a target integer. The function will return the index of the target integer in the list if it is present. If the target integer is not present in the list, the function will return the index where the target should be inserted in order to maintain the list's sort... | Here is the code to solve this problem:
```python
def find_or_insert(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
... | [
"assert find_or_insert( [1,3,5,6], 0 ) == 0",
"assert find_or_insert( [1,3,5,6], 2 ) == 1",
"assert find_or_insert( [1,3,5,6], 7 ) == 4",
"assert find_or_insert( [1,3,5,6], 5 ) == 2"
] | To achieve this, you can implement a function that leverages binary search. This will allow you to efficiently find the index of the target integer or determine where it should be inserted in a sorted list. Here’s how you can do this:
```python
def find_insert_index(nums, target):
left, right = 0, len(nums)
w... | 19,463 | [
{
"from": "human",
"value": "Write a python function that takes a list of integers and a target integer. The function will return the index of the target integer in the list if it is present. If the target integer is not present in the list, the function will return the index where the target should be inse... |
Write a function to find the smallest subsequence of a given string that contains all distinct characters of the string in the same order they appear in the string. | Here is the code to solve this problem:
```python
def smallest_subsequence(s: str) -> str:
last_occurences = {s[i]: i for i in range(len(s))}
S, i = [], -1
for char in s:
i += 1
if char not in S:
while S and i < last_occurences[S[-1]] and char < S[-1]:
... | [
"assert smallest_subsequence('abcd') == 'abcd'",
"assert smallest_subsequence('cdadabcc') == 'adbc'",
"assert smallest_subsequence('ecbacba') == 'eacb'",
"assert smallest_subsequence('leetcode') == 'letcod'"
] | To solve the problem of finding the smallest subsequence of a given string that contains all distinct characters in the order they appear, we can approach this by maintaining a few key pieces of information:
1. The set of distinct characters.
2. The frequency of each character in the original string.
3. The resulting... | 19,464 | [
{
"from": "human",
"value": "Write a function to find the smallest subsequence of a given string that contains all distinct characters of the string in the same order they appear in the string."
},
{
"from": "gpt",
"value": "To solve the problem of finding the smallest subsequence of a given str... |
Write a function to find the total number of boomerangs in a given list of points. A boomerang is defined as a set of three points that are not collinear, which means the distance from the first point to the second is not equal to the distance from the second point to the third. The function should return the total num... | Here is the code to solve this problem:
```python
from collections import defaultdict
def numberOfBoomerangs(points):
total = 0
for i in range(len(points)):
distance = defaultdict(int)
for j in range(len(points)):
dis = (points[j][0] - points[i][0])**2 + (points[j][1] - points[i][1... | [
"assert numberOfBoomerangs([[1,1],[2,2],[3,3]]) == 2",
"assert numberOfBoomerangs([[0,0],[1,0],[2,0]]) == 2",
"assert numberOfBoomerangs([[1,1]]) == 0"
] | To solve the problem of counting the number of boomerangs that can be formed from a list of points, we can define a function that iterates through each point, treating each point as a potential "center" of a boomerang. For each center point, we will calculate the distances to all other points and use these distances to... | 19,465 | [
{
"from": "human",
"value": "Write a function to find the total number of boomerangs in a given list of points. A boomerang is defined as a set of three points that are not collinear, which means the distance from the first point to the second is not equal to the distance from the second point to the third.... |
Write a function that takes in a list of integers and an integer k, and returns the number of pairs of numbers in the list that sum up to a multiple of k. | Here is the code to solve this problem:
```python
def count_divisible_pairs(nums, k):
count = 0
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if (nums[i] + nums[j]) % k == 0:
count += 1
return count
``` | [
"assert count_divisible_pairs([1, 3, 2, 6, 1, 2], 3) == 5",
"assert count_divisible_pairs([10, 20, 30, 40, 50], 10) == 10",
"assert count_divisible_pairs([1, 2, 3, 4, 5], 5) == 2"
] | Certainly! To create a function that counts the number of pairs of integers in a list that sum up to a multiple of a given integer \( k \), we can follow these steps:
1. Use a dictionary to track the frequency of the remainders when each element in the list is divided by \( k \).
2. For each element, calculate the rem... | 19,466 | [
{
"from": "human",
"value": "Write a function that takes in a list of integers and an integer k, and returns the number of pairs of numbers in the list that sum up to a multiple of k."
},
{
"from": "gpt",
"value": "Certainly! To create a function that counts the number of pairs of integers in a ... |
Write a function that takes a string as input and checks if it's possible to rearrange the characters of the string such that all the characters 'a', 'b', 'c', 'x', 'y', 'z' appear an even number of times. | Here is the code to solve this problem:
```python
def check_even_distribution(s):
record = {'a': 0, 'b': 0, 'c': 0, 'x': 0, 'y': 0, 'z': 0}
for i in s:
if i in record:
record[i] += 1
for count in record.values():
if count % 2 != 0:
return False
return True
``` | [
"assert check_even_distribution(\"aabc\") == False",
"assert check_even_distribution(\"xyzabcxyzabc\") == True",
"assert check_even_distribution(\"aabbcc\") == True",
"assert check_even_distribution(\"abcxyzz\") == False"
] | To solve the problem of determining whether the characters 'a', 'b', 'c', 'x', 'y', and 'z' can be rearranged in such a way that they all appear an even number of times, we can follow these steps:
1. Count the occurrences of each of the specified characters in the input string.
2. Check if each of these characters has... | 19,467 | [
{
"from": "human",
"value": "Write a function that takes a string as input and checks if it's possible to rearrange the characters of the string such that all the characters 'a', 'b', 'c', 'x', 'y', 'z' appear an even number of times."
},
{
"from": "gpt",
"value": "To solve the problem of determ... |
Write a python function to determine if a given number can be expressed as the sum of any two square numbers. | Here is the code to solve this problem:
```python
import math
def isSumOfSquares(n):
for i in range(0, int(math.sqrt(n)) + 1):
temp = n - (i * i)
if (int(math.sqrt(temp)) ** 2) == temp:
return True
return False
``` | [
"assert isSumOfSquares(10) == True",
"assert isSumOfSquares(3) == False",
"assert isSumOfSquares(5) == True"
] | To determine if a given number can be expressed as the sum of two square numbers, we can utilize a mathematical principle known as Fermat's theorem on sums of two squares. The theorem states that a number can be expressed as a sum of two squares if and only if in its prime factorization, every prime of the form \(4k + ... | 19,468 | [
{
"from": "human",
"value": "Write a python function to determine if a given number can be expressed as the sum of any two square numbers."
},
{
"from": "gpt",
"value": "To determine if a given number can be expressed as the sum of two square numbers, we can utilize a mathematical principle know... |
Create a function to check if a given year is a leap year or not. A leap year is exactly divisible by 4 except for end-of-century years which must be divisible by 400. This means that the year 2000 was a leap year, although 1900 was not. | Here is the code to solve this problem:
```python
def check_leap_year(year):
if year % 400 == 0:
return True
elif year % 100 == 0:
return False
elif year % 4 == 0:
return True
else:
return False
``` | [
"assert check_leap_year(2000) == True",
"assert check_leap_year(2012) == True",
"assert check_leap_year(1900) == False",
"assert check_leap_year(2019) == False"
] | Certainly! Below is a Python function that checks if a given year is a leap year according to the rules you've specified:
```python
def is_leap_year(year):
"""
Determine if a given year is a leap year.
A leap year is exactly divisible by 4,
except for end-of-century years which must be divisible by 40... | 19,469 | [
{
"from": "human",
"value": "Create a function to check if a given year is a leap year or not. A leap year is exactly divisible by 4 except for end-of-century years which must be divisible by 400. This means that the year 2000 was a leap year, although 1900 was not."
},
{
"from": "gpt",
"value":... |
Write a python function that implements the Sieve of Eratosthenes algorithm to find all prime numbers up to a given limit n. | Here is the code to solve this problem:
```python
def primes_up_to_limit(n):
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False
for current in range(2, int(n**0.5) + 1):
if sieve[current]:
for multiple in range(current * current, n + 1, current):
sieve[multiple] = Fals... | [
"assert primes_up_to_limit(1) == []",
"assert primes_up_to_limit(5) == [2, 3, 5]",
"assert primes_up_to_limit(10) == [2, 3, 5, 7]",
"assert primes_up_to_limit(30) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]"
] | Certainly! The Sieve of Eratosthenes is an efficient algorithm to find all prime numbers up to a specified integer \( n \). Below is a Python function that implements this algorithm:
```python
def sieve_of_eratosthenes(n):
"""Return a list of all prime numbers up to n using the Sieve of Eratosthenes algorithm."""
... | 19,470 | [
{
"from": "human",
"value": "Write a python function that implements the Sieve of Eratosthenes algorithm to find all prime numbers up to a given limit n."
},
{
"from": "gpt",
"value": "Certainly! The Sieve of Eratosthenes is an efficient algorithm to find all prime numbers up to a specified inte... |
Write a function to find the maximum length of the subarray with a given sum. | Here is the code to solve this problem:
```python
def max_subarray_with_sum(arr, target_sum):
max_length = 0
current_sum = 0
start_index = 0
sum_dict = {}
for i in range(len(arr)):
current_sum += arr[i]
if current_sum == target_sum:
max_length = i + 1
if current_... | [
"assert max_subarray_with_sum([-2, -1, 2, 1], 1) == 2",
"assert max_subarray_with_sum([1, 2, 3, 4, 5], 9) == 3",
"assert max_subarray_with_sum([1, -1, 5, -2, 3], 3) == 4"
] | Certainly! You can find the maximum length of a subarray with a given sum using a hash map to store the cumulative sums. The idea is to maintain the cumulative sum while iterating through the array. If the cumulative sum minus the target sum has been seen before, it indicates that a subarray with the given sum exists.
... | 19,471 | [
{
"from": "human",
"value": "Write a function to find the maximum length of the subarray with a given sum."
},
{
"from": "gpt",
"value": "Certainly! You can find the maximum length of a subarray with a given sum using a hash map to store the cumulative sums. The idea is to maintain the cumulativ... |
Write a python function to check 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 wordBreak(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
ret... | [
"assert wordBreak(\"leetcode\", [\"leet\", \"code\"]) == True",
"assert wordBreak(\"applepenapple\", [\"apple\", \"pen\"]) == True",
"assert wordBreak(\"catsandog\", [\"cats\", \"dog\", \"sand\", \"and\", \"cat\"]) == False"
] | To solve the problem of checking if a given string can be segmented into a space-separated sequence of one or more dictionary words, we can use a dynamic programming approach. This approach involves creating a boolean array where each index indicates whether the substring of the input string up to that index can be seg... | 19,472 | [
{
"from": "human",
"value": "Write a python function to check if a given string can be segmented into a space-separated sequence of one or more dictionary words."
},
{
"from": "gpt",
"value": "To solve the problem of checking if a given string can be segmented into a space-separated sequence of ... |
Write a python function to perform index wise multiplication of tuple elements in the given two nested tuples. | Here is the code to solve this problem:
```python
def multiply_nested_tuples(test_tup1, test_tup2):
res = tuple(tuple(a * b for a, b in zip(tup1, tup2))
for tup1, tup2 in zip(test_tup1, test_tup2))
return (res)
``` | [
"assert multiply_nested_tuples(((1, 3), (4, 5), (2, 9), (1, 10)), ((6, 7), (3, 9), (1, 1), (7, 3))) == ((6, 21), (12, 45), (2, 9), (7, 30))",
"assert multiply_nested_tuples(((3, 5), (6, 7), (4, 11), (3, 12)), ((8, 9), (5, 11), (3, 3), (9, 5))) == ((24, 45), (30, 77), (12, 33), (27, 60))",
"assert multiply_neste... | You can perform index-wise multiplication of elements in two nested tuples by using a nested loop within a function. Here's a Python function that accomplishes this:
```python
def index_wise_multiplication(tuple1, tuple2):
# Ensure both tuples have the same structure
if len(tuple1) != len(tuple2):
rais... | 19,473 | [
{
"from": "human",
"value": "Write a python function to perform index wise multiplication of tuple elements in the given two nested tuples."
},
{
"from": "gpt",
"value": "You can perform index-wise multiplication of elements in two nested tuples by using a nested loop within a function. Here's a... |
Write a function to find the number of times the digit 1 appears in all numbers from 1 to n (inclusive). | Here is the code to solve this problem:
```python
def count_digit_one(n: int) -> int:
ones = 0
if n <= 0:
return 0
block_size = 10
for _ in range(len(str(n))):
blocks, rem = divmod(n + 1, block_size)
ones += blocks * block_size // 10
ones += min(block_size // 10, max(0, ... | [
"assert count_digit_one(13) == 6",
"assert count_digit_one(50) == 15",
"assert count_digit_one(0) == 0"
] | To count how many times the digit '1' appears in all numbers from 1 to `n`, you can use a function that iterates through each number, converts it to a string, and counts the '1's in that string representation. Here's a straightforward implementation of such a function in Python:
```python
def count_digit_one(n):
c... | 19,474 | [
{
"from": "human",
"value": "Write a function to find the number of times the digit 1 appears in all numbers from 1 to n (inclusive)."
},
{
"from": "gpt",
"value": "To count how many times the digit '1' appears in all numbers from 1 to `n`, you can use a function that iterates through each numbe... |
Write a python function to check if a given 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... | Here is the code to solve this problem:
```python
def check_happy_number(num: int) -> bool:
def get_next(n: int) -> int:
return sum(int(digit) ** 2 for digit in str(n))
seen = set()
while num != 1 and num not in seen:
seen.add(num)
num = get_next(num)
return num == 1
``` | [
"assert check_happy_number(19) == True",
"assert check_happy_number(4) == False",
"assert check_happy_number(2) == False",
"assert check_happy_number(7) == True"
] | To determine if a given number is a happy number, we can implement a Python function that follows the process you've described. Here's the function to check for happy numbers:
```python
def is_happy(n):
def get_next(number):
total_sum = 0
while number > 0:
digit = number % 10
... | 19,475 | [
{
"from": "human",
"value": "Write a python function to check if a given number is a happy number.\n\nA 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 ... |
Write a function to find the nth term of the Fibonacci series using dynamic programming. | Here is the code to solve this problem:
```python
def fib_dp(n):
if n <= 1:
return n
dp = [0] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
``` | [
"assert fib_dp(0) == 0",
"assert fib_dp(1) == 1",
"assert fib_dp(10) == 55"
] | Certainly! The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The nth Fibonacci number can be computed using dynamic programming to ensure that we store previously computed values and avoid redundant calculations.
Here’s a Python functio... | 19,476 | [
{
"from": "human",
"value": "Write a function to find the nth term of the Fibonacci series using dynamic programming."
},
{
"from": "gpt",
"value": "Certainly! The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The... |
Write a function to convert a given decimal number to a binary string, with a prefix and suffix 'bin'. | Here is the code to solve this problem:
```python
def convert_to_binary(number):
return f"bin{bin(number)[2:]}bin"
``` | [
"assert convert_to_binary(15) == \"bin1111bin\"",
"assert convert_to_binary(32) == \"bin100000bin\"",
"assert convert_to_binary(255) == \"bin11111111bin\""
] | You can create a Python function to convert a decimal number to a binary string, while adding the specified prefix and suffix. Here's how you can implement this function:
```python
def decimal_to_binary_with_prefix_suffix(decimal_number):
# Convert the decimal number to binary and remove the '0b' prefix that Pytho... | 19,477 | [
{
"from": "human",
"value": "Write a function to convert a given decimal number to a binary string, with a prefix and suffix 'bin'."
},
{
"from": "gpt",
"value": "You can create a Python function to convert a decimal number to a binary string, while adding the specified prefix and suffix. Here's... |
Write a function to return the largest elements from each column in a given 2D array. | Here is the code to solve this problem:
```python
def largest_in_columns(arr):
# Transpose the 2D array to access columns as rows
transposed = list(zip(*arr))
# Return the max element from each row (originally a column)
return [max(row) for row in transposed]
``` | [
"assert largest_in_columns([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [7, 8, 9]",
"assert largest_in_columns([[10, 20], [15, 25], [13, 21]]) == [15, 25]",
"assert largest_in_columns([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) == [9, 10, 11, 12]"
] | You can accomplish this task using a straightforward approach in Python. Below is a function that takes a 2D list (array) as input and returns a list of the largest elements from each column.
Here's the implementation:
```python
def largest_elements_per_column(array):
if not array:
return []
# number... | 19,478 | [
{
"from": "human",
"value": "Write a function to return the largest elements from each column in a given 2D array."
},
{
"from": "gpt",
"value": "You can accomplish this task using a straightforward approach in Python. Below is a function that takes a 2D list (array) as input and returns a list ... |
Write a function that takes a string as input and returns the number of times the character 'a' appears in it. | Here is the code to solve this problem:
```python
def count_a(s):
count = 0
for char in s:
if char.lower() == 'a':
count += 1
return count
``` | [
"assert count_a('Cherry') == 0",
"assert count_a('banana') == 3",
"assert count_a('Apple') == 1"
] | Certainly! Below is a Python function that takes a string as input and returns the count of occurrences of the character 'a':
```python
def count_a(input_string):
return input_string.count('a')
# Example usage:
input_string = "Java is a popular programming language."
result = count_a(input_string)
print(f"The cha... | 19,479 | [
{
"from": "human",
"value": "Write a function that takes a string as input and returns the number of times the character 'a' appears in it."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that takes a string as input and returns the count of occurrences of the character 'a':... |
Write a python function to find the maximum subarray sum using Kadane's algorithm. | Here is the code to solve this problem:
```python
def kadane_algorithm(arr):
max_current = max_global = arr[0]
for i in range(1, len(arr)):
max_current = max(arr[i], max_current + arr[i])
if max_current > max_global:
max_global = max_current
return max_global
``` | [
"assert kadane_algorithm([-2,1,-3,4,-1,2,1,-5,4]) == 6",
"assert kadane_algorithm([1]) == 1",
"assert kadane_algorithm([-1,-2,-3,-4]) == -1"
] | Sure! Kadane's algorithm is an efficient way to solve the maximum subarray sum problem in linear time. Here's a Python function that implements this algorithm:
```python
def max_subarray_sum(arr):
if not arr:
return 0 # Handle empty array case
max_current = max_global = arr[0]
for i in r... | 19,480 | [
{
"from": "human",
"value": "Write a python function to find the maximum subarray sum using Kadane's algorithm."
},
{
"from": "gpt",
"value": "Sure! Kadane's algorithm is an efficient way to solve the maximum subarray sum problem in linear time. Here's a Python function that implements this algo... |
Write a python function to find the length of the longest substring of a given string that contains all unique characters. | Here is the code to solve this problem:
```python
def length_of_longest_unique_substring(s: str) -> int:
char_index = {}
left = 0
max_length = 0
for right, char in enumerate(s):
if char in char_index and char_index[char] >= left:
left = char_index[char] + 1
char_index[char] ... | [
"assert length_of_longest_unique_substring(\"abcabcbb\") == 3",
"assert length_of_longest_unique_substring(\"bbbbb\") == 1",
"assert length_of_longest_unique_substring(\"pwwkew\") == 3",
"assert length_of_longest_unique_substring(\"\") == 0"
] | You can find the length of the longest substring with all unique characters using a sliding window technique. Below is a Python function that implements this approach:
```python
def length_of_longest_unique_substring(s: str) -> int:
char_index_map = {}
left = 0
max_length = 0
for right in range(len(s)... | 19,481 | [
{
"from": "human",
"value": "Write a python function to find the length of the longest substring of a given string that contains all unique characters."
},
{
"from": "gpt",
"value": "You can find the length of the longest substring with all unique characters using a sliding window technique. Bel... |
Write a function to find the nth Fibonacci number using dynamic programming. | Here is the code to solve this problem:
```python
def fibonacci_number(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
fib = [0] * (n+1)
fib[1] = 1
for i in range(2, n+1):
fib[i] = fib[i-1] + fib[i-2]
return fib[n]
``` | [
"assert fibonacci_number(10) == 55",
"assert fibonacci_number(5) == 5",
"assert fibonacci_number(1) == 1"
] | Certainly! Here is a Python function that uses dynamic programming to find the nth Fibonacci number. The function stores the computed Fibonacci numbers to avoid redundant calculations, which makes it efficient.
```python
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
# Initial... | 19,482 | [
{
"from": "human",
"value": "Write a function to find the nth Fibonacci number using dynamic programming."
},
{
"from": "gpt",
"value": "Certainly! Here is a Python function that uses dynamic programming to find the nth Fibonacci number. The function stores the computed Fibonacci numbers to avoi... |
Write a function to check if a given graph is bipartite using Depth First Search (DFS). A graph is bipartite if it can be colored using two colors such that no two adjacent vertices have the same color. | Here is the code to solve this problem:
```python
from enum import Enum
class Color(Enum):
kWhite = 0
kRed = 1
kGreen = 2
def is_bipartite_dfs(graph):
colors = [Color.kWhite] * len(graph)
def dfs(u: int, color: Color) -> bool:
if colors[u] != Color.kWhite:
return colors[u] ==... | [
"assert is_bipartite_dfs([[1,2,3],[0,2],[0,1,3],[0,2]]) == False",
"assert is_bipartite_dfs([[1,3],[0,2],[1,3],[0,2]]) == True",
"assert is_bipartite_dfs([[1],[0]]) == True"
] | To determine if a graph is bipartite using Depth First Search (DFS), we can implement a function that colors the graph while traversing it. The algorithm will attempt to color the graph using two colors (often represented as 0 and 1). If we encounter a situation where two adjacent vertices have the same color, the grap... | 19,483 | [
{
"from": "human",
"value": "Write a function to check if a given graph is bipartite using Depth First Search (DFS). A graph is bipartite if it can be colored using two colors such that no two adjacent vertices have the same color."
},
{
"from": "gpt",
"value": "To determine if a graph is bipart... |
Write a function that finds the maximum sum of non-adjacent elements in a given list. This problem is also known as the Maximum Subset Sum problem, where the subset must not contain any two adjacent elements. | Here is the code to solve this problem:
```python
def max_subset_sum(nums):
if not nums:
return 0
if len(nums) <= 2:
return max(nums)
dp = [0] * len(nums)
dp[0], dp[1] = nums[0], max(nums[0], nums[1])
for i in range(2, len(nums)):
dp[i] = max(dp[i-1], nums[i] + dp[i-2])
... | [
"assert max_subset_sum([5, 1, 1, 5])==10",
"assert max_subset_sum([3, 2, 5, 10, 7])==15",
"assert max_subset_sum([3, 2, 7, 10])==13"
] | You can solve the Maximum Subset Sum problem using a dynamic programming approach. Here's how you can implement the function in Python:
```python
def max_subset_sum(arr):
if not arr:
return 0
elif len(arr) == 1:
return arr[0]
# Initialize an array to store the maximum sums
n = len(arr)... | 19,484 | [
{
"from": "human",
"value": "Write a function that finds the maximum sum of non-adjacent elements in a given list. This problem is also known as the Maximum Subset Sum problem, where the subset must not contain any two adjacent elements."
},
{
"from": "gpt",
"value": "You can solve the Maximum S... |
Write a python function that finds the length of the longest contiguous subarray which sums to a given value. | Here is the code to solve this problem:
```python
def longest_subarray_with_sum(nums, target):
sum_dict = {0: -1}
max_length = start = sum = 0
for i, num in enumerate(nums):
sum += num
if sum not in sum_dict:
sum_dict[sum] = i
if (sum - target) in sum_dict:
l... | [
"assert longest_subarray_with_sum([1, -1, 5, -2, 3], 3) == 4",
"assert longest_subarray_with_sum([-2, -1, 2, 1], 1) == 2",
"assert longest_subarray_with_sum([1, 2, 3, -3, 4], 4) == 3"
] | Certainly! You can solve the problem of finding the length of the longest contiguous subarray that sums to a given value using a dictionary to keep track of the cumulative sums and their indices. This approach allows you to efficiently check for the desired sum.
Here's a Python function that implements this logic:
``... | 19,485 | [
{
"from": "human",
"value": "Write a python function that finds the length of the longest contiguous subarray which sums to a given value."
},
{
"from": "gpt",
"value": "Certainly! You can solve the problem of finding the length of the longest contiguous subarray that sums to a given value using... |
Write a function to find the earliest time that a specific stock reaches a given target price. The function should take a list of tuples, where each tuple represents a day's stock price, and the target price as inputs. Each tuple contains the day number and the stock price on that day. If the stock never reaches the ta... | Here is the code to solve this problem:
```python
def earliest_reach_target(stock_prices, target_price):
for day, price in stock_prices:
if price >= target_price:
return day
return -1
``` | [
"assert earliest_reach_target([(1, 90), (2, 95), (3, 100), (4, 105)], 110) == -1",
"assert earliest_reach_target([(1, 100), (2, 105), (3, 110), (4, 115)], 110) == 3",
"assert earliest_reach_target([(1, 120), (2, 115), (3, 125), (4, 130)], 125) == 3"
] | Certainly! Here's a Python function that accomplishes this task. The function takes a list of tuples (where each tuple contains a day number and a stock price) and a target price. It returns the earliest day the stock reaches or exceeds the target price, or -1 if that never happens.
```python
def find_earliest_target_... | 19,486 | [
{
"from": "human",
"value": "Write a function to find the earliest time that a specific stock reaches a given target price. The function should take a list of tuples, where each tuple represents a day's stock price, and the target price as inputs. Each tuple contains the day number and the stock price on th... |
Write a function that finds the first non-repeating character in a given string and returns its index. If it doesn't exist, return -1. Assume that all characters are lowercase English letters. | Here is the code to solve this problem:
```python
def firstUniqChar(s: str) -> int:
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
for index, char in enumerate(s):
if char_count[char] == 1:
... | [
"assert firstUniqChar(\"leetcode\") == 0",
"assert firstUniqChar(\"aabb\") == -1",
"assert firstUniqChar(\"loveleetcode\") == 2"
] | You can find the first non-repeating character in a string by using a dictionary to count the occurrences of each character. Then, you can iterate through the string to identify the first character that has a count of one. Here is a Python function that implements this logic:
```python
def first_non_repeating_characte... | 19,487 | [
{
"from": "human",
"value": "Write a function that finds the first non-repeating character in a given string and returns its index. If it doesn't exist, return -1. Assume that all characters are lowercase English letters."
},
{
"from": "gpt",
"value": "You can find the first non-repeating charac... |
Write a function in Python to check if a list is sorted in ascending order. The list will contain integer elements. | Here is the code to solve this problem:
```python
def check_ascending(input_list):
for i in range(len(input_list) - 1):
if input_list[i] > input_list[i + 1]:
return False
return True
``` | [
"assert check_ascending([1, 2, 4, 3, 5]) == False",
"assert check_ascending([5, 4, 3, 2, 1]) == False",
"assert check_ascending([1, 2, 3, 4, 4]) == True",
"assert check_ascending([1, 2, 3, 4, 5]) == True"
] | Certainly! Below is a Python function that checks if a list of integers is sorted in ascending order:
```python
def is_sorted_ascending(lst):
"""Check if the list is sorted in ascending order.
Args:
lst (list): A list of integers.
Returns:
bool: True if the list is sorted in ascending ord... | 19,488 | [
{
"from": "human",
"value": "Write a function in Python to check if a list is sorted in ascending order. The list will contain integer elements."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that checks if a list of integers is sorted in ascending order:\n\n```python\ndef ... |
Write a function `concatenate_reversed` that takes a list of strings and returns a single string that is the result of concatenating the strings in reverse order. | Here is the code to solve this problem:
```python
def concatenate_reversed(strings):
reversed_strings = strings[::-1]
return ''.join(reversed_strings)
``` | [
"assert concatenate_reversed([\"abc\", \"def\", \"ghi\"]) == \"ghidefabc\"",
"assert concatenate_reversed([\"123\", \"456\", \"789\"]) == \"789456123\"",
"assert concatenate_reversed([\"hello\", \"world\", \"python\"]) == \"pythonworldhello\""
] | You can create a function called `concatenate_reversed` in Python, which will take a list of strings as input and return a single string that is the result of concatenating the strings in reverse order. Here is how you can implement it:
```python
def concatenate_reversed(strings):
# Reverse the list of strings and... | 19,489 | [
{
"from": "human",
"value": "Write a function `concatenate_reversed` that takes a list of strings and returns a single string that is the result of concatenating the strings in reverse order."
},
{
"from": "gpt",
"value": "You can create a function called `concatenate_reversed` in Python, which ... |
Write a function to check if a given number is a power of four. | Here is the code to solve this problem:
```python
def is_power_of_four(n):
pwr = 1
while pwr < n:
pwr *= 4
if pwr == n:
return True
else:
return False
``` | [
"assert is_power_of_four(16) == True",
"assert is_power_of_four(1) == True",
"assert is_power_of_four(64) == True",
"assert is_power_of_four(15) == False",
"assert is_power_of_four(0) == False"
] | You can check if a given number is a power of four by repeatedly dividing the number by 4 and checking if you reach 1. Here's a simple implementation of a function in Python that does this:
```python
def is_power_of_four(num):
# A number must be greater than 0 to be a power of four
if num <= 0:
return ... | 19,490 | [
{
"from": "human",
"value": "Write a function to check if a given number is a power of four."
},
{
"from": "gpt",
"value": "You can check if a given number is a power of four by repeatedly dividing the number by 4 and checking if you reach 1. Here's a simple implementation of a function in Pytho... |
Write a python function to find the number of ways to reach the last cell of a grid from the first cell using only right and down moves. | Here is the code to solve this problem:
```python
def count_Paths(m,n):
dp = [[0 for x in range(n)] for y in range(m)]
for i in range(m):
dp[i][0] = 1
for i in range(n):
dp[0][i] = 1
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i-1][j] + dp[i][j-1]... | [
"assert count_Paths(2,2) == 2",
"assert count_Paths(4,4) == 20",
"assert count_Paths(3,3) == 6"
] | Certainly! You can determine the number of ways to reach the last cell (bottom-right corner) of a grid starting from the first cell (top-left corner) using only right and down moves by utilizing combinatorics.
If we have a grid of size `m x n`, to reach the bottom-right corner from the top-left corner, we need to make... | 19,491 | [
{
"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 right and down moves."
},
{
"from": "gpt",
"value": "Certainly! You can determine the number of ways to reach the last cell (bottom-right corner) of a g... |
Write a function to find all the possible rotation of a given string. | Here is the code to solve this problem:
```python
def all_rotations(string):
rotations = [string]
for i in range(1, len(string)):
string = string[1:] + string[0]
rotations.append(string)
return rotations
``` | [
"assert all_rotations('a') == ['a']",
"assert all_rotations('abc') == ['abc', 'bca', 'cab']",
"assert all_rotations('hello') == ['hello', 'elloh', 'llohe', 'lohel', 'ohell']"
] | Certainly! To find all the possible rotations of a given string, you can use a simple function that generates each rotation by slicing the string in various ways. Here's a Python function that accomplishes this:
```python
def string_rotations(s):
# Get the length of the string
n = len(s)
# Create a list to... | 19,492 | [
{
"from": "human",
"value": "Write a function to find all the possible rotation of a given string."
},
{
"from": "gpt",
"value": "Certainly! To find all the possible rotations of a given string, you can use a simple function that generates each rotation by slicing the string in various ways. Her... |
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. | Here is the code to solve this problem:
```python
def exist(board, word):
def dfs(i, j, k):
if not (0 <= i < len(board)) or not (0 <= j < len(board[0])) or board[i][j] != word[k]:
return False
if k == len(word) - 1:
return True
board[i][j] = ''
res = dfs(i + ... | [
"assert exist([[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]],\"ABCCED\") == True",
"assert exist([[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]],\"SEE\") == True",
"assert exist([[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E... | To solve the problem of finding if a word exists in a 2D board by sequentially adjacent cells (horizontally or vertically), we can use a backtracking approach. This method will allow us to explore each cell and check for the presence of the word by marking cells as visited.
Here is a structured approach along with a s... | 19,493 | [
{
"from": "human",
"value": "Given a 2D board and a word, find if the word exists in the grid.\nThe word can be constructed from letters of sequentially adjacent cell, where \"adjacent\" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once."
},
{
... |
Write a python function to calculate the number of unique paths in a grid from the top-left corner to the bottom-right corner. You can only move either down or right at any point in time. | Here is the code to solve this problem:
```python
def grid_paths(m,n):
if m == 1 or n == 1:
return 1
return grid_paths(m-1, n) + grid_paths(m, n-1)
``` | [
"assert grid_paths(3,2) == 3",
"assert grid_paths(3,3) == 6",
"assert grid_paths(2,3) == 3"
] | You can solve the problem of counting unique paths in a grid using dynamic programming. The idea is to create a 2D list (array) to keep track of the number of ways to reach each cell in the grid.
Here's a Python function that implements this approach:
```python
def unique_paths(m, n):
# Create a 2D array to hold... | 19,494 | [
{
"from": "human",
"value": "Write a python function to calculate the number of unique paths in a grid from the top-left corner to the bottom-right corner. You can only move either down or right at any point in time."
},
{
"from": "gpt",
"value": "You can solve the problem of counting unique pat... |
Write a function that matches a string that has an 'a' followed by three 'b's. | Here is the code to solve this problem:
```python
import re
def text_match_three_b(text):
patterns = 'ab{3}'
if re.search(patterns, text):
return 'Found a match!'
else:
return 'Not matched!'
``` | [
"assert text_match_three_b(\"abbb\")==('Found a match!')",
"assert text_match_three_b(\"ababab\")==('Not matched!')",
"assert text_match_three_b(\"aabb\")==('Not matched!')"
] | You can accomplish this using regular expressions in Python. The pattern you're looking for can be represented as `'abbb'`, where `'a'` is followed directly by three `'b'` characters. Below is a simple Python function that checks if a given string matches this pattern:
```python
import re
def has_a_followed_by_three_... | 19,495 | [
{
"from": "human",
"value": "Write a function that matches a string that has an 'a' followed by three 'b's."
},
{
"from": "gpt",
"value": "You can accomplish this using regular expressions in Python. The pattern you're looking for can be represented as `'abbb'`, where `'a'` is followed directly ... |
Write a function to find the nth Lucas number. | Here is the code to solve this problem:
```python
def lucas_num(n):
if n == 0:
return 2
if n == 1:
return 1
lucas = [0] * (n + 1)
lucas[0] = 2
lucas[1] = 1
for i in range(2, n + 1):
lucas[i] = lucas[i - 1] + lucas[i - 2]
return lucas[n]
``` | [
"assert lucas_num(5) == 11",
"assert lucas_num(4) == 7",
"assert lucas_num(2) == 3"
] | The Lucas numbers are a sequence of numbers that are similar to the Fibonacci numbers, defined by the recurrence relation:
- \( L(n) = L(n-1) + L(n-2) \)
- with initial conditions \( L(0) = 2 \) and \( L(1) = 1 \).
Here's a Python function that computes the nth Lucas number using both an iterative approach and a recu... | 19,496 | [
{
"from": "human",
"value": "Write a function to find the nth Lucas number."
},
{
"from": "gpt",
"value": "The Lucas numbers are a sequence of numbers that are similar to the Fibonacci numbers, defined by the recurrence relation:\n\n- \\( L(n) = L(n-1) + L(n-2) \\)\n- with initial conditions \\(... |
Write a python function to find the smallest power of 2 which is greater than or equal to a given number. | Here is the code to solve this problem:
```python
def smallest_power_of_2(n):
power = 1
while power < n:
power *= 2
return power
``` | [
"assert smallest_power_of_2(17) == 32",
"assert smallest_power_of_2(5) == 8",
"assert smallest_power_of_2(16) == 16"
] | You can find the smallest power of 2 that is greater than or equal to a given number using the following Python function.
```python
def smallest_power_of_2(n):
if n <= 0:
raise ValueError("Input must be a positive integer.")
power = 1
while power < n:
power *= 2
return power
# Exa... | 19,497 | [
{
"from": "human",
"value": "Write a python function to find the smallest power of 2 which is greater than or equal to a given number."
},
{
"from": "gpt",
"value": "You can find the smallest power of 2 that is greater than or equal to a given number using the following Python function.\n\n```py... |
Write a function that takes two lists of integers as input and returns a list of all possible pairs (tuples) where the first element is from the first list and the second element is from the second list. | Here is the code to solve this problem:
```python
def cartesian_product(list1, list2):
result = [(i, j) for i in list1 for j in list2]
return result
``` | [
"assert cartesian_product([1, 2], [3, 4])==[(1, 3), (1, 4), (2, 3), (2, 4)]",
"assert cartesian_product([1, 2], [3, 4, 5])==[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]",
"assert cartesian_product([1], [3, 4, 5])==[(1, 3), (1, 4), (1, 5)]"
] | You can achieve this by using a nested loop or a list comprehension in Python. Here's a simple function that takes two lists of integers and returns a list of tuples containing all possible pairs:
```python
def generate_pairs(list1, list2):
pairs = [(a, b) for a in list1 for b in list2]
return pairs
# Example... | 19,498 | [
{
"from": "human",
"value": "Write a function that takes two lists of integers as input and returns a list of all possible pairs (tuples) where the first element is from the first list and the second element is from the second list."
},
{
"from": "gpt",
"value": "You can achieve this by using a ... |
Write a python function to find the number of times a given word appears as a prefix of the words in a list. | Here is the code to solve this problem:
```python
def count_prefix(word_list, prefix):
count = 0
for word in word_list:
if word.startswith(prefix):
count += 1
return count
``` | [
"assert count_prefix([\"hello\", \"world\", \"hi\", \"bye\"], \"h\") == 2",
"assert count_prefix([\"apple\", \"application\", \"appetite\", \"banana\"], \"app\") == 3",
"assert count_prefix([\"python\", \"java\", \"c++\", \"javascript\"], \"java\") == 2"
] | You can create a Python function to count how many times a given word appears as a prefix in a list of words by iterating through the list and checking if each word starts with the specified prefix. Below is a sample function that implements this:
```python
def count_prefix_occurrences(word_list, prefix):
"""
... | 19,499 | [
{
"from": "human",
"value": "Write a python function to find the number of times a given word appears as a prefix of the words in a list."
},
{
"from": "gpt",
"value": "You can create a Python function to count how many times a given word appears as a prefix in a list of words by iterating throu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.