instruction_seed stringlengths 42 1.67k | response_seed stringlengths 83 5.94k | testcase listlengths 3 39 | response stringlengths 46 5.35k | __original_row_idx int64 0 50k | conversations listlengths 2 2 |
|---|---|---|---|---|---|
Write a function to find the number of common elements between two lists without using the set() or intersection() function. | Here is the code to solve this problem:
```python
def find_common_elements(list1, list2):
common_elements = []
for i in list1:
if i in list2 and i not in common_elements:
common_elements.append(i)
return common_elements
``` | [
"assert find_common_elements([1,2,3,4,5],[4,5,6,7,8])==[4,5]",
"assert find_common_elements([10,20,30,40,50],[30,40,50,60,70])==[30,40,50]",
"assert find_common_elements([1,2,3],[4,5,6])==[]"
] | Certainly! You can write a function that iterates through the elements of both lists and counts the common elements. Here’s a simple function to do that:
```python
def count_common_elements(list1, list2):
# Initialize a count for common elements
common_count = 0
# Use a nested loop to check for common... | 2,400 | [
{
"from": "human",
"value": "Write a function to find the number of common elements between two lists without using the set() or intersection() function."
},
{
"from": "gpt",
"value": "Certainly! You can write a function that iterates through the elements of both lists and counts the common elem... |
Write a function to find the greatest common divisor (GCD) of two positive integers using the Euclidean algorithm. | Here is the code to solve this problem:
```python
def gcd(a, b):
while b:
a, b = b, a % b
return a
``` | [
"assert gcd(54, 24) == 6",
"assert gcd(1071, 462) == 21",
"assert gcd(17, 31) == 1"
] | Certainly! The Euclidean algorithm is an efficient method for computing the greatest common divisor (GCD) of two integers. Here is a Python function that implements this algorithm:
```python
def gcd(a, b):
"""Return the greatest common divisor of a and b using the Euclidean algorithm."""
while b != 0:
... | 2,401 | [
{
"from": "human",
"value": "Write a function to find the greatest common divisor (GCD) of two positive integers using the Euclidean algorithm."
},
{
"from": "gpt",
"value": "Certainly! The Euclidean algorithm is an efficient method for computing the greatest common divisor (GCD) of two integers... |
Write a function to find the number of islands in a given grid. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. | Here is the code to solve this problem:
```python
def count_islands(grid):
if not grid:
return 0
m, n = len(grid), len(grid[0])
count = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
count += 1
grid[i][j] = 0
stack... | [
"assert count_islands([[1,1,0,0,0],[1,1,0,0,0],[0,0,1,0,0],[0,0,0,1,1]]) == 3",
"assert count_islands([[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]]) == 1",
"assert count_islands([[1,1,0,0,0],[1,1,0,0,0],[0,0,1,1,0],[0,0,0,1,1]]) == 2"
] | To find the number of islands in a given grid, you can use a Depth-First Search (DFS) or Breadth-First Search (BFS) traversal technique. Here, I will provide a DFS approach. The idea is to iterate through each cell in the grid, and when you find a '1' (representing land), you trigger a DFS to mark the entire island as ... | 2,402 | [
{
"from": "human",
"value": "Write a function to find the number of islands in a given grid. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water."
},
{
"from": "gpt",
"value"... |
Write a function to find the indices of the starting points of all anagrams of a given pattern in a string. | Here is the code to solve this problem:
```python
import collections
from typing import List
def find_anagrams_indices(s: str, p: str) -> List[int]:
ans = []
target = collections.Counter()
for ch in p:
target[ch] += 1
curr = collections.Counter()
len_p = len(p)
len_s = len(s)
if l... | [
"assert find_anagrams_indices(\"abab\", \"ab\") == [0, 1, 2]",
"assert find_anagrams_indices(\"cbaebabacd\", \"abc\") == [0, 6]",
"assert find_anagrams_indices(\"hello\", \"ll\") == [2]"
] | Certainly! To find the starting indices of all anagrams of a given pattern in a string, we can use a sliding window approach along with character frequency counting. Here's a Python function that implements this logic:
```python
def find_anagrams(s, pattern):
from collections import Counter
# Lengths of the s... | 2,403 | [
{
"from": "human",
"value": "Write a function to find the indices of the starting points of all anagrams of a given pattern in a string."
},
{
"from": "gpt",
"value": "Certainly! To find the starting indices of all anagrams of a given pattern in a string, we can use a sliding window approach alo... |
Write a python function to count the number of digits in a given number. | Here is the code to solve this problem:
```python
def count_digits(n):
count = 0
while(n > 0):
count+=1
n = n//10
return count
``` | [
"assert count_digits(12345) == 5",
"assert count_digits(98765) == 5",
"assert count_digits(90) == 2"
] | Certainly! Below is a Python function that counts the number of digits in a given number (both positive and negative):
```python
def count_digits(number):
# Convert number to string and remove the sign if it's negative
if number < 0:
number = -number
return len(str(number))
# Example usage:
n... | 2,404 | [
{
"from": "human",
"value": "Write a python function to count the number of digits in a given number."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that counts the number of digits in a given number (both positive and negative):\n\n```python\ndef count_digits(number):\n ... |
Write a function that verifies if a string is a valid parentheses sequence. A valid parentheses sequence is defined as any sequence of parentheses where each opening parenthesis '(' has a corresponding closing parenthesis ')' and the pairs are properly nested. | Here is the code to solve this problem:
```python
def is_valid_parentheses(s: str) -> bool:
stack = []
for char in s:
if char == '(':
stack.append(char)
elif char == ')':
if not stack or stack[-1] != '(':
return False
stack.pop()
return no... | [
"assert is_valid_parentheses(\"()\") == True",
"assert is_valid_parentheses(\")(\") == False",
"assert is_valid_parentheses(\"(()())\") == True",
"assert is_valid_parentheses(\"(()\") == False",
"assert is_valid_parentheses(\"())(\") == False"
] | You can verify whether a string is a valid parentheses sequence by using a stack-based approach. The idea is to go through each character in the string, push opening parentheses onto the stack, and pop the stack when you encounter a closing parenthesis. If at any point you try to pop from an empty stack or if there are... | 2,405 | [
{
"from": "human",
"value": "Write a function that verifies if a string is a valid parentheses sequence. A valid parentheses sequence is defined as any sequence of parentheses where each opening parenthesis '(' has a corresponding closing parenthesis ')' and the pairs are properly nested."
},
{
"fro... |
Write a function that takes a list of integers as input and returns a list of integers representing the cumulative product of all elements up to the current index. | Here is the code to solve this problem:
```python
def cumulative_product(nums):
result = []
product = 1
for num in nums:
product *= num
result.append(product)
return result
``` | [
"assert cumulative_product([1, 2, 3, 4]) == [1, 2, 6, 24]",
"assert cumulative_product([3, 7, 11, 15]) == [3, 21, 231, 3465]",
"assert cumulative_product([2, 5, 10, 20]) == [2, 10, 100, 2000]"
] | You can create a function that computes the cumulative product of a list of integers by iterating through the list and maintaining a running product. Here's a simple implementation of this in Python:
```python
def cumulative_product(lst):
"""Returns a list of cumulative products of the input list."""
if not ls... | 2,406 | [
{
"from": "human",
"value": "Write a function that takes a list of integers as input and returns a list of integers representing the cumulative product of all elements up to the current index."
},
{
"from": "gpt",
"value": "You can create a function that computes the cumulative product of a list... |
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],3) == 123",
"assert find_Min_Num([4,5,6,1],4) == 1456",
"assert find_Min_Num([1,2,3,9],4) == 1239"
] | To find the smallest number that can be formed with a given list of digits, we can follow these steps:
1. Convert the list of digits into strings (if they aren't already).
2. Sort the list of strings.
3. Join the sorted list into a single string, which represents the smallest number.
Here's how you can implement this... | 2,407 | [
{
"from": "human",
"value": "Write a python function to find the smallest number that can be formed with the given digits."
},
{
"from": "gpt",
"value": "To find the smallest number that can be formed with a given list of digits, we can follow these steps:\n\n1. Convert the list of digits into s... |
Write a python function to check if a given number is a perfect number or not. A perfect number is a positive integer that is equal to the sum of its proper divisors. | Here is the code to solve this problem:
```python
def isPerfect(n):
sum = 0
for x in range(1, n):
if n % x == 0:
sum += x
return sum == n
``` | [
"assert isPerfect(496) == True",
"assert isPerfect(12) == False",
"assert isPerfect(6) == True",
"assert isPerfect(28) == True"
] | Sure! A perfect number is defined as a positive integer that is equal to the sum of its proper divisors (excluding the number itself). For example, the number 6 is a perfect number because the proper divisors of 6 are 1, 2, and 3, which sum up to 6.
Here's a Python function that checks if a given number is a perfect n... | 2,408 | [
{
"from": "human",
"value": "Write a python function to check if a given number is a perfect number or not. A perfect number is a positive integer that is equal to the sum of its proper divisors."
},
{
"from": "gpt",
"value": "Sure! A perfect number is defined as a positive integer that is equal... |
Write a python function to find the length of the longest consecutive sequence in an unsorted list of integers. | Here is the code to solve this problem:
```python
def longest_consecutive_sequence(nums):
if not nums:
return 0
nums = set(nums)
longest_streak = 0
for num in nums:
if num - 1 not in nums:
current_num = num
current_streak = 1
wh... | [
"assert longest_consecutive_sequence([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]) == 9",
"assert longest_consecutive_sequence([100, 4, 200, 1, 3, 2]) == 4",
"assert longest_consecutive_sequence([1, 9, 3, 10, 4, 20, 2]) == 4"
] | You can find the length of the longest consecutive sequence in an unsorted list of integers using a Python function. One efficient approach to do this is to use a set for O(1) average time complexity lookups. Here’s the function that implements this algorithm:
```python
def longest_consecutive_sequence(nums):
if n... | 2,409 | [
{
"from": "human",
"value": "Write a python function to find the length of the longest consecutive sequence in an unsorted list of integers."
},
{
"from": "gpt",
"value": "You can find the length of the longest consecutive sequence in an unsorted list of integers using a Python function. One eff... |
Write a python function to convert a decimal number to a binary number. | Here is the code to solve this problem:
```python
def dec_to_bin(n):
binary = ''
while n > 0:
binary = str(n % 2) + binary
n = n // 2
return binary
``` | [
"assert dec_to_bin(255) == '11111111'",
"assert dec_to_bin(10) == '1010'",
"assert dec_to_bin(5) == '101'"
] | You can convert a decimal number to a binary number in Python using various methods. Below is a simple function that performs this conversion using recursion.
Here's a Python function:
```python
def decimal_to_binary(n):
"""Convert a decimal number to a binary number represented as a string."""
if n == 0:
... | 2,410 | [
{
"from": "human",
"value": "Write a python function to convert a decimal number to a binary number."
},
{
"from": "gpt",
"value": "You can convert a decimal number to a binary number in Python using various methods. Below is a simple function that performs this conversion using recursion. \n\nH... |
Write a function to find the maximum product of three numbers in a given list. | Here is the code to solve this problem:
```python
def max_product_three(nums):
nums.sort()
# The maximum product can be either (the product of the three largest numbers) or (the product of the two smallest numbers and the largest number)
return max(nums[-1] * nums[-2] * nums[-3], nums[0] * nums[1] * nums[-... | [
"assert max_product_three([-10, -10, 5, 2]) == 500",
"assert max_product_three([1, 2, 3, 4]) == 24",
"assert max_product_three([1, 2, 3]) == 6"
] | Certainly! You can find the maximum product of three numbers in a list by considering both the highest positive numbers and the lowest negative numbers (since multiplying two negative numbers can yield a positive product). Below is a Python function that implements this logic:
```python
def maximum_product_of_three(nu... | 2,411 | [
{
"from": "human",
"value": "Write a function to find the maximum product of three numbers in a given list."
},
{
"from": "gpt",
"value": "Certainly! You can find the maximum product of three numbers in a list by considering both the highest positive numbers and the lowest negative numbers (sinc... |
Write a python function to find the number of islands in a given grid. An island is formed by connected 1s (representing land) not surrounded by water (0s). You may assume all four edges of the grid are surrounded by water. | Here is the code to solve this problem:
```python
def island_counter(grid):
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
count = 0
def dfs(i, j):
if i < 0 or i >= rows or j < 0 or j >= cols or grid[i][j] == 0:
return
grid[i][j] = 0
dfs(i+1, j)... | [
"assert island_counter([[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[0,0,0,0,0]]) == 1",
"assert island_counter([[1,1,1],[0,1,0],[1,1,1]]) == 1",
"assert island_counter([[1,1,0,0,0],[1,1,0,0,0],[0,0,1,0,0],[0,0,0,1,1]]) == 3"
] | To find the number of islands in a given grid, we can use Depth-First Search (DFS) or Breadth-First Search (BFS) to explore the land (1s) and count how many distinct islands there are. An island is defined as a group of connected 1s which can be connected either horizontally or vertically.
Here's a Python function tha... | 2,412 | [
{
"from": "human",
"value": "Write a python function to find the number of islands in a given grid. An island is formed by connected 1s (representing land) not surrounded by water (0s). You may assume all four edges of the grid are surrounded by water."
},
{
"from": "gpt",
"value": "To find the ... |
Write a python function to find the longest subsequence of consecutive characters in a given string. If there are multiple subsequences with the same length, return the one that appears first. | Here is the code to solve this problem:
```python
def longest_consecutive_subsequence(s):
if not s:
return ""
max_len = 1
current_len = 1
start = 0
for i in range(1, len(s)):
if s[i] == s[i - 1]:
current_len += 1
else:
if current_len > max_len:
... | [
"assert longest_consecutive_subsequence(\"abcde\") == \"a\"",
"assert longest_consecutive_subsequence(\"aabbbcc\") == \"bbb\"",
"assert longest_consecutive_subsequence(\"zzz\") == \"zzz\""
] | You can achieve this by iterating through the string and keeping track of the longest subsequence of consecutive characters. Here's a Python function that implements this logic:
```python
def longest_consecutive_subsequence(s):
if not s: # Handle empty string
return ""
longest = ""
current = ""
... | 2,413 | [
{
"from": "human",
"value": "Write a python function to find the longest subsequence of consecutive characters in a given string. If there are multiple subsequences with the same length, return the one that appears first."
},
{
"from": "gpt",
"value": "You can achieve this by iterating through t... |
Write a python function to find the smallest positive integer value that cannot be represented as the sum of any subset of a given list of positive integers. | Here is the code to solve this problem:
```python
def smallest_missing(arr):
arr.sort()
smallest_missing = 1
for num in arr:
if num > smallest_missing:
break
smallest_missing += num
return smallest_missing
``` | [
"assert smallest_missing([1, 3, 6, 10]) == 2",
"assert smallest_missing([1, 2, 3]) == 7",
"assert smallest_missing([1, 1, 3, 4]) == 10"
] | To solve this problem, we can use a greedy approach. The idea is to sort the list of positive integers and then iterate through the sorted list, maintaining a running total of the smallest integer that cannot be formed as a sum.
Here is a Python function that implements this logic:
```python
def smallest_nonconstruct... | 2,414 | [
{
"from": "human",
"value": "Write a python function to find the smallest positive integer value that cannot be represented as the sum of any subset of a given list of positive integers."
},
{
"from": "gpt",
"value": "To solve this problem, we can use a greedy approach. The idea is to sort the l... |
Write a function that checks if a given string is a valid URL. The function should return True if the URL is valid and False otherwise. A valid URL should start with "http://" or "https://", followed by a domain name (alphanumeric characters and hyphens), and end with a top-level domain (e.g., .com, .org, .edu). Option... | Here is the code to solve this problem:
```python
import re
def is_valid_url(url):
pattern = re.compile(
r'^(https?://)' # scheme is http or https
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+' # domain...
r'(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain name
r'localhost|' # ... | [
"assert is_valid_url(\"http://www.example.com\") == True",
"assert is_valid_url(\"https://www.example.com:8080/path?query=string#fragment\") == True",
"assert is_valid_url(\"http://www.example.com:8080/path?query=string\") == True",
"assert is_valid_url(\"https://www.example.com:8080/path\") == True",
"asse... | To check if a given string is a valid URL based on the specified criteria, we can use a regular expression. Below is a Python function that verifies if a URL is valid according to your description. This function will check for the correct scheme, domain name, optional port number, and other components like paths, query... | 2,415 | [
{
"from": "human",
"value": "Write a function that checks if a given string is a valid URL. The function should return True if the URL is valid and False otherwise. A valid URL should start with \"http://\" or \"https://\", followed by a domain name (alphanumeric characters and hyphens), and end with a top-... |
Write a python function that takes a list of strings and groups them by anagrams. Anagrams are words formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
For example, the strings "listen" and "silent" are anagrams of each other. | Here is the code to solve this problem:
```python
from collections import defaultdict
def group_anagrams(strs):
anagrams = defaultdict(list)
for word in strs:
# Sorted word is a key for anagrams
key = ''.join(sorted(word))
anagrams[key].append(word)
return list(anagrams.v... | [
"assert group_anagrams([\"cat\", \"tac\", \"act\", \"god\", \"dog\", \"ct\"]) == [[\"cat\", \"tac\", \"act\"], [\"god\", \"dog\"], [\"ct\"]]",
"assert group_anagrams([\"abc\", \"cba\", \"bac\", \"xyz\", \"zyx\", \"xzy\"]) == [[\"abc\", \"cba\", \"bac\"], [\"xyz\", \"zyx\", \"xzy\"]]",
"assert group_anagrams([\"... | You can group anagrams by sorting the letters of each word and using the sorted word as a key in a dictionary. Here's a Python function that accomplishes this:
```python
def group_anagrams(strings):
anagrams_map = {}
for word in strings:
# Sort the word to get the key
sorted_word = ''.join... | 2,416 | [
{
"from": "human",
"value": "Write a python function that takes a list of strings and groups them by anagrams. Anagrams are words formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.\n\nFor example, the strings \"listen\" and \"silent\" are ... |
Write a python function to find the number of ways to express n as a sum of 1, 3, and 4. | Here is the code to solve this problem:
```python
def waysToSum(n):
if n == 0:
return 1
if n < 0:
return 0
return waysToSum(n-1) + waysToSum(n-3) + waysToSum(n-4)
# Optimized solution using dynamic programming
def waysToSum_dp(n):
dp = [0] * (n+1)
dp[0] = 1
for i in range(1, n+... | [
"assert waysToSum(2) == 1",
"assert waysToSum(1) == 1",
"assert waysToSum(3) == 2"
] | To find the number of ways to express a number \( n \) as a sum of 1's, 3's, and 4's, we can use a dynamic programming approach. The idea is to build up the solution for numbers from 0 up to \( n \) based on previously computed results.
Here's a Python function that implements this logic:
```python
def count_ways(n):... | 2,417 | [
{
"from": "human",
"value": "Write a python function to find the number of ways to express n as a sum of 1, 3, and 4."
},
{
"from": "gpt",
"value": "To find the number of ways to express a number \\( n \\) as a sum of 1's, 3's, and 4's, we can use a dynamic programming approach. The idea is to b... |
Write a function to find the second smallest unique number in a given list of integers. If there is no second smallest number, return None. | Here is the code to solve this problem:
```python
def second_smallest(numbers):
unique_numbers = list(set(numbers))
if len(unique_numbers) < 2:
return None
unique_numbers.sort()
return unique_numbers[1]
``` | [
"assert second_smallest([1, 2, 3, 4, 5]) == 2",
"assert second_smallest([5, 1, 4, 3, 2]) == 2",
"assert second_smallest([1, 1]) == None",
"assert second_smallest([]) == None"
] | Here is a Python function that finds the second smallest unique number in a given list of integers. If there is no second smallest unique number, it returns `None`.
```python
def second_smallest_unique(numbers):
# Create a set to hold unique numbers
unique_numbers = set(numbers)
# If there are fewer than ... | 2,418 | [
{
"from": "human",
"value": "Write a function to find the second smallest unique number in a given list of integers. If there is no second smallest number, return None."
},
{
"from": "gpt",
"value": "Here is a Python function that finds the second smallest unique number in a given list of intege... |
Write a function to find the number of occurrences of a substring in a given string, including overlapping occurrences. | Here is the code to solve this problem:
```python
def count_substring_occurrences(string, substring):
count = start = 0
while True:
start = string.find(substring, start) + 1
if start > 0:
count += 1
else:
return count
``` | [
"assert count_substring_occurrences(\"banana\", \"na\") == 2",
"assert count_substring_occurrences(\"hello\", \"l\") == 2",
"assert count_substring_occurrences(\"programming\", \"mm\") == 1",
"assert count_substring_occurrences(\"aaaaa\", \"aa\") == 4"
] | Certainly! Below is a Python function that can find the number of occurrences of a substring in a given string, including overlapping occurrences. The function uses a combination of a loop and the `str.find()` method to count the occurrences:
```python
def count_overlapping_occurrences(string, substring):
count = ... | 2,419 | [
{
"from": "human",
"value": "Write a function to find the number of occurrences of a substring in a given string, including overlapping occurrences."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that can find the number of occurrences of a substring in a given string, incl... |
Write a python function to find the next greater element for every element in the given array. If no such element exists, return -1 for that index. | Here is the code to solve this problem:
```python
def next_greater_element(array):
result = [-1] * len(array)
stack = []
for i, num in enumerate(array):
while stack and array[stack[-1]] < num:
result[stack.pop()] = num
stack.append(i)
return result
``` | [
"assert next_greater_element([1, 2, 3]) == [2, 3, -1]",
"assert next_greater_element([3, 2, 1]) == [-1, -1, -1]",
"assert next_greater_element([2, 7, 3, 5, 4, 6, 8]) == [7, 8, 5, 6, 6, 8, -1]"
] | You can solve the problem of finding the next greater element for every element in an array using a stack. This approach efficiently finds the next greater element in O(n) time complexity, where n is the number of elements in the array.
Here’s a Python function that implements this approach:
```python
def next_greate... | 2,420 | [
{
"from": "human",
"value": "Write a python function to find the next greater element for every element in the given array. If no such element exists, return -1 for that index."
},
{
"from": "gpt",
"value": "You can solve the problem of finding the next greater element for every element in an ar... |
Write a function that takes a list of numbers as input and returns a new list where each number is replaced by its square if it is positive, or by its absolute value if it is negative. | Here is the code to solve this problem:
```python
def square_or_abs(nums):
return [num**2 if num > 0 else abs(num) for num in nums]
``` | [
"assert square_or_abs([1, 2, 3, 4, 5])==[1, 4, 9, 16, 25]",
"assert square_or_abs([-5, -4, -3, -2, -1])==[5, 4, 3, 2, 1]",
"assert square_or_abs([-3, 4, -2, 5, -1])==[3, 16, 2, 25, 1]"
] | Certainly! Below is a Python function that implements the required functionality:
```python
def transform_numbers(numbers):
result = []
for num in numbers:
if num > 0:
result.append(num ** 2) # Square the number if it is positive
else:
result.append(abs(num)) # Use a... | 2,421 | [
{
"from": "human",
"value": "Write a function that takes a list of numbers as input and returns a new list where each number is replaced by its square if it is positive, or by its absolute value if it is negative."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that implemen... |
Write a function to convert an integer to its Roman numeral equivalent. | Here is the code to solve this problem:
```python
def int_to_roman(num):
val = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4,
1
]
syms = [
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
"X", "IX", "V", "IV",
"I"
]
roman_num = ''
... | [
"assert int_to_roman(58) == \"LVIII\"",
"assert int_to_roman(3) == \"III\"",
"assert int_to_roman(1994) == \"MCMXCIV\""
] | Certainly! Here's a Python function that converts an integer to its Roman numeral equivalent:
```python
def int_to_roman(num):
# Mapping of values to Roman numerals
val = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4,
1
]
syms = [
"M", "CM", "D", "CD",
... | 2,422 | [
{
"from": "human",
"value": "Write a function to convert an integer to its Roman numeral equivalent."
},
{
"from": "gpt",
"value": "Certainly! Here's a Python function that converts an integer to its Roman numeral equivalent:\n\n```python\ndef int_to_roman(num):\n # Mapping of values to Roman... |
Write a function to find the first non-repeating character in a given string. | Here is the code to solve this problem:
```python
def find_first_non_repeating_char(s):
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
for char in s:
if char_count[char] == 1:
return char
... | [
"assert find_first_non_repeating_char(\"leetcode\") == 'l'",
"assert find_first_non_repeating_char(\"loveleetcode\") == 'v'",
"assert find_first_non_repeating_char(\"aabb\") == ''"
] | Here's a Python function that finds the first non-repeating character in a given string:
```python
def first_non_repeating_character(s):
# Create a dictionary to count occurrences of each character
char_count = {}
# Count the occurrences of each character in the string
for char in s:
char_... | 2,423 | [
{
"from": "human",
"value": "Write a function to find the first non-repeating character in a given string."
},
{
"from": "gpt",
"value": "Here's a Python function that finds the first non-repeating character in a given string:\n\n```python\ndef first_non_repeating_character(s):\n # Create a d... |
Write a python function to check whether a given string is a palindrome or not, ignoring case and non-alphanumeric characters. | Here is the code to solve this problem:
```python
def is_Palindrome(s):
s = ''.join([i.lower() for i in s if i.isalnum()])
return s == s[::-1]
``` | [
"assert is_Palindrome(\"A man, a plan, a canal: Panama\") == True",
"assert is_Palindrome(\"race a car\") == False",
"assert is_Palindrome(\" \") == True"
] | You can create a function in Python to check if a given string is a palindrome while ignoring case and non-alphanumeric characters. Here's a sample implementation:
```python
import re
def is_palindrome(s: str) -> bool:
# Use regex to remove non-alphanumeric characters and convert to lower case
cleaned_string ... | 2,424 | [
{
"from": "human",
"value": "Write a python function to check whether a given string is a palindrome or not, ignoring case and non-alphanumeric characters."
},
{
"from": "gpt",
"value": "You can create a function in Python to check if a given string is a palindrome while ignoring case and non-al... |
Write a python function to rotate the elements of a list by a certain number of positions to the right. | Here is the code to solve this problem:
```python
def rotate_list(lst, k):
if not lst or k == 0:
return lst
k = k % len(lst)
return lst[-k:] + lst[:-k]
``` | [
"assert rotate_list([1, 2, 3, 4, 5], 0) == [1, 2, 3, 4, 5]",
"assert rotate_list([1, 2, 3, 4, 5], 2) == [4, 5, 1, 2, 3]",
"assert rotate_list([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5]"
] | You can create a function to rotate the elements of a list to the right by a specified number of positions. Here's a simple implementation in Python:
```python
def rotate_list(lst, positions):
"""Rotate the elements of a list to the right by the specified number of positions."""
if not lst: # Check if the lis... | 2,425 | [
{
"from": "human",
"value": "Write a python function to rotate the elements of a list by a certain number of positions to the right."
},
{
"from": "gpt",
"value": "You can create a function to rotate the elements of a list to the right by a specified number of positions. Here's a simple implemen... |
Write a python function to find the symmetric difference between two sets. | Here is the code to solve this problem:
```python
def symmetric_difference(set1, set2):
return set1.symmetric_difference(set2)
``` | [
"assert symmetric_difference({5, 6, 7}, {7, 8, 9}) == {5, 6, 8, 9}",
"assert symmetric_difference({10, 11}, {10, 11, 12}) == {12}",
"assert symmetric_difference({1, 2, 3}, {2, 3, 4}) == {1, 4}"
] | Certainly! The symmetric difference between two sets is the set of elements that are in either of the sets, but not in their intersection. In Python, you can easily compute the symmetric difference using the built-in set operations.
Here’s a simple function to find the symmetric difference between two sets:
```python... | 2,426 | [
{
"from": "human",
"value": "Write a python function to find the symmetric difference between two sets."
},
{
"from": "gpt",
"value": "Certainly! The symmetric difference between two sets is the set of elements that are in either of the sets, but not in their intersection. In Python, you can eas... |
Write a python function to find the kth smallest element in a given list using QuickSelect algorithm. | Here is the code to solve this problem:
```python
def partition(arr, low, high):
i = (low-1)
pivot = arr[high]
for j in range(low, high):
if arr[j] <= pivot:
i = i+1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return (i+1)
def quickSe... | [
"assert kth_smallest_element([7, 10, 4, 3, 20, 15], 3) == 7",
"assert kth_smallest_element([12, 3, 5, 7, 19], 2) == 5",
"assert kth_smallest_element([7, 10, 4, 3, 20, 15], 4) == 10"
] | Certainly! The QuickSelect algorithm is an efficient way to find the kth smallest element in an unordered list. It is based on the partitioning method of QuickSort. Here's a Python function that implements the QuickSelect algorithm to find the kth smallest element:
```python
import random
def partition(arr, low, high... | 2,427 | [
{
"from": "human",
"value": "Write a python function to find the kth smallest element in a given list using QuickSelect algorithm."
},
{
"from": "gpt",
"value": "Certainly! The QuickSelect algorithm is an efficient way to find the kth smallest element in an unordered list. It is based on the par... |
Write a python function that takes a list of integers as input and returns the maximum product of two adjacent elements in the list. | Here is the code to solve this problem:
```python
def max_product_adjacent(lst):
max_product = lst[0] * lst[1]
for i in range(1, len(lst) - 1):
product = lst[i] * lst[i + 1]
if product > max_product:
max_product = product
return max_product
``` | [
"assert max_product_adjacent([0, -1, 1, 24, 1, -4, 8, 10]) == 80",
"assert max_product_adjacent([5, 6, -4, 2, 3, 2, -23]) == 30",
"assert max_product_adjacent([3, 6, -2, -5, 7, 3]) == 21"
] | Certainly! Here is a Python function that takes a list of integers as input and returns the maximum product of two adjacent elements in that list:
```python
def max_product_of_adjacent(nums):
if len(nums) < 2:
raise ValueError("The list must contain at least two integers.")
max_product = float... | 2,428 | [
{
"from": "human",
"value": "Write a python function that takes a list of integers as input and returns the maximum product of two adjacent elements in the list."
},
{
"from": "gpt",
"value": "Certainly! Here is a Python function that takes a list of integers as input and returns the maximum pro... |
Write a function to find the number of unique triplets in the given list that sum up to zero. | Here is the code to solve this problem:
```python
def find_zero_sum_triplets(nums):
nums.sort()
triplets = set()
for i in range(len(nums)-2):
if i > 0 and nums[i] == nums[i-1]:
continue
left, right = i+1, len(nums)-1
while left < right:
s = nums[i] + nums[lef... | [
"assert find_zero_sum_triplets([1, -1, -1, 0]) == 1",
"assert find_zero_sum_triplets([-1, 0, 1, 2, -1, -4]) == 2",
"assert find_zero_sum_triplets([0, 0, 0, 0]) == 1"
] | To find the number of unique triplets in a list that sum up to zero, you can use a combination of sorting the list and a two-pointer technique. Here's how you can implement this in Python:
```python
def three_sum(nums):
nums.sort() # First, sort the input list
unique_triplets = set() # Use a set to store uni... | 2,429 | [
{
"from": "human",
"value": "Write a function to find the number of unique triplets in the given list that sum up to zero."
},
{
"from": "gpt",
"value": "To find the number of unique triplets in a list that sum up to zero, you can use a combination of sorting the list and a two-pointer technique... |
Write a python function to find the number of unique paths in a grid from the top-left corner to the bottom-right corner, given that you can only move either down or right at any point in time. | Here is the code to solve this problem:
```python
def uniquePaths(m: int, n: int) -> int:
dp = [[1 for _ in range(n)] for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[-1][-1]
``` | [
"assert uniquePaths(3, 7) == 28",
"assert uniquePaths(3, 2) == 3",
"assert uniquePaths(7, 3) == 28"
] | Certainly! You can solve this problem using dynamic programming. The idea is to create a 2D list (or array) where each element at position `(i, j)` represents the number of unique paths to reach that cell from the top-left corner `(0, 0)`.
Here's a step-by-step breakdown:
1. Create a 2D list `dp` of size `m x n`, whe... | 2,430 | [
{
"from": "human",
"value": "Write a python function to find the number of unique paths in a grid from the top-left corner to the bottom-right corner, given that you can only move either down or right at any point in time."
},
{
"from": "gpt",
"value": "Certainly! You can solve this problem usin... |
Write a function that takes a string and returns the number of substrings that are palindromes. | Here is the code to solve this problem:
```python
def count_palindromes(s):
n = len(s)
count = 0
for i in range(n):
# odd length palindromes
l, r = i, i
while l >= 0 and r < n and s[l] == s[r]:
count += 1
l -= 1
r += 1
# even length palind... | [
"assert count_palindromes(\"abba\") == 6",
"assert count_palindromes(\"aaa\") == 6",
"assert count_palindromes(\"abc\") == 3"
] | To solve the problem of counting palindromic substrings in a given string, we can implement a straightforward algorithm using a center expansion approach. This method involves expanding around each character (and between each pair of characters) to check for palindromes.
Here’s a Python function that accomplishes this... | 2,431 | [
{
"from": "human",
"value": "Write a function that takes a string and returns the number of substrings that are palindromes."
},
{
"from": "gpt",
"value": "To solve the problem of counting palindromic substrings in a given string, we can implement a straightforward algorithm using a center expan... |
Write a function to find the minimum number of operations to make the given string palindrome by deleting characters. A palindrome is a string that reads the same backward as forward, e.g., 'radar' or 'level'. | Here is the code to solve this problem:
```python
def min_operations_to_palindrome(s):
n = len(s)
dp = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n - 1, -1, -1):
dp[i][i] = 0
for j in range(i + 1, n):
if s[i] == s[j]:
dp[i][j] = dp[i + 1][j - 1]
... | [
"assert min_operations_to_palindrome(\"abcde\") == 4",
"assert min_operations_to_palindrome(\"aba\") == 0",
"assert min_operations_to_palindrome(\"abc\") == 2",
"assert min_operations_to_palindrome(\"racecar\") == 0"
] | To find the minimum number of operations required to make a given string a palindrome by deleting characters, we can utilize a dynamic programming approach. The idea is to find the longest palindromic subsequence in the string. The minimum number of deletions needed to make the string a palindrome is equal to the diffe... | 2,432 | [
{
"from": "human",
"value": "Write a function to find the minimum number of operations to make the given string palindrome by deleting characters. A palindrome is a string that reads the same backward as forward, e.g., 'radar' or 'level'."
},
{
"from": "gpt",
"value": "To find the minimum number... |
Write a python function to calculate the sum of all odd numbers in a given list. | Here is the code to solve this problem:
```python
def sum_odd_numbers(numbers):
return sum(num for num in numbers if num % 2 != 0)
``` | [
"assert sum_odd_numbers([1, 2, 3, 4, 5]) == 9",
"assert sum_odd_numbers([10, 22, 33, 47, 55]) == 135",
"assert sum_odd_numbers([2, 4, 6, 8, 10]) == 0"
] | You can calculate the sum of all odd numbers in a given list by creating a function that iterates through the list and checks if each number is odd. Here's a simple implementation of such a function:
```python
def sum_of_odd_numbers(numbers):
# Initialize the sum to 0
total_sum = 0
# Iterate through each n... | 2,433 | [
{
"from": "human",
"value": "Write a python function to calculate the sum of all odd numbers in a given list."
},
{
"from": "gpt",
"value": "You can calculate the sum of all odd numbers in a given list by creating a function that iterates through the list and checks if each number is odd. Here's... |
Write a function that takes an integer and returns the sum of its digits. | Here is the code to solve this problem:
```python
def digit_sum(n):
return sum(int(digit) for digit in str(n))
``` | [
"assert digit_sum(123) == 6",
"assert digit_sum(104) == 5",
"assert digit_sum(999) == 27"
] | You can easily create a function to sum the digits of an integer in Python. Below is a simple implementation of such a function:
```python
def sum_of_digits(n):
# Convert to string to easily iterate over each digit, and sum the integer values of each digit
return sum(int(digit) for digit in str(abs(n)))
# Exa... | 2,434 | [
{
"from": "human",
"value": "Write a function that takes an integer and returns the sum of its digits."
},
{
"from": "gpt",
"value": "You can easily create a function to sum the digits of an integer in Python. Below is a simple implementation of such a function:\n\n```python\ndef sum_of_digits(n... |
Write a function that returns the index of the first occurrence of a substring (needle) in a string (haystack). If the substring is not found, return -1. | Here is the code to solve this problem:
```python
def find_substring(haystack, needle):
if haystack is None or needle is None:
return 0
lenh = len(haystack)
lenn = len(needle)
if lenn == 0:
return 0
for i in range(lenh - lenn + 1):
j = 0
while(j < l... | [
"assert find_substring(\"world\", \"d\") == 4",
"assert find_substring(\"hello\", \"ll\") == 2",
"assert find_substring(\"python\", \"java\") == -1"
] | You can accomplish this by writing a function in Python that utilizes the built-in `str.find()` method or manually searches for the substring within the string. Here’s how to do it in a couple of ways:
### Using `str.find()`
The simplest way is to use the `find()` method of the string, which returns the lowest index ... | 2,435 | [
{
"from": "human",
"value": "Write a function that returns the index of the first occurrence of a substring (needle) in a string (haystack). If the substring is not found, return -1."
},
{
"from": "gpt",
"value": "You can accomplish this by writing a function in Python that utilizes the built-in... |
Write a function that takes a string and encrypts it using a Caesar cipher with a given shift key. The function should preserve the case of the letters and ignore any non-alphabetic characters. | Here is the code to solve this problem:
```python
def caesar_cipher(text, shift):
result = ''
for char in text:
if char.isalpha():
shift_amount = shift % 26
if char.islower():
result += chr((ord(char) - ord('a') + shift_amount) % 26 + ord('a'))
else:
... | [
"assert caesar_cipher('Hello, World!', 3) == 'Khoor, Zruog!'",
"assert caesar_cipher('Python Programming', 5) == 'Udymts Uwtlwfrrnsl'",
"assert caesar_cipher('123abcABC', 2) == '123cdeCDE'"
] | Certainly! Here is a Python function that implements a Caesar cipher encryption. This function takes a string and a shift key, preserving the case of alphabetic characters while ignoring non-alphabetic characters.
```python
def caesar_cipher_encrypt(text, shift):
encrypted_text = []
for char in text:
... | 2,436 | [
{
"from": "human",
"value": "Write a function that takes a string and encrypts it using a Caesar cipher with a given shift key. The function should preserve the case of the letters and ignore any non-alphabetic characters."
},
{
"from": "gpt",
"value": "Certainly! Here is a Python function that ... |
Write a python function to find the maximum difference between two elements such that larger element appears after the smaller number in the list. | Here is the code to solve this problem:
```python
def max_diff(lst):
if not lst:
return 0
min_element = lst[0]
max_diff = lst[1] - lst[0]
for i in range(1, len(lst)):
if lst[i] - min_element > max_diff:
max_diff = lst[i] - min_element
if lst[i] < min_element:
... | [
"assert max_diff([2,3,10,2,4,8,1]) == 8",
"assert max_diff([7,9,5,6,3,2]) == 2",
"assert max_diff([1,2,3,4,5]) == 4"
] | Certainly! To find the maximum difference between two elements in a list where the larger element appears after the smaller element, you can follow this approach:
1. Iterate through each element in the list while keeping track of the minimum element found so far.
2. For each element, calculate the difference between t... | 2,437 | [
{
"from": "human",
"value": "Write a python function to find the maximum difference between two elements such that larger element appears after the smaller number in the list."
},
{
"from": "gpt",
"value": "Certainly! To find the maximum difference between two elements in a list where the larger... |
Write a function to find the length of the longest substring without repeating characters in the given string. | Here is the code to solve this problem:
```python
def substring_length(s):
char_set = set()
l = 0
res = 0
for r in range(len(s)):
while s[r] in char_set:
char_set.remove(s[l])
l += 1
char_set.add(s[r])
res = max(res, r - l + 1)
return res
``` | [
"assert substring_length(\"abcabcbb\") == 3",
"assert substring_length(\"pwwkew\") == 3",
"assert substring_length(\"bbbbb\") == 1"
] | Certainly! You can find the length of the longest substring without repeating characters using a sliding window approach. Below is a Python function that implements this technique:
```python
def length_of_longest_substring(s: str) -> int:
char_index_map = {}
start = 0
max_length = 0
for end in range(l... | 2,438 | [
{
"from": "human",
"value": "Write a function to find the length of the longest substring without repeating characters in the given string."
},
{
"from": "gpt",
"value": "Certainly! You can find the length of the longest substring without repeating characters using a sliding window approach. Bel... |
Write a python function to convert a given string from snake_case to CamelCase. | Here is the code to solve this problem:
```python
def snake_to_camel(s):
components = s.split('_')
return ''.join(x.title() for x in components)
``` | [
"assert snake_to_camel(\"this_is_a_test_string\") == \"ThisIsATestString\"",
"assert snake_to_camel(\"snake_to_camel\") == \"SnakeToCamel\"",
"assert snake_to_camel(\"hello_world\") == \"HelloWorld\""
] | You can create a function in Python that converts a string from `snake_case` to `CamelCase` by following these steps:
1. Split the input string at underscores (`_`).
2. Capitalize the first letter of each split component.
3. Join the capitalized components without spaces to form the final result.
Here's a Python func... | 2,439 | [
{
"from": "human",
"value": "Write a python function to convert a given string from snake_case to CamelCase."
},
{
"from": "gpt",
"value": "You can create a function in Python that converts a string from `snake_case` to `CamelCase` by following these steps:\n\n1. Split the input string at unders... |
Write a function to find the greatest common divisor (GCD) of two numbers using the Euclidean algorithm. | Here is the code to solve this problem:
```python
def find_gcd(x, y):
while(y):
x, y = y, x % y
return x
``` | [
"assert find_gcd(81, 153)==9",
"assert find_gcd(100, 80)==20",
"assert find_gcd(48, 180)==12"
] | Certainly! The Euclidean algorithm is a very efficient method for finding the greatest common divisor (GCD) of two integers. Here is a Python function that implements this algorithm:
```python
def gcd(a, b):
while b != 0:
a, b = b, a % b
return abs(a) # Return the absolute value of GCD
# Example usag... | 2,440 | [
{
"from": "human",
"value": "Write a function to find the greatest common divisor (GCD) of two numbers using the Euclidean algorithm."
},
{
"from": "gpt",
"value": "Certainly! The Euclidean algorithm is a very efficient method for finding the greatest common divisor (GCD) of two integers. Here i... |
Write a python function to find the number of subarrays which sum up to a given value k. | Here is the code to solve this problem:
```python
def find_subarrays_with_sum(nums, k):
count = 0
sum_list = [0]
answer = 0
for i in range(len(nums)):
sum_list.append(sum_list[-1]+nums[i])
for i in range(len(sum_list)):
for j in range(i+1, len(sum_list)):
if sum_list[j... | [
"assert find_subarrays_with_sum([1, 2, 3], 3) == 2",
"assert find_subarrays_with_sum([1, 1, 1], 2) == 2",
"assert find_subarrays_with_sum([10, 2, -2, -20, 10], -10) == 3"
] | You can solve the problem of finding the number of subarrays that sum up to a given value `k` using a hash map (dictionary in Python) to keep track of the cumulative sums. This approach has a time complexity of O(n), where n is the number of elements in the input array.
Here is a Python function that implements this m... | 2,441 | [
{
"from": "human",
"value": "Write a python function to find the number of subarrays which sum up to a given value k."
},
{
"from": "gpt",
"value": "You can solve the problem of finding the number of subarrays that sum up to a given value `k` using a hash map (dictionary in Python) to keep track... |
Write a function to find the maximum sum of a subarray with the length of k. | Here is the code to solve this problem:
```python
def max_sum_subarray(arr, k):
if len(arr) < k:
return None
max_sum = current_sum = sum(arr[:k])
for i in range(k, len(arr)):
current_sum = current_sum - arr[i-k] + arr[i]
max_sum = max(max_sum, current_sum)
return max_s... | [
"assert max_sum_subarray([1, 4, -2, -10, 23, 3, 1, 0, 20], 4) == 27",
"assert max_sum_subarray([2, 3, 4, 1, 5], 2) == 7",
"assert max_sum_subarray([1, 4, 2, 10, 23, 3, 1, 0, 20], 4) == 39"
] | Certainly! You can find the maximum sum of a subarray with a given length \( k \) using a sliding window approach. This approach is efficient and works in \( O(n) \) time complexity, where \( n \) is the length of the input array. Below is a Python function that accomplishes this:
```python
def max_sum_subarray(arr, k... | 2,442 | [
{
"from": "human",
"value": "Write a function to find the maximum sum of a subarray with the length of k."
},
{
"from": "gpt",
"value": "Certainly! You can find the maximum sum of a subarray with a given length \\( k \\) using a sliding window approach. This approach is efficient and works in \\... |
Write a function to find the largest number formed by the given list of integers. | Here is the code to solve this problem:
```python
import functools
def largest_number(numbers):
def comparator(n1, n2):
number_1 = int(n1 + n2)
number_2 = int(n2 + n1)
return (number_1 > number_2) - (number_1 < number_2)
numbers = list(map(str, numbers))
numbers = sorted(numbers... | [
"assert largest_number([10, 2]) == \"210\"",
"assert largest_number([1, 10, 100, 1000]) == \"1101001000\"",
"assert largest_number([3, 30, 34, 5, 9]) == \"9534330\""
] | To find the largest number that can be formed by a list of integers, we can approach the problem by sorting the integers based on their string representations. Specifically, we'll convert each integer to a string and sort them in such a way that when concatenated, produces the largest possible number.
Here is a Python... | 2,443 | [
{
"from": "human",
"value": "Write a function to find the largest number formed by the given list of integers."
},
{
"from": "gpt",
"value": "To find the largest number that can be formed by a list of integers, we can approach the problem by sorting the integers based on their string representat... |
Write a function to determine if a given linked list is a palindrome. A linked list is a palindrome if it reads the same backward as forward. | Here is the code to solve this problem:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def create_linked_list(lst):
head = ListNode(lst[0])
current = head
for i in range(1, len(lst)):
current.next = ListNode(lst[i])
curre... | [
"assert is_palindrome_linked_list(create_linked_list([1, 2, 3, 4, 5])) == False",
"assert is_palindrome_linked_list(create_linked_list([1, 2, 2, 1])) == True",
"assert is_palindrome_linked_list(create_linked_list([1])) == True",
"assert is_palindrome_linked_list(create_linked_list([1, 2, 3, 2, 1])) == True"
] | To determine if a given linked list is a palindrome, we can follow a two-step approach:
1. **Find the middle of the linked list** using the slow and fast pointer technique.
2. **Reverse the second half of the linked list** and compare it with the first half.
Here is a Python implementation of a method to check if a s... | 2,444 | [
{
"from": "human",
"value": "Write a function to determine if a given linked list is a palindrome. A linked list is a palindrome if it reads the same backward as forward."
},
{
"from": "gpt",
"value": "To determine if a given linked list is a palindrome, we can follow a two-step approach:\n\n1. ... |
Write a function that checks if a given set of four points form a non-degenerate square. The points are represented as lists of two integers, [x, y], where x and y are the coordinates of the point on a 2D plane. A non-degenerate square is a square with positive area. | Here is the code to solve this problem:
```python
from typing import List
def is_non_degenerate_square(p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
def distance2(point1, point2):
x1, y1 = point1
x2, y2 = point2
return (x1 - x2) ** 2 + (y1 - y2) ** 2
points = [p... | [
"assert is_non_degenerate_square([0, 0], [1, 1], [1, 0], [0, 2]) == False",
"assert is_non_degenerate_square([0, 0], [1, 1], [1, 0], [0, 1]) == True",
"assert is_non_degenerate_square([1, -1], [1, 1], [-1, 1], [-1, -1]) == True"
] | To determine if a given set of four points forms a non-degenerate square in a 2D plane, we can follow these steps:
1. Check that the number of unique points is exactly four.
2. Calculate the distances between every pair of points.
3. A valid square has:
- Four sides of equal length.
- Two diagonals of equal leng... | 2,445 | [
{
"from": "human",
"value": "Write a function that checks if a given set of four points form a non-degenerate square. The points are represented as lists of two integers, [x, y], where x and y are the coordinates of the point on a 2D plane. A non-degenerate square is a square with positive area."
},
{
... |
Write a function to convert a given list of strings into a dictionary where the keys are the strings and the values are the lengths of the strings. | Here is the code to solve this problem:
```python
def string_length_dict(string_list):
result = {x: len(x) for x in string_list}
return result
``` | [
"assert string_length_dict(['hello', 'world', 'python']) == {'hello': 5, 'world': 5, 'python': 6}",
"assert string_length_dict(['apple', 'banana', 'cherry']) == {'apple': 5, 'banana': 6, 'cherry': 6}",
"assert string_length_dict(['cat', 'dog', 'elephant']) == {'cat': 3, 'dog': 3, 'elephant': 8}"
] | You can create a function in Python that takes a list of strings and returns a dictionary with the strings as keys and their lengths as values. Here’s a simple implementation:
```python
def strings_to_lengths(string_list):
return {s: len(s) for s in string_list}
# Example usage:
input_list = ["apple", "banana", "... | 2,446 | [
{
"from": "human",
"value": "Write a function to convert a given list of strings into a dictionary where the keys are the strings and the values are the lengths of the strings."
},
{
"from": "gpt",
"value": "You can create a function in Python that takes a list of strings and returns a dictionar... |
Write a python function to find the maximum and minimum number from a sequence of numbers. | Here is the code to solve this problem:
```python
def max_min_number(sequence):
max_num = max(sequence)
min_num = min(sequence)
return max_num, min_num
``` | [
"assert max_min_number([10, 20, 30, 40, 50]) == (50, 10)",
"assert max_min_number([-1, -2, -3, -4, 0]) == (0, -4)",
"assert max_min_number([1, 2, 3, 4, 5]) == (5, 1)"
] | You can create a Python function that takes a list of numbers as input and returns the maximum and minimum numbers from that list. Here's a simple implementation of such a function:
```python
def find_max_min(numbers):
# Check if the input is empty
if not numbers:
return None, None # Return None for b... | 2,447 | [
{
"from": "human",
"value": "Write a python function to find the maximum and minimum number from a sequence of numbers."
},
{
"from": "gpt",
"value": "You can create a Python function that takes a list of numbers as input and returns the maximum and minimum numbers from that list. Here's a simpl... |
Write a function to check if a given number is a perfect number or not. A perfect number is a positive integer that is equal to the sum of its proper divisors. The smallest perfect number is 6, which is the sum of 1, 2, and 3. | Here is the code to solve this problem:
```python
def check_perfect_number(num):
if num < 1:
return False
sum = 0
for i in range(1, num):
if num % i == 0:
sum += i
return sum == num
``` | [
"assert check_perfect_number(28) == True",
"assert check_perfect_number(6) == True",
"assert check_perfect_number(496) == True",
"assert check_perfect_number(12) == False"
] | Sure! Below is a Python function that checks if a given number is a perfect number. The function computes the sum of the proper divisors of the number and compares it to the number itself.
```python
def is_perfect_number(n):
if n <= 1:
return False # 0 and 1 are not perfect numbers
# Find proper ... | 2,448 | [
{
"from": "human",
"value": "Write a function to check if a given number is a perfect number or not. A perfect number is a positive integer that is equal to the sum of its proper divisors. The smallest perfect number is 6, which is the sum of 1, 2, and 3."
},
{
"from": "gpt",
"value": "Sure! Bel... |
Write a Python function that computes the Cartesian product of two lists. | Here is the code to solve this problem:
```python
def cartesian_product(list1, list2):
result = []
for i in list1:
for j in list2:
result.append((i, j))
return result
``` | [
"assert cartesian_product([1, 2], ['a', 'b']) == [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]",
"assert cartesian_product(['x', 'y'], [1, 2, 3]) == [('x', 1), ('x', 2), ('x', 3), ('y', 1), ('y', 2), ('y', 3)]",
"assert cartesian_product([1, 3], [2, 4]) == [(1, 2), (1, 4), (3, 2), (3, 4)]"
] | Certainly! The Cartesian product of two lists can be computed using a simple nested loop, or you can use the `itertools.product` function from the Python standard library, which is more concise and efficient.
Here’s a function to compute the Cartesian product using both methods:
### Method 1: Using Nested Loops
```p... | 2,449 | [
{
"from": "human",
"value": "Write a Python function that computes the Cartesian product of two lists."
},
{
"from": "gpt",
"value": "Certainly! The Cartesian product of two lists can be computed using a simple nested loop, or you can use the `itertools.product` function from the Python standard... |
Write a function to find the intersection of two lists, returning the common elements without duplicates. | Here is the code to solve this problem:
```python
def common_elements(list1, list2):
return list(set(list1) & set(list2))
``` | [
"assert common_elements([1,2,3,4,5], [4,5,6,7,8]) == [4, 5]",
"assert common_elements([10,20,30,40], [20,30,50,60]) == [20, 30]",
"assert common_elements([1,2,3], [4,5,6]) == []"
] | You can find the intersection of two lists by using Python's built-in data structures such as sets, which automatically handle duplicates for you. Here’s a simple function that takes two lists as input and returns a list of unique common elements:
```python
def intersect_lists(list1, list2):
# Convert lists to set... | 2,450 | [
{
"from": "human",
"value": "Write a function to find the intersection of two lists, returning the common elements without duplicates."
},
{
"from": "gpt",
"value": "You can find the intersection of two lists by using Python's built-in data structures such as sets, which automatically handle dup... |
Write a python function to find the maximum water that can be contained between two vertical lines on a histogram. The width of each bar is 1. | Here is the code to solve this problem:
```python
def max_water(height):
left, right = 0, len(height) - 1
max_area = 0
while left < right:
max_area = max(max_area, min(height[left], height[right]) * (right - left))
if height[left] < height[right]:
left += 1
else:
... | [
"assert max_water([4,3,2,1,4])==16",
"assert max_water([1,1])==1",
"assert max_water([1,8,6,2,5,4,8,3,7])==49"
] | You can solve this problem using the two-pointer approach, which effectively finds the maximum area bounded by two vertical lines representing the heights of the bars in the histogram. Here's a Python function that implements this approach:
```python
def max_area(height):
left = 0
right = len(height) - 1
m... | 2,451 | [
{
"from": "human",
"value": "Write a python function to find the maximum water that can be contained between two vertical lines on a histogram. The width of each bar is 1."
},
{
"from": "gpt",
"value": "You can solve this problem using the two-pointer approach, which effectively finds the maximu... |
Write a function to find the most frequent character in a given string. If there are multiple characters with the same highest frequency, return all of them in a list sorted by their appearance in the string. | Here is the code to solve this problem:
```python
def most_frequent_char(s):
count = dict()
for item in s:
if item in count:
count[item] += 1
else:
count[item] = 1
max_freq = max(count.values())
result = [k for k, v in count.items() if v == max_freq]
return s... | [
"assert most_frequent_char(\"mississippi\") == ['i', 's']",
"assert most_frequent_char(\"hello world\") == ['l']",
"assert most_frequent_char(\"apple\") == ['p']"
] | Sure! Below is a Python function that takes a string as an input and finds the most frequent character(s). If there are multiple characters with the same highest frequency, it returns them in a list sorted by their first appearance in the string.
```python
def most_frequent_char(s):
frequency = {}
# Count... | 2,452 | [
{
"from": "human",
"value": "Write a function to find the most frequent character in a given string. If there are multiple characters with the same highest frequency, return all of them in a list sorted by their appearance in the string."
},
{
"from": "gpt",
"value": "Sure! Below is a Python fun... |
Write a python function to count the number of occurrences of a substring in a main string, ignoring case sensitivity. | Here is the code to solve this problem:
```python
def substring_count(main_string, substring):
main_string = main_string.lower()
substring = substring.lower()
return main_string.count(substring)
``` | [
"assert substring_count('Hello world', 'o') == 2",
"assert substring_count('Python programming', 'mm') == 1",
"assert substring_count('Data Science', 'data') == 1"
] | You can create a function in Python that counts the number of occurrences of a substring in a main string while ignoring case sensitivity. To do this, you can convert both the main string and the substring to the same case (either upper or lower) using the `str.lower()` or `str.upper()` methods. Then, you can use the `... | 2,453 | [
{
"from": "human",
"value": "Write a python function to count the number of occurrences of a substring in a main string, ignoring case sensitivity."
},
{
"from": "gpt",
"value": "You can create a function in Python that counts the number of occurrences of a substring in a main string while ignor... |
Write a python function to find the minimum number of operations required to transform a given number into 1. The operations allowed are:
1. If the number is even, you can divide it by 2.
2. If the number is odd, you can either add or subtract 1 from it. | Here is the code to solve this problem:
```python
def min_operations(n):
operations = 0
while n != 1:
if n % 2 == 0:
n = n // 2
else:
if n == 3 or n % 4 == 1:
n -= 1
else:
n += 1
operations += 1
return operations
``... | [
"assert min_operations(4) == 2",
"assert min_operations(15) == 5",
"assert min_operations(1) == 0"
] | You can solve this problem using a breadth-first search (BFS) approach, as it explores all possible states (numbers) and finds the shortest path (minimum operations) to reach the target number (1). Here's how you can implement this in Python:
```python
from collections import deque
def min_operations_to_one(n):
i... | 2,454 | [
{
"from": "human",
"value": "Write a python function to find the minimum number of operations required to transform a given number into 1. The operations allowed are:\n1. If the number is even, you can divide it by 2.\n2. If the number is odd, you can either add or subtract 1 from it."
},
{
"from": ... |
Write a function to check if the given list of integers is a valid mountain array.
A mountain array is defined as:
- It has at least three elements
- There exists some index i (0 < i < arr.length - 1) such that:
- arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
- arr[i] > arr[i + 1] > ... > arr[arr.length - 1] | Here is the code to solve this problem:
```python
def is_mountain_array(arr):
if len(arr) < 3:
return False
peak = 0
for i in range(1, len(arr)):
if arr[i] > arr[i - 1]:
peak = i
else:
break
if peak == 0 or peak == len(arr) - 1:
return False
f... | [
"assert is_mountain_array([2, 1]) == False",
"assert is_mountain_array([0, 3, 2, 1]) == True",
"assert is_mountain_array([3, 5, 5]) == False"
] | To check if a given list of integers is a valid mountain array, we can follow these steps:
1. First, check if the length of the array is less than 3. If it is, return `False` because a mountain array needs at least three elements.
2. Initialize two pointers or indices: traverse the array from the start to find the pea... | 2,455 | [
{
"from": "human",
"value": "Write a function to check if the given list of integers is a valid mountain array.\n\nA mountain array is defined as:\n- It has at least three elements\n- There exists some index i (0 < i < arr.length - 1) such that:\n - arr[0] < arr[1] < ... < arr[i - 1] < arr[i]\n - arr[... |
Write a function to find the intersection of two sorted lists. | Here is the code to solve this problem:
```python
def intersection_sorted_lists(list1, list2):
i, j = 0, 0
result = []
while i < len(list1) and j < len(list2):
if list1[i] == list2[j]:
result.append(list1[i])
i += 1
j += 1
elif list1[i] < list2[j]:
... | [
"assert intersection_sorted_lists([1, 3, 5, 7, 9], [2, 4, 6, 8, 10]) == []",
"assert intersection_sorted_lists([1, 2, 4, 5, 6], [2, 3, 5, 7]) == [2, 5]",
"assert intersection_sorted_lists([1, 2, 2, 3, 4], [2, 2, 4, 6, 8]) == [2, 2, 4]"
] | Certainly! To find the intersection of two sorted lists, we can use a two-pointer technique, which is efficient given that both lists are already sorted. Here's a Python function that implements this approach:
```python
def intersect_sorted_lists(list1, list2):
# Initialize pointers for both lists
pointer1 = 0... | 2,456 | [
{
"from": "human",
"value": "Write a function to find the intersection of two sorted lists."
},
{
"from": "gpt",
"value": "Certainly! To find the intersection of two sorted lists, we can use a two-pointer technique, which is efficient given that both lists are already sorted. Here's a Python fun... |
Write a python function to check if a string can be constructed by rearranging the characters of another string. | Here is the code to solve this problem:
```python
from collections import Counter
def can_construct(str1, str2):
return Counter(str1) == Counter(str2)
``` | [
"assert can_construct(\"world\", \"dlrow\")==True",
"assert can_construct(\"python\", \"nothyp\")==True",
"assert can_construct(\"hello\", \"oellh\")==True",
"assert can_construct(\"java\", \"avaj\")==True"
] | You can check if a string can be constructed by rearranging the characters of another string by following these steps:
1. Both strings must have the same length.
2. Both strings must have the same character counts.
We can implement this check in a Python function using the `collections.Counter` class which will allow... | 2,457 | [
{
"from": "human",
"value": "Write a python function to check if a string can be constructed by rearranging the characters of another string."
},
{
"from": "gpt",
"value": "You can check if a string can be constructed by rearranging the characters of another string by following these steps:\n\n1... |
Write a function that merges two sorted lists into one sorted list. | Here is the code to solve this problem:
```python
def merge_sorted_lists(list1, list2):
merged_list = []
i = j = 0
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
merged_list.append(list1[i])
i += 1
else:
merged_list.append(list2[j])
... | [
"assert merge_sorted_lists([1, 3, 5], [2, 4, 6]) == [1, 2, 3, 4, 5, 6]",
"assert merge_sorted_lists([1, 4, 7], [2, 5, 8]) == [1, 2, 4, 5, 7, 8]",
"assert merge_sorted_lists([1, 2, 3], [4, 5, 6]) == [1, 2, 3, 4, 5, 6]"
] | You can merge two sorted lists into one sorted list using a function in Python. Below is a simple implementation of such a function:
```python
def merge_sorted_lists(list1, list2):
merged_list = []
i, j = 0, 0
# Traverse both lists and append smaller element to the merged list
while i < len(list1) and... | 2,458 | [
{
"from": "human",
"value": "Write a function that merges two sorted lists into one sorted list."
},
{
"from": "gpt",
"value": "You can merge two sorted lists into one sorted list using a function in Python. Below is a simple implementation of such a function:\n\n```python\ndef merge_sorted_list... |
Write a function to find the first occurrence of a substring within a string. If the substring is not found, return -1. | Here is the code to solve this problem:
```python
def str_find(s, sub):
m, n = len(sub), len(s)
if m > n:
return -1
low, high = 0, 0
while high < n:
i = 0
while i < m and high < n and s[high] == sub[i]:
if i == m - 1:
return low
high, i =... | [
"assert str_find(\"hello world\", \"world\") == 6",
"assert str_find(\"data science\", \"data\") == 0",
"assert str_find(\"machine learning\", \"deep\") == -1"
] | Certainly! Below is a Python function that finds the first occurrence of a substring within a given string. If the substring is found, it returns the index of its first occurrence; if not, it returns -1.
```python
def find_first_occurrence(string, substring):
index = string.find(substring)
return index
# Exam... | 2,459 | [
{
"from": "human",
"value": "Write a function to find the first occurrence of a substring within a string. If the substring is not found, return -1."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that finds the first occurrence of a substring within a given string. If the s... |
Write a python function to find the maximum length of a contiguous subarray with equal number of 0 and 1. | Here is the code to solve this problem:
```python
def max_length_of_subarray(nums):
count = 0
max_length = 0
count_dict = {0: -1}
for i in range(len(nums)):
if nums[i] == 0:
count -= 1
else:
count += 1
if count in count_dict:
max_length = max(... | [
"assert max_length_of_subarray([0,1]) == 2",
"assert max_length_of_subarray([0,1,0]) == 2",
"assert max_length_of_subarray([0,0,1,0,1,1]) == 6"
] | Certainly! To find the maximum length of a contiguous subarray with an equal number of 0s and 1s, we can utilize a hash map (dictionary in Python) to store the cumulative counts of 0s and 1s. The key insight is to consider 0s as -1 and 1s as +1, and then keep track of the cumulative sum. When the cumulative sum is the ... | 2,460 | [
{
"from": "human",
"value": "Write a python function to find the maximum length of a contiguous subarray with equal number of 0 and 1."
},
{
"from": "gpt",
"value": "Certainly! To find the maximum length of a contiguous subarray with an equal number of 0s and 1s, we can utilize a hash map (dicti... |
Write a python function to determine if a given list of integers can reach the last index using the integers' values as jump lengths. The function should return True if it's possible to reach the last index, otherwise False. | Here is the code to solve this problem:
```python
def can_jump(nums):
max_reach = 0
for i in range(len(nums)):
if i > max_reach:
return False
max_reach = max(max_reach, i + nums[i])
if max_reach >= len(nums) - 1:
return True
return False
``` | [
"assert can_jump([1,0]) == True",
"assert can_jump([2,3,1,1,4]) == True",
"assert can_jump([0]) == True",
"assert can_jump([3,2,1,0,4]) == False",
"assert can_jump([0,1]) == False",
"assert can_jump([2,0,0]) == True"
] | You can solve this problem using a greedy approach. The idea is to keep track of the furthest index that can be reached as you traverse the list. If at any point you reach an index that is beyond the furthest index that can be reached, then it's impossible to reach the last index.
Here’s how you can implement this in ... | 2,461 | [
{
"from": "human",
"value": "Write a python function to determine if a given list of integers can reach the last index using the integers' values as jump lengths. The function should return True if it's possible to reach the last index, otherwise False."
},
{
"from": "gpt",
"value": "You can sol... |
Write a function to reverse the words in a given sentence while keeping the order of the words intact. | Here is the code to solve this problem:
```python
def reverse_words_in_sentence(sentence):
result = ' '.join([word[::-1] for word in sentence.split()])
return result
``` | [
"assert reverse_words_in_sentence(\"I love Python\") == \"I evol nohtyP\"",
"assert reverse_words_in_sentence(\"Hello World\") == \"olleH dlroW\"",
"assert reverse_words_in_sentence(\"This is a test\") == \"sihT si a tset\""
] | Certainly! You can achieve this by creating a function that splits the sentence into words, reverses each word, and then combines them back into a single string. Below is a Python function that does just that:
```python
def reverse_words_in_sentence(sentence):
# Split the sentence into words
words = sentence.s... | 2,462 | [
{
"from": "human",
"value": "Write a function to reverse the words in a given sentence while keeping the order of the words intact."
},
{
"from": "gpt",
"value": "Certainly! You can achieve this by creating a function that splits the sentence into words, reverses each word, and then combines the... |
Write a python function to find the minimum number of jumps to reach the end of the array from the first element.
The function should take a list of integers as input and return the minimum number of jumps to reach the end of the array. Each element in the array represents the maximum number of steps that can be jumpe... | Here is the code to solve this problem:
```python
def minJumps(arr):
n = len(arr)
if n <= 1:
return 0
if arr[0] == 0:
return -1
maxReach = arr[0]
step = arr[0]
jump = 1
for i in range(1, n):
if i == n - 1:
return jump
maxReach = max(maxReach, i + ... | [
"assert minJumps([1, 1, 1, 1, 1]) == 4",
"assert minJumps([2, 3, 1, 1, 4]) == 2",
"assert minJumps([0, 2, 3]) == -1",
"assert minJumps([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) == 1"
] | To solve the problem of finding the minimum number of jumps to reach the end of the array, you can implement a greedy algorithm. The idea is to keep track of the maximum reachable index at each step and determine how many jumps are needed to reach the end.
Here's a Python function that implements this algorithm:
```p... | 2,463 | [
{
"from": "human",
"value": "Write a python function to find the minimum number of jumps to reach the end of the array from the first element.\n\nThe function should take a list of integers as input and return the minimum number of jumps to reach the end of the array. Each element in the array represents th... |
Write a function to find the closest value to a target in a sorted list of integers. If two numbers are equally close, return the smallest number. | Here is the code to solve this problem:
```python
def closest_value(nums, target):
left = 0
right = len(nums) - 1
closest = float('inf')
closest_val = nums[0]
while left <= right:
mid = (left + right) // 2
if abs(target - nums[mid]) < closest:
closest = abs(target -... | [
"assert closest_value([1, 2, 3, 4, 5], -1) == 1",
"assert closest_value([1, 2, 3, 4, 5], 2.5) == 2",
"assert closest_value([1, 2, 3, 4, 5], 6) == 5",
"assert closest_value([1, 2, 3, 4, 5], 3.7) == 4"
] | You can implement a function to find the closest value to a target in a sorted list of integers using a binary search approach for efficiency. Here's how you can do it in Python:
```python
def find_closest(nums, target):
if not nums:
return None # Return None if the input list is empty
left, right = ... | 2,464 | [
{
"from": "human",
"value": "Write a function to find the closest value to a target in a sorted list of integers. If two numbers are equally close, return the smallest number."
},
{
"from": "gpt",
"value": "You can implement a function to find the closest value to a target in a sorted list of in... |
Write a function to convert a given list of numbers into a single number by concatenating them. | Here is the code to solve this problem:
```python
def list_to_number(numbers):
result = ''.join(str(number) for number in numbers)
return int(result)
``` | [
"assert list_to_number([4, 5, 6, 7])==4567",
"assert list_to_number([1, 2, 3])==123",
"assert list_to_number([8, 9, 0, 1, 2])==89012"
] | Sure! Below is a Python function that takes a list of numbers, converts each number to a string, and then concatenates them into a single string. Finally, it converts that string back to an integer and returns it.
```python
def concatenate_numbers(num_list):
# Convert each number to a string
str_list = map(str... | 2,465 | [
{
"from": "human",
"value": "Write a function to convert a given list of numbers into a single number by concatenating them."
},
{
"from": "gpt",
"value": "Sure! Below is a Python function that takes a list of numbers, converts each number to a string, and then concatenates them into a single st... |
Write a python function to find the number of unique paths from the top-left corner to the bottom-right corner in a 2D grid. Paths can only move right or down. Obstacles are represented as 1 in the grid and cannot be passed through. | Here is the code to solve this problem:
```python
def uniquePaths(obstacleGrid):
m=len(obstacleGrid)
n=len(obstacleGrid[0])
dp=[[-1 for i in range (n+1)] for j in range (m+1)]
ans=helper(obstacleGrid,m-1,n-1,dp)
return ans
def helper(obstacleGrid,row,col,dp):
... | [
"assert uniquePaths([[0,1],[0,0]]) == 1",
"assert uniquePaths([[0,0,0],[0,1,0],[0,0,0]]) == 2",
"assert uniquePaths([[0]]) == 1"
] | To solve the problem of finding the number of unique paths from the top-left corner to the bottom-right corner in a 2D grid, while considering obstacles that cannot be passed through, we can use dynamic programming.
Here is a Python function that implements this approach:
```python
def unique_paths_with_obstacles(ob... | 2,466 | [
{
"from": "human",
"value": "Write a python function to find the number of unique paths from the top-left corner to the bottom-right corner in a 2D grid. Paths can only move right or down. Obstacles are represented as 1 in the grid and cannot be passed through."
},
{
"from": "gpt",
"value": "To ... |
Write a python function to check if a given string is an anagram of a palindrome.
A palindrome is a word that reads the same backward as forward, e.g., 'radar'. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once, e.g., '... | Here is the code to solve this problem:
```python
def is_anagram_of_palindrome(s: str) -> bool:
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
odd_counts = 0
for count in char_count.values():
if coun... | [
"assert is_anagram_of_palindrome(\"aabbcc\") == True",
"assert is_anagram_of_palindrome(\"aabbccde\") == False",
"assert is_anagram_of_palindrome(\"cinema\") == False",
"assert is_anagram_of_palindrome(\"radar\") == True",
"assert is_anagram_of_palindrome(\"aabbccd\") == True"
] | To determine if a given string is an anagram of a palindrome, we can use the following insights:
1. **Character Count**: A string can be rearranged into a palindrome if at most one character has an odd count. This is because, in a palindrome, characters appear in mirrored pairs around the center. For example:
- The... | 2,467 | [
{
"from": "human",
"value": "Write a python function to check if a given string is an anagram of a palindrome.\n\nA palindrome is a word that reads the same backward as forward, e.g., 'radar'. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all... |
Write a function to find the largest rectangle containing only 1's in a binary matrix. | Here is the code to solve this problem:
```python
def largest_rectangle(matrix):
if not matrix:
return 0
m, n = len(matrix), len(matrix[0])
heights = [0] * (n + 1)
max_area = 0
for i in range(m):
for j in range(n):
heights[j] = heights[j] + 1 if matrix[i][j] == 1 else 0
... | [
"assert largest_rectangle([[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 0, 0]]) == 8",
"assert largest_rectangle([[1, 1], [1, 1]]) == 4",
"assert largest_rectangle([[1, 0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 0, 1, 0]]) == 6"
] | To find the largest rectangle containing only 1's in a binary matrix, we can use a dynamic programming approach with a stack. The basic idea is to treat each row of the matrix as a histogram and use the largest rectangle in histogram concept.
Here’s a step-by-step Python function to achieve this:
1. Convert each row ... | 2,468 | [
{
"from": "human",
"value": "Write a function to find the largest rectangle containing only 1's in a binary matrix."
},
{
"from": "gpt",
"value": "To find the largest rectangle containing only 1's in a binary matrix, we can use a dynamic programming approach with a stack. The basic idea is to tr... |
Write a function to find the intersecting elements between two lists and return the result as a set. | Here is the code to solve this problem:
```python
def intersect_elements(list1, list2):
return set(list1) & set(list2)
``` | [
"assert intersect_elements([1, 2, 3, 4, 5], [4, 5, 6, 7, 8]) == {4, 5}",
"assert intersect_elements([10, 20, 30], [40, 50, 60]) == set()",
"assert intersect_elements(['apple', 'banana', 'orange'], ['banana', 'grape', 'orange']) == {'banana', 'orange'}"
] | You can create a function in Python to find the intersecting elements between two lists by using the built-in set data type, which allows for easy computation of intersections. Here is a simple implementation of such a function:
```python
def find_intersection(list1, list2):
# Convert both lists to sets
set1 =... | 2,469 | [
{
"from": "human",
"value": "Write a function to find the intersecting elements between two lists and return the result as a set."
},
{
"from": "gpt",
"value": "You can create a function in Python to find the intersecting elements between two lists by using the built-in set data type, which allo... |
Write a function to check if a number is a Harshad number. A Harshad number in a given number base is an integer that is divisible by the sum of its digits when written in that base.
Example:
Input: n = 18
Output: true
Explanation: 18 is divisible by the sum of its digits in base 10 (1 + 8 = 9).
Input: n = 1729
Outpu... | Here is the code to solve this problem:
```python
def is_harshad_number(n):
digit_sum = sum(int(digit) for digit in str(n))
return n % digit_sum == 0
``` | [
"assert is_harshad_number(19) == False",
"assert is_harshad_number(1) == True",
"assert is_harshad_number(18) == True",
"assert is_harshad_number(1729) == True"
] | Here’s a Python function that checks whether a given number is a Harshad number. The function computes the sum of the digits of the number in base 10 and then checks if the number is divisible by this sum.
```python
def is_harshad(n):
# Convert the number to a string to iterate over digits
str_n = str(n)
... | 2,470 | [
{
"from": "human",
"value": "Write a function to check if a number is a Harshad number. A Harshad number in a given number base is an integer that is divisible by the sum of its digits when written in that base.\n\nExample:\nInput: n = 18\nOutput: true\nExplanation: 18 is divisible by the sum of its digits ... |
Write a function to check if a given string is a rotation of a palindrome. | Here is the code to solve this problem:
```python
def isRotationOfPalindrome(s):
def isPalindrome(s):
return s == s[::-1]
for i in range(len(s)):
if isPalindrome(s):
return True
s = s[1:] + s[0]
return False
``` | [
"assert isRotationOfPalindrome(\"racecar\") == True",
"assert isRotationOfPalindrome(\"hello\") == False",
"assert isRotationOfPalindrome(\"tacocat\") == True"
] | To determine if a given string is a rotation of a palindrome, we can use the following approach:
1. **Check if the string can be a palindrome**: A string can be a rearrangement of a palindrome if at most one character has an odd count (for odd-length palindromes) or all characters have even counts (for even-length pal... | 2,471 | [
{
"from": "human",
"value": "Write a function to check if a given string is a rotation of a palindrome."
},
{
"from": "gpt",
"value": "To determine if a given string is a rotation of a palindrome, we can use the following approach:\n\n1. **Check if the string can be a palindrome**: A string can ... |
Write a python function to find the number of occurrences of a specific character in a given string and return the count. | Here is the code to solve this problem:
```python
def find_char_count(str, char):
count = 0
for i in str:
if i == char:
count += 1
return count
``` | [
"assert find_char_count('hello', 'l') == 2",
"assert find_char_count('mississippi', 's') == 4",
"assert find_char_count('character', 'c') == 2"
] | You can create a simple Python function to count the occurrences of a specific character in a given string using the built-in string method `.count()`. Here is an example of such a function:
```python
def count_character(string, character):
"""
Count the occurrences of a specific character in a given string.
... | 2,472 | [
{
"from": "human",
"value": "Write a python function to find the number of occurrences of a specific character in a given string and return the count."
},
{
"from": "gpt",
"value": "You can create a simple Python function to count the occurrences of a specific character in a given string using t... |
Write a python function to find the length of the longest strictly increasing subsequence in an array. | Here is the code to solve this problem:
```python
def find_longest_increasing_subsequence(nums):
n = len(nums)
dp = [1] * n
for i in range(1, n):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
print(find_longest_increasing_sub... | [
"assert find_longest_increasing_subsequence([0, 1, 0, 3, 2, 3]) == 4",
"assert find_longest_increasing_subsequence([7, 7, 7, 7, 7, 7, 7]) == 1",
"assert find_longest_increasing_subsequence([10, 9, 2, 5, 3, 7, 101, 18]) == 4"
] | To find the length of the longest strictly increasing subsequence (LIS) in an array, you can use dynamic programming. Here’s a Python function that implements this approach:
```python
def length_of_lis(nums):
if not nums:
return 0
# Create an array to store the length of the longest increasing subsequ... | 2,473 | [
{
"from": "human",
"value": "Write a python function to find the length of the longest strictly increasing subsequence in an array."
},
{
"from": "gpt",
"value": "To find the length of the longest strictly increasing subsequence (LIS) in an array, you can use dynamic programming. Here’s a Python... |
Write a function to find the power of a number using recursion. The function takes a base number and a power number as parameters and returns the result of raising the base number to the power number. | Here is the code to solve this problem:
```python
def power(x, n):
if n == 0:
return 1
elif n < 0:
return 1 / power(x, -n)
elif n % 2 == 0:
return power(x * x, n // 2)
else:
return x * power(x, n - 1)
``` | [
"assert power(2, 3) == 8",
"assert power(2, -3) == 0.125",
"assert power(5, 0) == 1"
] | Certainly! Below is a Python function that uses recursion to calculate the power of a base number raised to a certain exponent. The function handles both positive and negative exponents.
```python
def power(base, exponent):
# Base case: any number raised to the power of 0 is 1
if exponent == 0:
return ... | 2,474 | [
{
"from": "human",
"value": "Write a function to find the power of a number using recursion. The function takes a base number and a power number as parameters and returns the result of raising the base number to the power number."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python functi... |
Write a function that returns the greatest common divisor of two integers. | Here is the code to solve this problem:
```python
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
``` | [
"assert gcd(8,12) == 4",
"assert gcd(17,31) == 1",
"assert gcd(54,24) == 6"
] | Certainly! You can find the greatest common divisor (GCD) of two integers using the Euclidean algorithm. Below is a Python function that implements this algorithm to compute the GCD:
```python
def gcd(a, b):
while b:
a, b = b, a % b
return abs(a) # Return the absolute value to ensure the result is non... | 2,475 | [
{
"from": "human",
"value": "Write a function that returns the greatest common divisor of two integers."
},
{
"from": "gpt",
"value": "Certainly! You can find the greatest common divisor (GCD) of two integers using the Euclidean algorithm. Below is a Python function that implements this algorith... |
Write a Python function that finds the longest consecutive subsequence in an array of positive integers. | Here is the code to solve this problem:
```python
def longest_consecutive_subsequence(arr):
if not arr:
return 0
arr = set(arr)
longest_streak = 0
for num in arr:
if num - 1 not in arr:
current_num = num
current_streak = 1
while current_num + 1 in ar... | [
"assert longest_consecutive_subsequence([100, 4, 200, 1, 3, 2]) == 4",
"assert longest_consecutive_subsequence([36, 41, 56, 35, 44, 33, 34, 92, 43, 32, 42]) == 5",
"assert longest_consecutive_subsequence([1, 9, 3, 10, 4, 20, 2]) == 4"
] | To find the longest consecutive subsequence in an array of positive integers, we can use a set to store the elements of the array. This allows us to check for the existence of numbers efficiently. The idea is to iterate through the array and, for each number, check if it is the start of a sequence. If it is, we count t... | 2,476 | [
{
"from": "human",
"value": "Write a Python function that finds the longest consecutive subsequence in an array of positive integers."
},
{
"from": "gpt",
"value": "To find the longest consecutive subsequence in an array of positive integers, we can use a set to store the elements of the array. ... |
Write a python function to count the frequency of each character in a given string. | Here is the code to solve this problem:
```python
def character_frequency(str1):
dict = {}
for n in str1:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
return dict
``` | [
"assert character_frequency(\"algorithm\") == {'a': 1, 'l': 1, 'g': 1, 'o': 1, 'r': 1, 'i': 1, 't': 1, 'h': 1, 'm': 1}",
"assert character_frequency(\"programming\") == {'p': 1, 'r': 2, 'o': 1, 'g': 2, 'a': 1, 'm': 2, 'i': 1, 'n': 1}",
"assert character_frequency(\"hello\") == {'h': 1, 'e': 1, 'l': 2, 'o': 1}"
... | Certainly! You can use the following Python function to count the frequency of each character in a given string. This function uses a dictionary to store the count of each character.
Here's the implementation:
```python
def count_character_frequency(input_string):
frequency = {}
for char in input_string:... | 2,477 | [
{
"from": "human",
"value": "Write a python function to count the frequency of each character in a given string."
},
{
"from": "gpt",
"value": "Certainly! You can use the following Python function to count the frequency of each character in a given string. This function uses a dictionary to stor... |
Write a function to count the frequency of each character in a given string and return the result as a dictionary. | Here is the code to solve this problem:
```python
def count_characters(s):
freq = {}
for char in s:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
return freq
``` | [
"assert count_characters(\"programming\") == {'p': 1, 'r': 2, 'o': 1, 'g': 2, 'a': 1, 'm': 2, 'i': 1, 'n': 1}",
"assert count_characters(\"hello\") == {'h': 1, 'e': 1, 'l': 2, 'o': 1}",
"assert count_characters(\"python\") == {'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1}"
] | You can create a function in Python to count the frequency of each character in a given string and return the result as a dictionary. Below is an example implementation:
```python
def char_frequency(s):
frequency = {}
for char in s:
if char in frequency:
frequency[char] += 1
else:
... | 2,478 | [
{
"from": "human",
"value": "Write a function to count the frequency of each character in a given string and return the result as a dictionary."
},
{
"from": "gpt",
"value": "You can create a function in Python to count the frequency of each character in a given string and return the result as a... |
Write a python function to find the longest subsequence of consecutive characters in a given string. | Here is the code to solve this problem:
```python
def longest_consecutive_subsequence(s):
if not s:
return 0
max_len = 1
current_len = 1
for i in range(1, len(s)):
if s[i] == s[i-1]:
current_len += 1
max_len = max(max_len, current_len)
else:
c... | [
"assert longest_consecutive_subsequence(\"aabbcc\") == 2",
"assert longest_consecutive_subsequence(\"aabbbcc\") == 3",
"assert longest_consecutive_subsequence(\"abcabcabc\") == 1"
] | You can find the longest subsequence of consecutive characters in a given string by iterating through the string and checking for consecutive characters. Here's a Python function that implements this logic:
```python
def longest_consecutive_subsequence(s):
if not s:
return ""
max_length = 1
curren... | 2,479 | [
{
"from": "human",
"value": "Write a python function to find the longest subsequence of consecutive characters in a given string."
},
{
"from": "gpt",
"value": "You can find the longest subsequence of consecutive characters in a given string by iterating through the string and checking for conse... |
Write a python function to find the next prime number after a given number. | Here is the code to solve this problem:
```python
def next_prime(num):
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + ... | [
"assert next_prime(10) == 11",
"assert next_prime(25) == 29",
"assert next_prime(1) == 2"
] | Certainly! You can determine the next prime number after a given number by implementing a function in Python that checks each subsequent number for primality until it finds the next prime. Below is an example of how you can do this:
```python
def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
... | 2,480 | [
{
"from": "human",
"value": "Write a python function to find the next prime number after a given number."
},
{
"from": "gpt",
"value": "Certainly! You can determine the next prime number after a given number by implementing a function in Python that checks each subsequent number for primality un... |
Write a function that takes a string and returns the number of alphabetic characters in it. | Here is the code to solve this problem:
```python
def count_alphabetic(s):
count = 0
for char in s:
if char.isalpha():
count += 1
return count
``` | [
"assert count_alphabetic(\"12345\") == 0",
"assert count_alphabetic(\"Hello, World!\") == 10",
"assert count_alphabetic(\"abc123\") == 3"
] | Here's a simple Python function that takes a string as input and returns the number of alphabetic characters in that string:
```python
def count_alphabetic_characters(s):
count = sum(c.isalpha() for c in s)
return count
# Example usage:
input_string = "Hello, World! 123"
result = count_alphabetic_characters(i... | 2,481 | [
{
"from": "human",
"value": "Write a function that takes a string and returns the number of alphabetic characters in it."
},
{
"from": "gpt",
"value": "Here's a simple Python function that takes a string as input and returns the number of alphabetic characters in that string:\n\n```python\ndef c... |
Write a function to find the longest subsequence of unique characters in a given string. | Here is the code to solve this problem:
```python
def longest_unique_sub(s):
max_len = 0
max_sub = ""
i = 0
j = 0
char_dict = {}
while j < len(s):
if s[j] in char_dict:
i = max(i, char_dict[s[j]]+1)
char_dict[s[j]] = j
if j-i+1 > max_len:
max_len ... | [
"assert longest_unique_sub(\"pwwkew\") == \"wke\"",
"assert longest_unique_sub(\"abcabcbb\") == \"abc\"",
"assert longest_unique_sub(\"bbbbb\") == \"b\""
] | You can find the longest subsequence of unique characters in a given string using a two-pointer approach or a dynamic programming approach. However, a simple and efficient way to solve this problem is by using a set to keep track of the unique characters as you traverse the string.
Here is a Python function that accom... | 2,482 | [
{
"from": "human",
"value": "Write a function to find the longest subsequence of unique characters in a given string."
},
{
"from": "gpt",
"value": "You can find the longest subsequence of unique characters in a given string using a two-pointer approach or a dynamic programming approach. However... |
Write a python function to check if a given string is a palindrome. | Here is the code to solve this problem:
```python
def palindrome(s) :
return s == s[::-1]
``` | [
"assert palindrome(\"racecar\") == True",
"assert palindrome(\"hello\") == False",
"assert palindrome(\"madam\") == True"
] | Certainly! A palindrome is a string that reads the same forwards and backwards. Here’s a simple Python function to check if a given string is a palindrome:
```python
def is_palindrome(s: str) -> bool:
# Normalize the string by converting it to lowercase and removing non-alphanumeric characters
normalized_str =... | 2,483 | [
{
"from": "human",
"value": "Write a python function to check if a given string is a palindrome."
},
{
"from": "gpt",
"value": "Certainly! A palindrome is a string that reads the same forwards and backwards. Here’s a simple Python function to check if a given string is a palindrome:\n\n```python... |
Write a function to reverse the order of words in a given sentence without changing the order of the characters within each word. | Here is the code to solve this problem:
```python
def reverse_sentence(sentence):
words = sentence.split(" ")
reversed_sentence = " ".join(words[::-1])
return reversed_sentence
``` | [
"assert reverse_sentence(\"I love coding in Python\") == \"Python in coding love I\"",
"assert reverse_sentence(\"Python is fun\") == \"fun is Python\"",
"assert reverse_sentence(\"Hello World\") == \"World Hello\""
] | You can reverse the order of words in a sentence by splitting the sentence into words, reversing the list of words, and then joining them back together. Below is a Python function that accomplishes this:
```python
def reverse_words(sentence):
# Split the sentence into words based on whitespace
words = sentence... | 2,484 | [
{
"from": "human",
"value": "Write a function to reverse the order of words in a given sentence without changing the order of the characters within each word."
},
{
"from": "gpt",
"value": "You can reverse the order of words in a sentence by splitting the sentence into words, reversing the list ... |
Write a function to convert a decimal number to a binary number. | Here is the code to solve this problem:
```python
def dec_to_bin(num):
if num == 0:
return "0"
binary = ""
while num > 0:
binary = str(num % 2) + binary
num = num // 2
return binary
``` | [
"assert dec_to_bin(0) == \"0\"",
"assert dec_to_bin(255) == \"11111111\"",
"assert dec_to_bin(10) == \"1010\""
] | Certainly! Below is a Python function that converts a decimal number to its binary equivalent using a straightforward approach.
```python
def decimal_to_binary(decimal_number):
if decimal_number < 0:
raise ValueError("The input must be a non-negative integer.")
if decimal_number == 0:
ret... | 2,485 | [
{
"from": "human",
"value": "Write a function to convert a decimal number to a binary number."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that converts a decimal number to its binary equivalent using a straightforward approach. \n\n```python\ndef decimal_to_binary(decima... |
Write a python function to check if a given string is an anagram of another string or not. | Here is the code to solve this problem:
```python
def is_Anagram(str1, str2):
if len(str1) != len(str2):
return False
str1 = sorted(str1)
str2 = sorted(str2)
for i in range(len(str1)):
if str1[i] != str2[i]:
return False
return True
``` | [
"assert is_Anagram(\"listen\", \"silent\") == True",
"assert is_Anagram(\"triangle\", \"integral\") == True",
"assert is_Anagram(\"hello\", \"world\") == False"
] | Certainly! To check if two strings are anagrams of each other, we can follow a simple approach:
1. First, we need to remove any spaces and convert both strings to lowercase (for case insensitivity).
2. Then, we can sort the characters in both strings and compare them.
Here’s a Python function that implements this log... | 2,486 | [
{
"from": "human",
"value": "Write a python function to check if a given string is an anagram of another string or not."
},
{
"from": "gpt",
"value": "Certainly! To check if two strings are anagrams of each other, we can follow a simple approach:\n\n1. First, we need to remove any spaces and con... |
Write a python function to find the longest palindrome that can be constructed with the letters of the given string. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward or backward (ignoring spaces, punctuation, and capitalization). | Here is the code to solve this problem:
```python
from collections import Counter
def longest_possible_palindrome(s):
c = Counter(s)
length = 0
odd_found = False
for val in c.values():
if val % 2 == 0:
length += val
else:
length += val - 1
odd_found... | [
"assert longest_possible_palindrome(\"abccccdd\") == 7",
"assert longest_possible_palindrome(\"a\") == 1",
"assert longest_possible_palindrome(\"bb\") == 2"
] | To find the longest palindrome that can be constructed from the letters of a given string, you can follow these steps:
1. Count the occurrences of each character in the string.
2. Use the counts to construct the palindrome.
3. If there are characters with an odd count, you can use one of them as the center of the pali... | 2,487 | [
{
"from": "human",
"value": "Write a python function to find the longest palindrome that can be constructed with the letters of the given string. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward or backward (ignoring spaces, punctuation, and capitalization)... |
Write a function to find the most common element in a list. If there is a tie for the most common element, return the one that appears first in the list. | Here is the code to solve this problem:
```python
def most_common_element(lst):
from collections import Counter
count = Counter(lst)
max_count = max(list(count.values()))
for num in lst:
if count[num] == max_count:
return num
``` | [
"assert most_common_element([1, 1, 2, 2, 3, 3]) == 1",
"assert most_common_element([1, 2, 2, 3, 3, 3]) == 3",
"assert most_common_element([5, 6, 7, 7, 5, 5]) == 5"
] | You can achieve this by using a Python function that counts the occurrences of each element in the list and keeps track of the first appearance of each element. Here's a simple implementation:
```python
def most_common_element(lst):
count_map = {}
max_count = 0
most_common = None
for index, element in... | 2,488 | [
{
"from": "human",
"value": "Write a function to find the most common element in a list. If there is a tie for the most common element, return the one that appears first in the list."
},
{
"from": "gpt",
"value": "You can achieve this by using a Python function that counts the occurrences of eac... |
Write a python function to find the longest substring without repeating characters in a given string. | Here is the code to solve this problem:
```python
def longest_unique_substring(s):
start = 0
max_length = 0
max_substring = ""
used_char = {}
for i in range(len(s)):
if s[i] in used_char and start <= used_char[s[i]]:
start = used_char[s[i]] + 1
else:
if i - ... | [
"assert longest_unique_substring(\"bbbbb\") == \"b\"",
"assert longest_unique_substring(\"pwwkew\") == \"wke\"",
"assert longest_unique_substring(\"abcabcbb\") == \"abc\""
] | Certainly! Here’s a Python function that finds the longest substring without repeating characters using a sliding window approach:
```python
def longest_substring_without_repeating(s: str) -> str:
char_index_map = {}
longest_start = 0
longest_length = 0
start = 0
for index, char in enumerate(s... | 2,489 | [
{
"from": "human",
"value": "Write a python function to find the longest substring without repeating characters in a given string."
},
{
"from": "gpt",
"value": "Certainly! Here’s a Python function that finds the longest substring without repeating characters using a sliding window approach:\n\n... |
Write a python function to find the maximum sum of non-adjacent elements in an array using dynamic programming. | Here is the code to solve this problem:
```python
def maxSumNonAdjacent(arr):
if len(arr) == 0:
return 0
elif len(arr) == 1:
return arr[0]
elif len(arr) == 2:
return max(arr[0], arr[1])
dp = [0] * len(arr)
dp[0] = arr[0]
dp[1] = max(arr[0], arr[1])
for i in range(2, ... | [
"assert maxSumNonAdjacent([3, 2, 5, 10, 7]) == 15",
"assert maxSumNonAdjacent([3, 2, 7, 10]) == 13",
"assert maxSumNonAdjacent([5, 5, 10, 100, 10, 5]) == 110"
] | Certainly! To solve the problem of finding the maximum sum of non-adjacent elements in an array using dynamic programming, we can use a bottom-up approach. The key idea is to maintain a running maximum sum that considers whether to include the current element or not.
Here is a Python function that implements this appr... | 2,490 | [
{
"from": "human",
"value": "Write a python function to find the maximum sum of non-adjacent elements in an array using dynamic programming."
},
{
"from": "gpt",
"value": "Certainly! To solve the problem of finding the maximum sum of non-adjacent elements in an array using dynamic programming, w... |
Write a function to calculate the number of unique paths in a grid from the top-left corner to the bottom-right corner, given that the robot can only move down or right at any point in time. The grid dimensions are given by m rows and n columns. | Here is the code to solve this problem:
```python
def unique_paths(m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if n == 1 or m == 1:
return 1
dp = [[1] * n for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i-1][j] + dp[i][j-... | [
"assert unique_paths(7, 3) == 28",
"assert unique_paths(3, 2) == 3",
"assert unique_paths(4, 4) == 20"
] | To calculate the number of unique paths from the top-left corner to the bottom-right corner of a grid with `m` rows and `n` columns, where the robot can only move either down or right, we can use a combinatorial approach.
The key observation is that any path from the top-left to the bottom-right in an `m x n` grid con... | 2,491 | [
{
"from": "human",
"value": "Write a function to calculate the number of unique paths in a grid from the top-left corner to the bottom-right corner, given that the robot can only move down or right at any point in time. The grid dimensions are given by m rows and n columns."
},
{
"from": "gpt",
... |
Write a python function to reverse the digits of a given number. | Here is the code to solve this problem:
```python
def reverse_digits(num):
rev = 0
while num > 0:
rev = (rev * 10) + num % 10
num = num // 10
return rev
``` | [
"assert reverse_digits(98765) == 56789",
"assert reverse_digits(100) == 1",
"assert reverse_digits(12345) == 54321"
] | You can reverse the digits of a number in Python by converting the number to a string, reversing the string, and then converting it back to an integer. Here's a function that does just that:
```python
def reverse_digits(n):
# Convert the number to a string and reverse it
reversed_str = str(n)[::-1]
# ... | 2,492 | [
{
"from": "human",
"value": "Write a python function to reverse the digits of a given number."
},
{
"from": "gpt",
"value": "You can reverse the digits of a number in Python by converting the number to a string, reversing the string, and then converting it back to an integer. Here's a function t... |
Write a function to rearrange a given list by moving all odd numbers to the end while maintaining the relative order of the even numbers. | Here is the code to solve this problem:
```python
def rearrange_list(A):
i = 0
odd = []
even = []
while i < len(A):
if A[i] % 2 == 0:
even.append(A[i])
else:
odd.append(A[i])
i += 1
return even + odd
``` | [
"assert rearrange_list([10, 11, 12, 13, 14, 15])==([10, 12, 14, 11, 13, 15])",
"assert rearrange_list([1, 2, 3, 4, 5])==([2, 4, 1, 3, 5])",
"assert rearrange_list([2, 3, 4, 5, 6, 7, 8])==([2, 4, 6, 8, 3, 5, 7])"
] | You can achieve this by iterating through the list and separating the even and odd numbers. Here’s a Python function that accomplishes this:
```python
def rearrange_odds_to_end(lst):
# Create a new list to hold even numbers
evens = []
# Create a new list to hold odd numbers
odds = []
# Iterate... | 2,493 | [
{
"from": "human",
"value": "Write a function to rearrange a given list by moving all odd numbers to the end while maintaining the relative order of the even numbers."
},
{
"from": "gpt",
"value": "You can achieve this by iterating through the list and separating the even and odd numbers. Here’s... |
Write a python function to find the longest consecutive elements sequence in a list of integers. Note that the sequence must be strictly increasing and consecutive. | Here is the code to solve this problem:
```python
def longest_consecutive_sequence(nums):
num_set = set(nums)
longest_sequence = []
for num in num_set:
if num - 1 not in num_set:
current_num = num
current_sequence = []
while current_num in num_set:
... | [
"assert longest_consecutive_sequence([100, 4, 200, 1, 3, 2]) == [1, 2, 3, 4]",
"assert longest_consecutive_sequence([1, 2, 0, 1]) == [0, 1, 2]",
"assert longest_consecutive_sequence([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]) == [0, 1, 2, 3, 4, 5, 6, 7, 8]"
] | To find the longest consecutive elements sequence in a list of integers, we can use a set for efficient look-ups and iterate through the unique elements in the list. Here's a Python function that accomplishes this with a time complexity of O(n):
```python
def longest_consecutive_sequence(nums):
if not nums:
... | 2,494 | [
{
"from": "human",
"value": "Write a python function to find the longest consecutive elements sequence in a list of integers. Note that the sequence must be strictly increasing and consecutive."
},
{
"from": "gpt",
"value": "To find the longest consecutive elements sequence in a list of integers... |
Write a function to find the mode of a list of numbers. The mode is the number that appears most frequently in a list. If there are multiple modes, return all of them in a list. | Here is the code to solve this problem:
```python
from collections import Counter
def find_mode(numbers):
count = Counter(numbers)
max_count = max(count.values())
return [num for num, freq in count.items() if freq == max_count]
``` | [
"assert find_mode([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]",
"assert find_mode([1, 2, 2, 3, 4, 4, 5]) == [2, 4]",
"assert find_mode([1, 1, 1, 2, 3, 4, 5]) == [1]"
] | Certainly! Here’s a Python function that finds the mode(s) of a list of numbers. The function utilizes the `collections.Counter` to count the occurrences of each number in the list, identifies the maximum frequency, and then collects all numbers that have this maximum frequency.
```python
from collections import Count... | 2,495 | [
{
"from": "human",
"value": "Write a function to find the mode of a list of numbers. The mode is the number that appears most frequently in a list. If there are multiple modes, return all of them in a list."
},
{
"from": "gpt",
"value": "Certainly! Here’s a Python function that finds the mode(s)... |
Write a function to convert a number from base 10 to a given base. | Here is the code to solve this problem:
```python
def convert_base(n, base):
new_num = ""
while n > 0:
new_num = str(n % base) + new_num
n = n // base
return new_num
``` | [
"assert convert_base(7, 2)==\"111\"",
"assert convert_base(8, 2)==\"1000\"",
"assert convert_base(8, 3)==\"22\""
] | Certainly! Below is a Python function that converts a number from base 10 to a specified base (from 2 to 36). This function handles numbers including those that require letters for bases higher than 10 (e.g., 'A' for 10, 'B' for 11, ..., 'Z' for 35).
```python
def convert_to_base(num, base):
if base < 2 or base > ... | 2,496 | [
{
"from": "human",
"value": "Write a function to convert a number from base 10 to a given base."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that converts a number from base 10 to a specified base (from 2 to 36). This function handles numbers including those that require ... |
Write a function to check if a given number is a perfect square. | Here is the code to solve this problem:
```python
import math
def check_perfect_square(n):
return math.isqrt(n)**2 == n
``` | [
"assert check_perfect_square(14) == False",
"assert check_perfect_square(16) == True",
"assert check_perfect_square(1) == True"
] | Certainly! A perfect square is an integer that is the square of another integer. For example, 1, 4, 9, 16, etc. are perfect squares because they can be expressed as \(1^2\), \(2^2\), \(3^2\), \(4^2\), respectively.
Here’s a function in Python that checks if a given number is a perfect square:
```python
def is_perfect... | 2,497 | [
{
"from": "human",
"value": "Write a function to check if a given number is a perfect square."
},
{
"from": "gpt",
"value": "Certainly! A perfect square is an integer that is the square of another integer. For example, 1, 4, 9, 16, etc. are perfect squares because they can be expressed as \\(1^2... |
Write a python function to find the number of unique substrings in a given string. A substring is a contiguous sequence of characters within a string. | Here is the code to solve this problem:
```python
def unique_substrings(s):
substrings = set()
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
substrings.add(s[i:j])
return len(substrings)
``` | [
"assert unique_substrings(\"abcd\") == 10",
"assert unique_substrings(\"aaa\") == 3",
"assert unique_substrings(\"abc\") == 6"
] | To find the number of unique substrings in a given string, you can use a method based on the Suffix Array and Longest Common Prefix (LCP) array. Here’s a Python function that implements this approach:
```python
def build_suffix_array(s):
n = len(s)
suffixes = sorted((s[i:], i) for i in range(n))
suffix_arr... | 2,498 | [
{
"from": "human",
"value": "Write a python function to find the number of unique substrings in a given string. A substring is a contiguous sequence of characters within a string."
},
{
"from": "gpt",
"value": "To find the number of unique substrings in a given string, you can use a method based... |
Write a python function to find the largest sum of non-adjacent elements in a list of numbers. | Here is the code to solve this problem:
```python
def largest_non_adjacent_sum(nums):
incl = 0
excl = 0
for i in nums:
new_excl = excl if excl > incl else incl
incl = excl + i
excl = new_excl
return max(excl, incl)
``` | [
"assert largest_non_adjacent_sum([5, 1, 1, 5]) == 10",
"assert largest_non_adjacent_sum([2, 4, 6, 2, 5]) == 13",
"assert largest_non_adjacent_sum([1, 2, 3, 4, 5, 6]) == 12"
] | You can solve the problem of finding the largest sum of non-adjacent elements in a list by using dynamic programming. The idea is to maintain two variables that keep track of the maximum sums including and excluding the current element.
Here's a Python function that implements this logic:
```python
def largest_non_ad... | 2,499 | [
{
"from": "human",
"value": "Write a python function to find the largest sum of non-adjacent elements in a list of numbers."
},
{
"from": "gpt",
"value": "You can solve the problem of finding the largest sum of non-adjacent elements in a list by using dynamic programming. The idea is to maintain... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.