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 kth smallest element in an unsorted list using the QuickSelect algorithm. | Here is the code to solve this problem:
```python
from typing import List
def quickSelect(arr: List[int], k: int) -> int:
if len(arr) == 1:
return arr[0]
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in ar... | [
"assert quickSelect([10, 4, 5, 8, 6, 11, 26], 3) == 6",
"assert quickSelect([7, 10, 4, 3, 20, 15], 3) == 7",
"assert quickSelect([1, 3, 2, 4], 2) == 2"
] | Sure! The QuickSelect algorithm is an efficient way to find the k-th smallest (or largest) element in an unsorted list. It is related to the QuickSort sorting algorithm and has an average time complexity of O(n).
Here’s a Python function that implements the QuickSelect algorithm to find the k-th smallest element in an... | 10,400 | [
{
"from": "human",
"value": "Write a function to find the kth smallest element in an unsorted list using the QuickSelect algorithm."
},
{
"from": "gpt",
"value": "Sure! The QuickSelect algorithm is an efficient way to find the k-th smallest (or largest) element in an unsorted list. It is related... |
Write a python function to find the largest substring without repeating characters in a given string. | Here is the code to solve this problem:
```python
def largest_substring_without_repeating_characters(s: str) -> int:
n = len(s)
if n <= 1:
return n
max_len = 0
start = 0
char_index = {}
for end in range(n):
if s[end] in char_index and char_index[s[end]] >= start:
s... | [
"assert largest_substring_without_repeating_characters(\"bbbbb\") == 1",
"assert largest_substring_without_repeating_characters(\"abcabcbb\") == 3",
"assert largest_substring_without_repeating_characters(\"pwwkew\") == 3"
] | Certainly! You can use a sliding window approach to find the largest substring without repeating characters efficiently. Here's a Python function that implements this algorithm:
```python
def largest_substring_without_repeating(s: str) -> str:
char_index_map = {}
start = 0
max_length = 0
longest_substr... | 10,401 | [
{
"from": "human",
"value": "Write a python function to find the largest substring without repeating characters in a given string."
},
{
"from": "gpt",
"value": "Certainly! You can use a sliding window approach to find the largest substring without repeating characters efficiently. Here's a Pyth... |
Write a python function to find the longest consecutive sequence in an integer array. | Here is the code to solve this problem:
```python
def find_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
while current_num... | [
"assert find_longest_consecutive_sequence([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]) == 9",
"assert find_longest_consecutive_sequence([10]) == 1",
"assert find_longest_consecutive_sequence([100, 4, 200, 1, 3, 2]) == 4"
] | Certainly! The problem of finding the longest consecutive sequence in an array of integers can be tackled efficiently using a set to achieve an average time complexity of O(n). Here’s a Python function that accomplishes this:
```python
def longest_consecutive(nums):
if not nums:
return 0
num_set =... | 10,402 | [
{
"from": "human",
"value": "Write a python function to find the longest consecutive sequence in an integer array."
},
{
"from": "gpt",
"value": "Certainly! The problem of finding the longest consecutive sequence in an array of integers can be tackled efficiently using a set to achieve an averag... |
Write a python function to find the last occurring prime number in the given list. | Here is the code to solve this problem:
```python
def find_Last_Prime(lst):
def isPrime(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 % ... | [
"assert find_Last_Prime([1,2,3,4,5,6,7,8,9,10,11]) == 11",
"assert find_Last_Prime([1,4,6,8,10]) == -1",
"assert find_Last_Prime([1,2,3,4,6,8,10,12]) == 3"
] | Certainly! Below is a Python function that takes a list of integers and returns the last occurring prime number in that list. If there are no prime numbers in the list, it returns `None`.
```python
def is_prime(n):
"""Helper function to check if a number is prime."""
if n <= 1:
return False
for i i... | 10,403 | [
{
"from": "human",
"value": "Write a python function to find the last occurring prime number in the given list."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that takes a list of integers and returns the last occurring prime number in that list. If there are no prime numbe... |
Write a python function that takes a list of strings and returns a list of the lengths of the corresponding strings. Do this without using the built-in length function. | Here is the code to solve this problem:
```python
def length_of_strings(lst):
lengths = []
for string in lst:
count = 0
for char in string:
count += 1
lengths.append(count)
return lengths
``` | [
"assert length_of_strings([\"\", \"abc\", \"defg\"]) == [0, 3, 4]",
"assert length_of_strings([\"python\"]) == [6]",
"assert length_of_strings([\"hello\", \"world\", \"!\"]) == [5, 5, 1]"
] | Certainly! You can create a Python function that calculates the length of each string in the list without using the built-in `len` function by iterating through each string character by character. Here’s a sample implementation:
```python
def custom_length(s):
count = 0
for char in s:
count += 1
re... | 10,404 | [
{
"from": "human",
"value": "Write a python function that takes a list of strings and returns a list of the lengths of the corresponding strings. Do this without using the built-in length function."
},
{
"from": "gpt",
"value": "Certainly! You can create a Python function that calculates the len... |
Write a function to check if a given list is a valid valley array. A valid valley array is a list which starts with an increasing sequence, reaches a peak, and then decreases until the end. The peak should not be the first or last element in the list. | Here is the code to solve this problem:
```python
def is_valid_valley(arr):
if len(arr) < 3 or arr[0] >= arr[1] or arr[-2] <= arr[-1]:
return False
left = 0
while left < len(arr) - 1 and arr[left] < arr[left + 1]:
left += 1
if left == 0 or left == len(arr) - 1:
return False
... | [
"assert is_valid_valley([1, 3, 2]) == True",
"assert is_valid_valley([2, 1, 3, 4]) == False",
"assert is_valid_valley([1, 2, 3, 2, 1]) == True",
"assert is_valid_valley([1, 2, 3, 4, 5]) == False"
] | To determine if a given list is a valid valley array, we need to implement the following checks:
1. The list should contain at least 3 elements, because a valley can only exist with at least three points.
2. The sequence must start with a strictly increasing segment.
3. After reaching a peak, which cannot be the first... | 10,405 | [
{
"from": "human",
"value": "Write a function to check if a given list is a valid valley array. A valid valley array is a list which starts with an increasing sequence, reaches a peak, and then decreases until the end. The peak should not be the first or last element in the list."
},
{
"from": "gpt"... |
Write a python function to find the number of valid parentheses strings of a given length. A valid parentheses string is either an empty string, "(", followed by a valid parentheses string, followed by ")", or two valid parentheses strings concatenated together. | Here is the code to solve this problem:
```python
def num_Parentheses(n):
dp = [0] * (n + 1)
dp[0] = 1
for i in range(1, n + 1):
for j in range(0, i, 2):
dp[i] += dp[j] * ((dp[i - 2 - j] if i >= 2 + j else 0) + (1 if i - 1 - j == 0 else 0))
return dp[n]
``` | [
"assert num_Parentheses(0) == 1",
"assert num_Parentheses(2) == 1",
"assert num_Parentheses(4) == 2",
"assert num_Parentheses(6) == 5"
] | To compute the number of valid parentheses strings of a given length, we can use dynamic programming or apply the combinatorial method involving Catalan numbers. Let's write a function that leverages the properties of Catalan numbers.
The nth Catalan number can represent the number of valid parentheses strings made up... | 10,406 | [
{
"from": "human",
"value": "Write a python function to find the number of valid parentheses strings of a given length. A valid parentheses string is either an empty string, \"(\", followed by a valid parentheses string, followed by \")\", or two valid parentheses strings concatenated together."
},
{
... |
Write a function that calculates the number of days between two dates. | Here is the code to solve this problem:
```python
from datetime import datetime
def calculate_days(date1, date2):
date_format = "%Y-%m-%d"
a = datetime.strptime(date1, date_format)
b = datetime.strptime(date2, date_format)
delta = b - a
return abs(delta.days)
``` | [
"assert calculate_days(\"2022-03-01\", \"2022-03-01\") == 0",
"assert calculate_days(\"2022-01-01\", \"2022-01-10\") == 9",
"assert calculate_days(\"2022-02-01\", \"2022-02-28\") == 27"
] | Certainly! Below is an example of a Python function that calculates the number of days between two given dates. The function uses Python's built-in `datetime` module to handle date manipulations.
```python
from datetime import datetime
def days_between_dates(date1, date2):
"""
Calculate the number of days bet... | 10,407 | [
{
"from": "human",
"value": "Write a function that calculates the number of days between two dates."
},
{
"from": "gpt",
"value": "Certainly! Below is an example of a Python function that calculates the number of days between two given dates. The function uses Python's built-in `datetime` module... |
Write a python function to find the largest number in a list that is divisible by 3. | Here is the code to solve this problem:
```python
def find_largest_divisible_by_three(lst):
max_num = None
for num in lst:
if num % 3 == 0 and (max_num is None or num > max_num):
max_num = num
return max_num
``` | [
"assert find_largest_divisible_by_three([6, 5, 12, 9, 3]) == 12",
"assert find_largest_divisible_by_three([9, 11, 15, 18, 21]) == 21",
"assert find_largest_divisible_by_three([4, 7, 13, 16, 19]) == None"
] | You can create a function to find the largest number in a list that is divisible by 3 like this:
```python
def largest_divisible_by_3(numbers):
# Filter the list to only include numbers divisible by 3
divisible_by_3 = [num for num in numbers if num % 3 == 0]
# Return the largest number found, or None ... | 10,408 | [
{
"from": "human",
"value": "Write a python function to find the largest number in a list that is divisible by 3."
},
{
"from": "gpt",
"value": "You can create a function to find the largest number in a list that is divisible by 3 like this:\n\n```python\ndef largest_divisible_by_3(numbers):\n ... |
Write a function to determine if a phone number is unique in a phone book. A phone number is considered unique if no other number in the phone book is a prefix of it. | Here is the code to solve this problem:
```python
def is_unique_phone_number(phone_book):
phone_book.sort()
for i in range(len(phone_book)-1):
if phone_book[i] == phone_book[i+1][:len(phone_book[i])]:
return False
return True
``` | [
"assert is_unique_phone_number([\"123\", \"456\", \"789\"]) == True",
"assert is_unique_phone_number([\"12345\", \"1234\", \"123456\"]) == False",
"assert is_unique_phone_number([\"97674223\", \"1195524421\",\"119\"]) == False"
] | To determine if a phone number is unique in a phone book based on the prefix rule, you can implement a function that checks each phone number in the list to see if it is a prefix of any other number. If any number is found that is a prefix of the given number, then the phone number is not unique.
Here’s how you can im... | 10,409 | [
{
"from": "human",
"value": "Write a function to determine if a phone number is unique in a phone book. A phone number is considered unique if no other number in the phone book is a prefix of it."
},
{
"from": "gpt",
"value": "To determine if a phone number is unique in a phone book based on the... |
Write a function that determines if a list of words is sorted according to a given alien dictionary order. | Here is the code to solve this problem:
```python
from typing import List
def isAlienSorted(words: List[str], order: str) -> bool:
index = {char: i for i, char in enumerate(order)}
for i in range(len(words) - 1):
word1, word2 = words[i], words[i + 1]
for j in range(min(len(word1), len(word2)))... | [
"assert isAlienSorted([\"hello\", \"leetcode\"], \"hlabcdefgijkmnopqrstuvwxyz\") == True",
"assert isAlienSorted([\"word\", \"world\", \"row\"], \"worldabcefghijkmnpqstuvxyz\") == False",
"assert isAlienSorted([\"apple\", \"app\"], \"abcdefghijklmnopqrstuvwxyz\") == False"
] | Sure! To determine if a list of words is sorted according to a given alien dictionary order, you can create a function that maps each character of the alien alphabet to its corresponding index, and then compares each pair of adjacent words based on this order.
Here is a Python function that accomplishes this:
```pyth... | 10,410 | [
{
"from": "human",
"value": "Write a function that determines if a list of words is sorted according to a given alien dictionary order."
},
{
"from": "gpt",
"value": "Sure! To determine if a list of words is sorted according to a given alien dictionary order, you can create a function that maps ... |
Write a function that takes a string as input and returns a new string that is a palindrome. The new string should be formed by appending the minimum number of characters to the end of the input string. | Here is the code to solve this problem:
```python
def create_minimal_palindrome(word):
if word == word[::-1]:
return word
else:
for i in range(len(word)):
new_word = word + word[:i][::-1]
if new_word == new_word[::-1]:
return new_word
``` | [
"assert create_minimal_palindrome(\"cat\") == \"catac\"",
"assert create_minimal_palindrome(\"race\") == \"racecar\"",
"assert create_minimal_palindrome(\"cata\") == \"catac\""
] | To create a function that transforms a given string into a palindrome by appending the minimum number of characters, we can follow a systematic approach. The idea is to find the longest suffix of the string that is also a prefix of the string when read in reverse (because a palindrome reads the same forwards and backwa... | 10,411 | [
{
"from": "human",
"value": "Write a function that takes a string as input and returns a new string that is a palindrome. The new string should be formed by appending the minimum number of characters to the end of the input string."
},
{
"from": "gpt",
"value": "To create a function that transfo... |
Write a python function to find the longest substring with at least k repeating characters in a given string. If no such substring exists, return 0.
**Example:**
```
assert longest_substring_k_repeating("aaabb", 3) == 3
assert longest_substring_k_repeating("ababbc", 2) == 5
assert longest_substring_k_repeating("a", 1)... | Here is the code to solve this problem:
```python
from collections import Counter
def longest_substring_k_repeating(s, k):
"""
Finds the longest substring with at least k repeating characters.
:param s: Input string
:param k: Minimum number of repetitions for a character to be considered
:ret... | [
"assert longest_substring_k_repeating(\"a\", 1) == 1",
"assert longest_substring_k_repeating(\"ababbc\", 2) == 5",
"assert longest_substring_k_repeating(\"aaabb\", 3) == 3"
] | Certainly! To find the longest substring with at least `k` repeating characters in a given string, we can use a sliding window approach combined with a frequency count of characters within the window.
Below is the implementation of the function `longest_substring_k_repeating`:
```python
def longest_substring_k_repeat... | 10,412 | [
{
"from": "human",
"value": "Write a python function to find the longest substring with at least k repeating characters in a given string. If no such substring exists, return 0.\n\n**Example:**\n```\nassert longest_substring_k_repeating(\"aaabb\", 3) == 3\nassert longest_substring_k_repeating(\"ababbc\", 2)... |
Write a function named "find_odd_occurrences" that takes a list of integers as input and returns the integer that appears an odd number of times. There will always be only one integer that appears an odd number of times in the list. | Here is the code to solve this problem:
```python
def find_odd_occurrences(arr):
counts = {}
for num in arr:
if num in counts:
counts[num] += 1
else:
counts[num] = 1
for num, count in counts.items():
if count % 2 == 1:
return num
``` | [
"assert find_odd_occurrences([20, 1, 1, 2, 2]) == 20",
"assert find_odd_occurrences([10, 3, 10, 3, 3]) == 3",
"assert find_odd_occurrences([5, 7, 2, 7, 5, 2, 5]) == 5"
] | Certainly! Below is a Python function named `find_odd_occurrences` that takes a list of integers as input and returns the integer that appears an odd number of times.
```python
def find_odd_occurrences(numbers):
# Initialize a dictionary to count occurrences
count_dict = {}
# Count occurrences of each... | 10,413 | [
{
"from": "human",
"value": "Write a function named \"find_odd_occurrences\" that takes a list of integers as input and returns the integer that appears an odd number of times. There will always be only one integer that appears an odd number of times in the list."
},
{
"from": "gpt",
"value": "C... |
Write a function to check if a string is a palindrome using a stack. A palindrome is a word, phrase, number, or other sequences of characters that reads the same backward or forward. | Here is the code to solve this problem:
```python
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return not bool(self.items)
def push(self, data):
self.items.append(data)
def pop(self):
return self.items.pop()
def peek(self):
return ... | [
"assert is_palindrome_stack(\"hello\") == False",
"assert is_palindrome_stack(\"madam\") == True",
"assert is_palindrome_stack(\"racecar\") == True"
] | To check if a string is a palindrome using a stack, we can follow these steps:
1. Normalize the string (remove any non-alphanumeric characters and convert it to the same case).
2. Use a stack to push each character of the normalized string.
3. Then, pop characters from the stack and compare them with the original norm... | 10,414 | [
{
"from": "human",
"value": "Write a function to check if a string is a palindrome using a stack. A palindrome is a word, phrase, number, or other sequences of characters that reads the same backward or forward."
},
{
"from": "gpt",
"value": "To check if a string is a palindrome using a stack, w... |
Write a function to count the number of even and odd numbers in a given list. | Here is the code to solve this problem:
```python
def count_even_odd(nums):
even_count = 0
odd_count = 0
for num in nums:
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
return even_count, odd_count
``` | [
"assert count_even_odd([10, 20, 30, 40, 50]) == (5, 0)",
"assert count_even_odd([11, 21, 31, 41, 51]) == (0, 5)",
"assert count_even_odd([1, 2, 3, 4, 5]) == (2, 3)"
] | Certainly! Below is a Python function that counts the number of even and odd numbers in a given list. The function takes a list of integers as input and returns a tuple with the counts of even and odd numbers.
```python
def count_even_odd(numbers):
even_count = 0
odd_count = 0
for number in numbers:
... | 10,415 | [
{
"from": "human",
"value": "Write a function to count the number of even and odd numbers in a given list."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that counts the number of even and odd numbers in a given list. The function takes a list of integers as input and retur... |
Write a function to find the largest difference between two numbers in a given list, where the larger number comes after the smaller number. | Here is the code to solve this problem:
```python
def largest_difference(nums):
max_diff = 0
min_num = nums[0]
for num in nums[1:]:
if num - min_num > max_diff:
max_diff = num - min_num
if num < min_num:
min_num = num
return max_diff
``` | [
"assert largest_difference([10, 7, 5, 8, 11, 9])==6",
"assert largest_difference([2, 3, 10, 6, 4, 8, 1])==8",
"assert largest_difference([7, 9, 5, 6, 3, 2])==2"
] | To find the largest difference between two numbers in a given list, where the larger number comes after the smaller number, you can implement the following function in Python:
```python
def max_difference(arr):
if len(arr) < 2:
return 0 # Not enough elements to find a difference
min_value = arr[0] #... | 10,416 | [
{
"from": "human",
"value": "Write a function to find the largest difference between two numbers in a given list, where the larger number comes after the smaller number."
},
{
"from": "gpt",
"value": "To find the largest difference between two numbers in a given list, where the larger number com... |
Write a function to merge two sorted arrays into a single sorted array. | Here is the code to solve this problem:
```python
def merge_sorted_arrays(arr1, arr2):
# Initialize an empty list to store the merged sorted array
merged_array = []
# Initialize two pointers to traverse the arrays
i, j = 0, 0
# Traverse both arrays
while i < len(arr1) and j < len(arr2):
... | [
"assert merge_sorted_arrays([1, 3, 5, 7], [2, 4, 6, 8]) == [1, 2, 3, 4, 5, 6, 7, 8]",
"assert merge_sorted_arrays([1, 3, 5, 7], [2, 4, 6]) == [1, 2, 3, 4, 5, 6, 7]",
"assert merge_sorted_arrays([1, 2, 3, 4], [1, 2, 3, 4]) == [1, 1, 2, 2, 3, 3, 4, 4]"
] | Certainly! Here is a Python function that merges two sorted arrays into a single sorted array:
```python
def merge_sorted_arrays(arr1, arr2):
# Initialize pointers for arr1 and arr2
i, j = 0, 0
merged_array = []
# Iterate through both arrays until we reach the end of one of them
while i < len(arr1... | 10,417 | [
{
"from": "human",
"value": "Write a function to merge two sorted arrays into a single sorted array."
},
{
"from": "gpt",
"value": "Certainly! Here is a Python function that merges two sorted arrays into a single sorted array:\n\n```python\ndef merge_sorted_arrays(arr1, arr2):\n # Initialize ... |
Write a function to convert a given string into a list of words. The function should split the string based on spaces, commas, or periods, and ignore any empty strings that result from the split. | Here is the code to solve this problem:
```python
import re
def string_to_list(s):
return [word for word in re.split("[ ,.]+", s) if word]
``` | [
"assert string_to_list(\"No, separators,here.\") == ['No', 'separators', 'here']",
"assert string_to_list(\"Hello, world. This is a test\") == ['Hello', 'world', 'This', 'is', 'a', 'test']",
"assert string_to_list(\"One,two,three. ,five\") == ['One', 'two', 'three', 'five']"
] | You can create a Python function to convert a given string into a list of words by using the `re` module, which provides support for regular expressions. This allows you to easily split the string based on multiple delimiters (like spaces, commas, and periods) and ignore any empty strings that result from the split.
H... | 10,418 | [
{
"from": "human",
"value": "Write a function to convert a given string into a list of words. The function should split the string based on spaces, commas, or periods, and ignore any empty strings that result from the split."
},
{
"from": "gpt",
"value": "You can create a Python function to conv... |
Write a python function to find the largest subarray with equal number of 0's and 1's in a binary array. | Here is the code to solve this problem:
```python
def largest_Subarray_Equal_0_1(arr,n):
curr_sum = 0
max_len = 0
sum_dict = {}
for i in range(0,n):
if (arr[i] == 0):
curr_sum -= 1
else:
curr_sum += 1
if (curr_sum == 0):
max_len = i + 1
... | [
"assert largest_Subarray_Equal_0_1([0, 0, 1, 0, 1, 0, 0, 1],8) == 6",
"assert largest_Subarray_Equal_0_1([0, 1],2) == 2",
"assert largest_Subarray_Equal_0_1([0, 0, 1, 1, 0],5) == 4"
] | You can solve the problem of finding the largest subarray with an equal number of 0's and 1's in a binary array by using a hashmap (dictionary) to track the cumulative sum of the elements, treating 0's as -1's. Here's how you can implement this in Python:
```python
def findLargestSubarrayWithEqual0sAnd1s(arr):
# C... | 10,419 | [
{
"from": "human",
"value": "Write a python function to find the largest subarray with equal number of 0's and 1's in a binary array."
},
{
"from": "gpt",
"value": "You can solve the problem of finding the largest subarray with an equal number of 0's and 1's in a binary array by using a hashmap ... |
Write a function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one). All inputs will be valid IPv4 addresses in the form of strings. The last address will always be greater than the first one. | Here is the code to solve this problem:
```python
def ips_between(start, end) -> int:
start_bits = start.split(".")
start_bits = list(map(lambda x: int(x), start_bits))
end_bits = end.split(".")
end_bits = list(map(lambda x: int(x), end_bits))
multiply = 0
for i in range(len(start_bits)):
... | [
"assert ips_between(\"10.0.0.0\", \"10.0.0.50\") == 50",
"assert ips_between(\"10.0.0.0\", \"10.0.1.0\") == 256",
"assert ips_between(\"20.0.0.10\", \"20.0.1.0\") == 246"
] | Certainly! To solve this problem, we can break down the steps needed to calculate the number of IP addresses between two given IPv4 addresses (including the first address but excluding the last).
Here's a Python function that accomplishes this:
```python
def ip_to_int(ip):
"""
Convert an IPv4 address from str... | 10,420 | [
{
"from": "human",
"value": "Write a function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one). All inputs will be valid IPv4 addresses in the form of strings. The last address will always be greater than the first one."
}... |
Write a python function to find the largest element in a list that is divisible by a specified divisor. | Here is the code to solve this problem:
```python
def find_largest_divisible(numbers, divisor):
result = -1
for num in numbers:
if num % divisor == 0 and num > result:
result = num
return result
``` | [
"assert find_largest_divisible([3, 6, 9, 12], 5) == -1",
"assert find_largest_divisible([7, 14, 21, 28], 7) == 28",
"assert find_largest_divisible([24, 36, 12, 48], 12) == 48"
] | Certainly! Below is a Python function that takes a list of numbers and a divisor as inputs, and returns the largest element from the list that is divisible by the given divisor. If no such element exists, it returns `None`.
```python
def largest_divisible(numbers, divisor):
"""
Find the largest element in the ... | 10,421 | [
{
"from": "human",
"value": "Write a python function to find the largest element in a list that is divisible by a specified divisor."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that takes a list of numbers and a divisor as inputs, and returns the largest element from the... |
Write a python function to count the occurrences of a specific word in a list of sentences. The function should be case-insensitive. | Here is the code to solve this problem:
```python
def count_word_occurrence(sentences, word):
count = 0
for sentence in sentences:
if sentence.lower().count(word.lower()) > 0:
count += sentence.lower().count(word.lower())
return count
``` | [
"assert count_word_occurrence([\"The quick brown fox\", \"The quick fox\", \"The lazy dog\"], \"the\") == 3",
"assert count_word_occurrence([\"Hello world\", \"hello everyone\", \"hello\"], \"hello\") == 3",
"assert count_word_occurrence([\"Coding is fun\", \"coding is challenging\", \"coding\"], \"coding\") ==... | Certainly! Below is a Python function that counts the occurrences of a specific word in a list of sentences. The function converts the sentences and the word to lowercase to ensure that the counting is case-insensitive.
```python
def count_word_occurrences(sentences, word):
"""
Count the occurrences of a speci... | 10,422 | [
{
"from": "human",
"value": "Write a python function to count the occurrences of a specific word in a list of sentences. The function should be case-insensitive."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that counts the occurrences of a specific word in a list of sente... |
Write a python function to check for the existence of any consecutive duplicate elements in a list. | Here is the code to solve this problem:
```python
def has_consecutive_duplicates(lst):
for i in range(1, len(lst)):
if lst[i] == lst[i-1]:
return True
return False
``` | [
"assert has_consecutive_duplicates([1,2,2,3,4,5,6,7]) == True",
"assert has_consecutive_duplicates([1,2,3,4,5,6,7,7,8]) == True",
"assert has_consecutive_duplicates([1,2,3,4,5,6,7]) == False",
"assert has_consecutive_duplicates([1,2,3,4,5,6,7,7]) == True",
"assert has_consecutive_duplicates([1,1,2,3,4,5,6,7... | Certainly! You can create a Python function to check for consecutive duplicate elements in a list by iterating through the list and comparing each element with the next one. Here's one way to implement this:
```python
def has_consecutive_duplicates(input_list):
# Iterate over the list, comparing each element to th... | 10,423 | [
{
"from": "human",
"value": "Write a python function to check for the existence of any consecutive duplicate elements in a list."
},
{
"from": "gpt",
"value": "Certainly! You can create a Python function to check for consecutive duplicate elements in a list by iterating through the list and comp... |
Write a python function to find the missing number in a given list of numbers ranging from 0 to n. The list contains n distinct numbers taken from 0, 1, 2, ..., n. | Here is the code to solve this problem:
```python
def missing_num(nums):
n = len(nums)
total = n * (n + 1) // 2
sum_of_nums = sum(nums)
return total - sum_of_nums
``` | [
"assert missing_num([3, 0, 1]) == 2",
"assert missing_num([9, 6, 4, 2, 3, 5, 7, 0, 1]) == 8",
"assert missing_num([0, 1]) == 2"
] | To find the missing number in a list of distinct numbers ranging from `0` to `n`, you can use the mathematical approach of summing the first `n` natural numbers and then subtracting the sum of the numbers in the list from it.
Here’s a Python function that implements this logic:
```python
def find_missing_number(nums)... | 10,424 | [
{
"from": "human",
"value": "Write a python function to find the missing number in a given list of numbers ranging from 0 to n. The list contains n distinct numbers taken from 0, 1, 2, ..., n."
},
{
"from": "gpt",
"value": "To find the missing number in a list of distinct numbers ranging from `0... |
Write a function to find the intersection of two lists. | Here is the code to solve this problem:
```python
def intersect_list(list1,list2):
result = list(set(list1) & set(list2))
return result
``` | [
"assert intersect_list([1, 2, 3, 4, 5],[4,5,6,7,8])==[4,5]",
"assert intersect_list([10,20,30,40],[40,50,60,70])==[40]",
"assert intersect_list([1,2,3],[4,5,6])==[]"
] | You can find the intersection of two lists in Python using a variety of methods. One common way is to use set operations for efficiency. Here's a simple function that achieves this:
```python
def intersection(list1, list2):
# Convert lists to sets to find the intersection
set1 = set(list1)
set2 = set(list2... | 10,425 | [
{
"from": "human",
"value": "Write a function to find the intersection of two lists."
},
{
"from": "gpt",
"value": "You can find the intersection of two lists in Python using a variety of methods. One common way is to use set operations for efficiency. Here's a simple function that achieves this... |
Write a python function to find the longest consecutive sequence in an array of integers. | Here is the code to solve this problem:
```python
def find_longest_consecutive(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
while current_num + 1 in n... | [
"assert find_longest_consecutive([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]) == 9",
"assert find_longest_consecutive([10, 5, 12]) == 1",
"assert find_longest_consecutive([100, 4, 200, 1, 3, 2]) == 4"
] | You can find the longest consecutive sequence in an array of integers by utilizing a set for efficient lookup. Here's a Python function that does just that:
```python
def longest_consecutive_sequence(nums):
if not nums:
return 0
num_set = set(nums)
longest_streak = 0
for num in num_se... | 10,426 | [
{
"from": "human",
"value": "Write a python function to find the longest consecutive sequence in an array of integers."
},
{
"from": "gpt",
"value": "You can find the longest consecutive sequence in an array of integers by utilizing a set for efficient lookup. Here's a Python function that does ... |
Write a python function to find the maximum number of points on the same line from a list of points in a 2D plane. Each point is represented as a list of [x, y] coordinates. | Here is the code to solve this problem:
```python
from collections import defaultdict
from math import gcd
def max_points(points):
if len(points)<=1:
return len(points)
points.sort(key=lambda x: x[0])
equations = defaultdict(lambda:set())
for i in range(len(points)-1):
x1, y1 = p... | [
"assert max_points([[1,1],[2,2],[3,3]]) == 3",
"assert max_points([[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]) == 4",
"assert max_points([[0,0],[1,1],[0,0],[1,1]]) == 4"
] | To find the maximum number of points that lie on the same line in a 2D plane from a list of points, we can use a combination of slopes and hash maps. Here’s a step-by-step explanation followed by the code.
1. **Iterate through each point**: For each point, treat it as a starting point.
2. **Calculate the slope for all... | 10,427 | [
{
"from": "human",
"value": "Write a python function to find the maximum number of points on the same line from a list of points in a 2D plane. Each point is represented as a list of [x, y] coordinates."
},
{
"from": "gpt",
"value": "To find the maximum number of points that lie on the same line... |
Write a function to group the elements of a list based on the given dictionary's keys and values. | Here is the code to solve this problem:
```python
def group_elements(lst, dic):
result = {}
for elem in lst:
key = dic[elem]
if key in result:
result[key].append(elem)
else:
result[key] = [elem]
return result
``` | [
"assert group_elements(['a', 'b', 'c', 'd', 'e', 'f', 'g'], {'a': 1, 'b': 1, 'c': 2, 'd': 2, 'e': 3, 'f': 3, 'g': 4}) == {1: ['a', 'b'], 2: ['c', 'd'], 3: ['e', 'f'], 4: ['g']}",
"assert group_elements(['apple', 'banana', 'cherry', 'date', 'fig', 'grape'], {'apple': 'fruit', 'banana': 'fruit', 'cherry': 'fruit', ... | Sure! You can achieve this by writing a function that takes a list and a dictionary as input, where the dictionary's keys are the desired group identifiers and the values are the criteria based on which the elements should be grouped.
Here's a Python function that demonstrates how to group the elements of a list based... | 10,428 | [
{
"from": "human",
"value": "Write a function to group the elements of a list based on the given dictionary's keys and values."
},
{
"from": "gpt",
"value": "Sure! You can achieve this by writing a function that takes a list and a dictionary as input, where the dictionary's keys are the desired ... |
Write a function to find the number of contiguous subarrays whose product is less than a given threshold. | Here is the code to solve this problem:
```python
def num_subarrays_with_product_less_than_k(arr, k):
if k <= 1:
return 0
product = 1
result = 0
left = 0
for right in range(len(arr)):
product *= arr[right]
while product >= k:
product /= arr[left]
lef... | [
"assert num_subarrays_with_product_less_than_k([1, 2, 3], 6) == 4",
"assert num_subarrays_with_product_less_than_k([10, 5, 2, 6], 100) == 8",
"assert num_subarrays_with_product_less_than_k([1, 2, 3], 0) == 0"
] | To find the number of contiguous subarrays whose product is less than a given threshold, you can use a sliding window approach. This method is efficient and works in linear time, O(n), which is better than the naive O(n^2) method for this problem.
Here’s how the sliding window approach works:
1. Maintain a product th... | 10,429 | [
{
"from": "human",
"value": "Write a function to find the number of contiguous subarrays whose product is less than a given threshold."
},
{
"from": "gpt",
"value": "To find the number of contiguous subarrays whose product is less than a given threshold, you can use a sliding window approach. Th... |
Write a function to find the pair of numbers in a list that adds up to a given target sum. If there are multiple pairs, return the pair with the smallest product. If no such pair exists, return an empty list. | Here is the code to solve this problem:
```python
def find_pair_with_smallest_product(nums, target):
if not nums or nums[-1] + nums[-2] < target:
return []
low, high = 0, len(nums) - 1
min_product = float('inf')
result = []
while low < high:
cur_sum = nums[low] + nums[high]
... | [
"assert find_pair_with_smallest_product([10, 20, 30, 40, 50], 60) == [10, 50]",
"assert find_pair_with_smallest_product([1, 3, 5, 7, 9], 12) == [3, 9]",
"assert find_pair_with_smallest_product([1, 2, 3, 4, 5], 7) == [2, 5]",
"assert find_pair_with_smallest_product([1, 3, 5, 7, 9], 13) == []"
] | You can achieve this by writing a function that iterates over the list of numbers, checking each possible pair to see if they add up to the target sum. If multiple pairs meet the criteria, the function will return the pair with the smallest product. Below is a Python function that implements this logic:
```python
def ... | 10,430 | [
{
"from": "human",
"value": "Write a function to find the pair of numbers in a list that adds up to a given target sum. If there are multiple pairs, return the pair with the smallest product. If no such pair exists, return an empty list."
},
{
"from": "gpt",
"value": "You can achieve this by wri... |
Write a function to find the number of good pairs in an array. A pair (i, j) is called good if nums[i] == nums[j] and i < j. | Here is the code to solve this problem:
```python
def countGoodPairs(nums):
count = 0
seen = {}
for i in nums:
if i in seen:
count += seen[i]
seen[i] += 1
else:
seen[i] = 1
return count
``` | [
"assert countGoodPairs([1,2,3]) == 0",
"assert countGoodPairs([1,1,1,1]) == 6",
"assert countGoodPairs([1,2,3,1,1,3]) == 4"
] | To find the number of good pairs in an array where a pair (i, j) is considered good if `nums[i] == nums[j]` and `i < j`, you can use a dictionary to count the occurrences of each number as you iterate through the array. For each number, the potential good pairs can be calculated based on how many times that number has ... | 10,431 | [
{
"from": "human",
"value": "Write a function to find the number of good pairs in an array. A pair (i, j) is called good if nums[i] == nums[j] and i < j."
},
{
"from": "gpt",
"value": "To find the number of good pairs in an array where a pair (i, j) is considered good if `nums[i] == nums[j]` and... |
Write a function to find the median of two sorted arrays. | Here is the code to solve this problem:
```python
def median_of_two_sorted_arrays(nums1, nums2):
nums = sorted(nums1 + nums2)
length = len(nums)
if length % 2 == 0:
return (nums[length // 2] + nums[length // 2 - 1]) / 2
else:
return nums[length // 2]
``` | [
"assert median_of_two_sorted_arrays([1, 3], [2])==2.0",
"assert median_of_two_sorted_arrays([1, 2], [3, 4])==2.5",
"assert median_of_two_sorted_arrays([0, 0], [0, 0])==0.0"
] | To find the median of two sorted arrays, we can use a binary search approach to achieve a time complexity of O(log(min(n, m))), where n and m are the sizes of the two arrays. Here is a Python function that implements this algorithm:
```python
def findMedianSortedArrays(nums1, nums2):
# Make sure nums1 is the small... | 10,432 | [
{
"from": "human",
"value": "Write a function to find the median of two sorted arrays."
},
{
"from": "gpt",
"value": "To find the median of two sorted arrays, we can use a binary search approach to achieve a time complexity of O(log(min(n, m))), where n and m are the sizes of the two arrays. Her... |
Write a python function to check whether a given list of integers is a palindrome or not. | Here is the code to solve this problem:
```python
def is_list_palindrome(lst):
return lst == lst[::-1]
``` | [
"assert is_list_palindrome([1, 2, 3, 4, 5]) == False",
"assert is_list_palindrome([1, 1, 2, 1, 1]) == True",
"assert is_list_palindrome([1, 2, 3, 2, 1]) == True"
] | Certainly! A palindrome is a sequence that reads the same backward as forward. To check if a list of integers is a palindrome, you can compare the list with its reverse. Here’s a simple Python function to accomplish this:
```python
def is_palindrome(lst):
return lst == lst[::-1]
# Example usage:
numbers = [1, 2, ... | 10,433 | [
{
"from": "human",
"value": "Write a python function to check whether a given list of integers is a palindrome or not."
},
{
"from": "gpt",
"value": "Certainly! A palindrome is a sequence that reads the same backward as forward. To check if a list of integers is a palindrome, you can compare the... |
Write a Python function to find the most frequent words in a given list of words, returning a list of tuples where each tuple contains a word and its frequency. | Here is the code to solve this problem:
```python
from collections import Counter
def most_frequent_words(words):
word_counts = Counter(words)
return word_counts.most_common()
``` | [
"assert most_frequent_words([\"apple\", \"banana\", \"apple\", \"orange\", \"banana\", \"banana\"]) == [(\"banana\", 3), (\"apple\", 2), (\"orange\", 1)]",
"assert most_frequent_words([\"a\", \"b\", \"c\", \"a\", \"b\", \"a\"]) == [(\"a\", 3), (\"b\", 2), (\"c\", 1)]",
"assert most_frequent_words([\"hello\", \"... | You can create a Python function to find the most frequent words in a list by using the `collections.Counter` class, which makes it easy to count the occurrences of items in a list. The solution below sorts the words by their frequency in descending order and returns a list of tuples, where each tuple consists of a wor... | 10,434 | [
{
"from": "human",
"value": "Write a Python function to find the most frequent words in a given list of words, returning a list of tuples where each tuple contains a word and its frequency."
},
{
"from": "gpt",
"value": "You can create a Python function to find the most frequent words in a list ... |
Write a function to find all starting indices of substrings in a given string that is a concatenation of each word in a list exactly once and without any intervening characters. | Here is the code to solve this problem:
```python
from collections import Counter
def find_substring_indices(s, words):
if not words or not s:
return []
word_count = Counter(words)
word_length = len(words[0])
total_length = word_length * len(words)
result = []
for i in range(len(s) - ... | [
"assert find_substring_indices(\"barfoothefoobarman\", [\"foo\", \"bar\"]) == [0,9]",
"assert find_substring_indices(\"wordgoodgoodgoodbestword\", [\"word\",\"good\",\"best\",\"word\"]) == []",
"assert find_substring_indices(\"barfoofoobarthefoobarman\", [\"bar\",\"foo\",\"the\"]) == [6,9,12]"
] | To solve the problem of finding all starting indices of substrings in a given string that form a concatenation of each word in a list exactly once, we can use a sliding window approach. This is efficient and effective for this type of substring search problem.
Here's a Python function that implements this algorithm:
... | 10,435 | [
{
"from": "human",
"value": "Write a function to find all starting indices of substrings in a given string that is a concatenation of each word in a list exactly once and without any intervening characters."
},
{
"from": "gpt",
"value": "To solve the problem of finding all starting indices of su... |
Write a Python function to find the maximum difference between two consecutive elements in a list. If the list has less than two elements, the function should return None. | Here is the code to solve this problem:
```python
def max_consecutive_diff(lst):
if len(lst) < 2:
return None
max_diff = 0
for i in range(len(lst) - 1):
diff = abs(lst[i] - lst[i + 1])
if diff > max_diff:
max_diff = diff
return max_diff
``` | [
"assert max_consecutive_diff([5, 3, 1, 2, 5]) == 3",
"assert max_consecutive_diff([1]) == None",
"assert max_consecutive_diff([7, 7, 7]) == 0",
"assert max_consecutive_diff([1, 9, 2, -7, 10, 4]) == 17"
] | You can create a Python function to find the maximum difference between two consecutive elements in a list as follows:
```python
def max_consecutive_difference(lst):
# Check if the list has less than two elements
if len(lst) < 2:
return None
# Initialize the maximum difference
max_diff = f... | 10,436 | [
{
"from": "human",
"value": "Write a Python function to find the maximum difference between two consecutive elements in a list. If the list has less than two elements, the function should return None."
},
{
"from": "gpt",
"value": "You can create a Python function to find the maximum difference ... |
Write a python function to check if a given string is a valid ISBN-10 number. An ISBN-10 number is a 10 digit code which is used to uniquely identify books. The last digit is a check digit which can be a number from 0 to 10 (the letter 'X' is used for 10). The check digit is calculated using a weighted sum of the first... | Here is the code to solve this problem:
```python
def is_valid_isbn(isbn: str) -> bool:
if len(isbn) != 10:
return False
total = 0
for i in range(9):
if not isbn[i].isdigit():
return False
total += int(isbn[i]) * (i + 1)
last_digit = isbn[-1]
if last_digit.isdigi... | [
"assert is_valid_isbn(\"0306406153\") == False",
"assert is_valid_isbn(\"0760707652\") == False",
"assert is_valid_isbn(\"0306406152\") == True",
"assert is_valid_isbn(\"123456789X\") == True",
"assert is_valid_isbn(\"1234567890\") == False"
] | To check if a given string is a valid ISBN-10 number, we can follow these steps:
1. Ensure the string is exactly 10 characters long.
2. Check that the first 9 characters are digits (0-9).
3. Validate the last character, which can be a digit (0-9) or 'X'.
4. Calculate the check digit using the weighted sum of the first... | 10,437 | [
{
"from": "human",
"value": "Write a python function to check if a given string is a valid ISBN-10 number. An ISBN-10 number is a 10 digit code which is used to uniquely identify books. The last digit is a check digit which can be a number from 0 to 10 (the letter 'X' is used for 10). The check digit is cal... |
Write a Python function that prints the first n terms of the Fibonacci sequence. | Here is the code to solve this problem:
```python
def print_fibonacci(n):
fib_sequence = [0, 1]
while len(fib_sequence) < n:
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence[:n]
``` | [
"assert print_fibonacci(8) == [0, 1, 1, 2, 3, 5, 8, 13]",
"assert print_fibonacci(1) == [0]",
"assert print_fibonacci(5) == [0, 1, 1, 2, 3]"
] | Certainly! The Fibonacci sequence is a series of numbers where the next term is the sum of the previous two terms. The sequence typically starts with the numbers 0 and 1. Below is a Python function that prints the first `n` terms of the Fibonacci sequence:
```python
def print_fibonacci(n):
# Check if n is valid
... | 10,438 | [
{
"from": "human",
"value": "Write a Python function that prints the first n terms of the Fibonacci sequence."
},
{
"from": "gpt",
"value": "Certainly! The Fibonacci sequence is a series of numbers where the next term is the sum of the previous two terms. The sequence typically starts with the n... |
Write a function to find the third largest number in a list of integers. | Here is the code to solve this problem:
```python
def third_largest(nums):
if len(nums) < 3:
return None
unique_nums = list(set(nums))
if len(unique_nums) < 3:
return None
unique_nums.sort(reverse=True)
return unique_nums[2]
``` | [
"assert third_largest([1, 2, 3, 4, 5]) == 3",
"assert third_largest([5, 1, 2, 3, 4]) == 3",
"assert third_largest([-5, -1, -2, -3, -4]) == -3",
"assert third_largest([2, 2, 2]) == None",
"assert third_largest([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 8",
"assert third_largest([10, 9, 8, 8, 7]) == 8",
"assert ... | Certainly! Below is a Python function that takes a list of integers and returns the third largest number. If there are less than three unique numbers in the list, it will return `None`.
```python
def third_largest(nums):
# Convert the list to a set to remove duplicates
unique_nums = set(nums)
# Check ... | 10,439 | [
{
"from": "human",
"value": "Write a function to find the third largest number in a list of integers."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that takes a list of integers and returns the third largest number. If there are less than three unique numbers in the list, ... |
Write a function that takes a list of integers and returns all possible permutations of the list. However, the function should only return unique permutations, and it should not use any built-in library or method for generating permutations. | Here is the code to solve this problem:
```python
from typing import List
def permuteUnique(nums: List[int]) -> List[List[int]]:
def dfs(res, curr, nums, used):
if len(curr) == len(nums):
res.append(curr[:])
return
for i in range(len(nums)):
if used[i]:
... | [
"assert permuteUnique([1,2,3]) == [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]",
"assert permuteUnique([1,1,2]) == [[1,1,2], [1,2,1], [2,1,1]]",
"assert permuteUnique([1,2,2]) == [[1,2,2], [2,1,2], [2,2,1]]"
] | To create a function that returns all unique permutations of a list of integers without using any built-in libraries or methods, we can use a backtracking approach. The idea is to build the permutations step by step, while ensuring that we do not include duplicate permutations that arise from duplicate numbers in the i... | 10,440 | [
{
"from": "human",
"value": "Write a function that takes a list of integers and returns all possible permutations of the list. However, the function should only return unique permutations, and it should not use any built-in library or method for generating permutations."
},
{
"from": "gpt",
"val... |
Write a python function to find the middle element of a given list. If the list has an even number of elements, return the two middle elements. | Here is the code to solve this problem:
```python
def find_middle(lst):
middle = len(lst) // 2
if len(lst) % 2 == 0:
return lst[middle-1:middle+1]
else:
return [lst[middle]]
``` | [
"assert find_middle([1,2,3,4,5,6,7,8]) == [4,5]",
"assert find_middle([1,2,3,4,5]) == [3]",
"assert find_middle([1,2,3,4,5,6]) == [3,4]"
] | You can achieve this by defining a function that takes a list as an input and determines its length. Based on the length, it will either return the middle element or the two middle elements if the number of elements is even. Here’s how you can implement this in Python:
```python
def find_middle_elements(lst):
leng... | 10,441 | [
{
"from": "human",
"value": "Write a python function to find the middle element of a given list. If the list has an even number of elements, return the two middle elements."
},
{
"from": "gpt",
"value": "You can achieve this by defining a function that takes a list as an input and determines its... |
Write a function to find the median of two sorted arrays. | Here is the code to solve this problem:
```python
def median_two_sorted_arrays(A, B):
m, n = len(A), len(B)
if m > n:
A, B, m, n = B, A, n, m
imin, imax, half_len = 0, m, (m + n + 1) // 2
while imin <= imax:
i = (imin + imax) // 2
j = half_len - i
if i < m and B[j-1] > A... | [
"assert median_two_sorted_arrays([1, 2], [3, 4]) == 2.5",
"assert median_two_sorted_arrays([1, 3], [2, 7]) == 2.5",
"assert median_two_sorted_arrays([1, 3], [2]) == 2.0"
] | To find the median of two sorted arrays, you can use a binary search approach to achieve an efficient solution with a time complexity of \( O(\log(\min(n, m))) \), where \( n \) and \( m \) are the sizes of the two arrays. Below is a Python function that implements this method.
```python
def findMedianSortedArrays(num... | 10,442 | [
{
"from": "human",
"value": "Write a function to find the median of two sorted arrays."
},
{
"from": "gpt",
"value": "To find the median of two sorted arrays, you can use a binary search approach to achieve an efficient solution with a time complexity of \\( O(\\log(\\min(n, m))) \\), where \\( ... |
Write a function to find the distance between two points in a 3D space using the Euclidean distance formula. | Here is the code to solve this problem:
```python
import math
def euclidean_distance(point1, point2):
x1, y1, z1 = point1
x2, y2, z2 = point2
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2 - z1)**2)
return distance
``` | [
"assert euclidean_distance((1, 2, 3), (4, 5, 6)) == 5.196152422706632",
"assert euclidean_distance((0, 0, 0), (1, 1, 1)) == 1.7320508075688772",
"assert euclidean_distance((10, 10, 10), (10, 10, 10)) == 0.0"
] | You can use the following Python function to calculate the Euclidean distance between two points in a 3D space. Each point can be represented as a tuple (x, y, z).
Here's the function:
```python
import math
def euclidean_distance(point1, point2):
"""
Calculate the Euclidean distance between two points in 3D ... | 10,443 | [
{
"from": "human",
"value": "Write a function to find the distance between two points in a 3D space using the Euclidean distance formula."
},
{
"from": "gpt",
"value": "You can use the following Python function to calculate the Euclidean distance between two points in a 3D space. Each point can ... |
Write a python function to find the longest sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of a given positive integer. | Here is the code to solve this problem:
```python
def find_max_consecutive_zeros(N):
binary = bin(N)[2:]
max_gap = 0
current_gap = 0
found_one = False
for bit in binary:
if bit == '1':
if found_one and current_gap > max_gap:
max_gap = current_gap
curr... | [
"assert find_max_consecutive_zeros(9) == 2",
"assert find_max_consecutive_zeros(1041) == 5",
"assert find_max_consecutive_zeros(15) == 0"
] | Certainly! To find the longest sequence of consecutive zeros that is surrounded by ones in the binary representation of a given positive integer, you can follow these steps:
1. Convert the integer to its binary representation.
2. Split the binary string by the character '1'.
3. Find the lengths of the resultant segmen... | 10,444 | [
{
"from": "human",
"value": "Write a python function to find the longest sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of a given positive integer."
},
{
"from": "gpt",
"value": "Certainly! To find the longest sequence of consecutive zeros tha... |
Write a function that takes a list of numbers and returns the sum of the squares of all the even numbers in the list. | Here is the code to solve this problem:
```python
def sum_of_even_squares(lst):
return sum(i**2 for i in lst if i % 2 == 0)
``` | [
"assert sum_of_even_squares([2, 4, 6, 8])==120",
"assert sum_of_even_squares([1, 2, 3, 4, 5, 6])==56",
"assert sum_of_even_squares([1, 3, 5, 7])==0"
] | You can achieve this by writing a function in Python that filters out the even numbers from the list, squares them, and then computes the sum of these squares. Here is a simple implementation of such a function:
```python
def sum_of_squares_of_evens(numbers):
return sum(x ** 2 for x in numbers if x % 2 == 0)
# Ex... | 10,445 | [
{
"from": "human",
"value": "Write a function that takes a list of numbers and returns the sum of the squares of all the even numbers in the list."
},
{
"from": "gpt",
"value": "You can achieve this by writing a function in Python that filters out the even numbers from the list, squares them, an... |
Write a python function to find the length of the longest uncommon subsequence (LUS) of two strings. An uncommon subsequence is a subsequence of one of the strings that is not a subsequence of the other string. | Here is the code to solve this problem:
```python
def lus_length(str1, str2):
if str1 == str2:
return -1
return max(len(str1), len(str2))
``` | [
"assert lus_length(\"aba\", \"cdc\")==3",
"assert lus_length(\"aaa\", \"bbb\")==3",
"assert lus_length(\"aaa\", \"aaa\")==-1"
] | To find the length of the longest uncommon subsequence (LUS) between two strings, we can follow a straightforward approach:
1. If the two strings are equal, the longest uncommon subsequence does not exist, so we return -1.
2. If the two strings are not equal, the longest uncommon subsequence will be the longer of the ... | 10,446 | [
{
"from": "human",
"value": "Write a python function to find the length of the longest uncommon subsequence (LUS) of two strings. An uncommon subsequence is a subsequence of one of the strings that is not a subsequence of the other string."
},
{
"from": "gpt",
"value": "To find the length of the... |
Write a python function to find the longest common subsequence of two strings. | Here is the code to solve this problem:
```python
def find_longest_common_subsequence(str1, str2):
m = len(str1)
n = len(str2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if str1[i - 1] == str2[j - 1]:
dp[i][j] = dp[... | [
"assert find_longest_common_subsequence(\"AGGTAB\", \"GXTXAYB\") == 4",
"assert find_longest_common_subsequence(\"ABC\", \"AC\") == 2",
"assert find_longest_common_subsequence(\"ABCBDAB\", \"BDCAB\") == 4"
] | Certainly! The longest common subsequence (LCS) of two strings is a classic problem in computer science. Here's a Python function to find the LCS using dynamic programming:
```python
def longest_common_subsequence(str1, str2):
# Get the lengths of both strings
m = len(str1)
n = len(str2)
# Create a 2D... | 10,447 | [
{
"from": "human",
"value": "Write a python function to find the longest common subsequence of two strings."
},
{
"from": "gpt",
"value": "Certainly! The longest common subsequence (LCS) of two strings is a classic problem in computer science. Here's a Python function to find the LCS using dynam... |
Write a python function to calculate the area of a circle based on its radius. | Here is the code to solve this problem:
```python
import math
def area_circle(radius):
area=math.pi*(radius**2)
return area
``` | [
"assert area_circle(1)==3.1415926535897932",
"assert area_circle(10)==314.1592653589793",
"assert area_circle(5)==78.53981633974483"
] | Certainly! You can calculate the area of a circle using the formula:
\[ \text{Area} = \pi \times \text{radius}^2 \]
Here's a Python function that takes the radius as an argument and returns the area of the circle:
```python
import math
def calculate_circle_area(radius):
if radius < 0:
raise ValueError("... | 10,448 | [
{
"from": "human",
"value": "Write a python function to calculate the area of a circle based on its radius."
},
{
"from": "gpt",
"value": "Certainly! You can calculate the area of a circle using the formula:\n\n\\[ \\text{Area} = \\pi \\times \\text{radius}^2 \\]\n\nHere's a Python function that... |
Write a Python function to check if a given number is a power of four. | Here is the code to solve this problem:
```python
def is_power_of_four(n):
if n < 1:
return False
while n % 4 == 0:
n = n / 4
return n == 1
``` | [
"assert is_power_of_four(0) == False",
"assert is_power_of_four(16) == True",
"assert is_power_of_four(64) == True",
"assert is_power_of_four(15) == False",
"assert is_power_of_four(1) == True"
] | Certainly! You can determine if a number is a power of four by checking if it can be expressed as \(4^n\) for some integer \(n \geq 0\). One way to do this is by continuously dividing the number by 4 until the number becomes 1 or it cannot be divided evenly by 4 anymore. Alternatively, you can also use logarithmic prop... | 10,449 | [
{
"from": "human",
"value": "Write a Python function to check if a given number is a power of four."
},
{
"from": "gpt",
"value": "Certainly! You can determine if a number is a power of four by checking if it can be expressed as \\(4^n\\) for some integer \\(n \\geq 0\\). One way to do this is b... |
Write a function `bit_difference(a, b)` that returns the number of bits that are different between two integers `a` and `b`. | Here is the code to solve this problem:
```python
def bit_difference(a, b):
"""
Calculate the number of bits that are different between two integers.
"""
xor_result = a ^ b
count = 0
while xor_result:
xor_result &= xor_result - 1
count += 1
return count
``` | [
"assert bit_difference(1, 3) == 1",
"assert bit_difference(255, 0) == 8",
"assert bit_difference(1, 4) == 2"
] | You can calculate the number of bits that are different between two integers `a` and `b` by using the XOR operation. The XOR operation will return a value where each bit is set to `1` if the corresponding bits of `a` and `b` are different. Then, you can count the number of `1`s in the result to find the total number of... | 10,450 | [
{
"from": "human",
"value": "Write a function `bit_difference(a, b)` that returns the number of bits that are different between two integers `a` and `b`."
},
{
"from": "gpt",
"value": "You can calculate the number of bits that are different between two integers `a` and `b` by using the XOR opera... |
Write a python function to calculate the total number of ways to reach the top of a staircase. You can climb either 1 or 2 steps at a time. | Here is the code to solve this problem:
```python
def total_ways(n):
if n <= 1:
return n
a, b = 1, 2
for _ in range(3, n + 1):
a, b = b, a + b
return b
``` | [
"assert total_ways(3) == 3",
"assert total_ways(5) == 8",
"assert total_ways(4) == 5"
] | You can calculate the total number of ways to reach the top of a staircase using a dynamic programming approach. The number of ways to reach the `n`-th step can be expressed as the sum of the ways to reach the `(n-1)`-th step and the `(n-2)`-th step, because you can arrive at step `n` by either climbing one step from `... | 10,451 | [
{
"from": "human",
"value": "Write a python function to calculate the total number of ways to reach the top of a staircase. You can climb either 1 or 2 steps at a time."
},
{
"from": "gpt",
"value": "You can calculate the total number of ways to reach the top of a staircase using a dynamic progr... |
Write a function that takes a list of integers as input and returns the count of pairs of numbers in the list that add up to a given target sum. | Here is the code to solve this problem:
```python
def count_target_pairs(nums: list[int], target: int) -> int:
count = 0
num_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_map:
count += num_map[complement]
num_map[num] = num_map.ge... | [
"assert count_target_pairs([1, 5, 7, -1], 6) == 2",
"assert count_target_pairs([1, 1, 1, 1], 2) == 6",
"assert count_target_pairs([1, 2, 3, 4, 5], 5) == 2"
] | Certainly! Below is a Python function that takes a list of integers and a target sum as inputs and returns the count of unique pairs of numbers in the list that add up to the target sum.
```python
def count_pairs_with_sum(numbers, target_sum):
# Create a set to keep track of seen numbers
seen = set()
# Cre... | 10,452 | [
{
"from": "human",
"value": "Write a function that takes a list of integers as input and returns the count of pairs of numbers in the list that add up to a given target sum."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that takes a list of integers and a target sum as inp... |
Write a python function to find the longest common prefix string amongst an array of strings. | Here is the code to solve this problem:
```python
def longest_prefix(strs):
if not strs:
return ""
shortest = min(strs,key=len)
for i, ch in enumerate(shortest):
for other in strs:
if other[i] != ch:
return shortest[:i]
return shortest
``` | [
"assert longest_prefix([\"dog\",\"racecar\",\"car\"]) == \"\"",
"assert longest_prefix([\"flower\",\"flow\",\"flight\"]) == \"fl\"",
"assert longest_prefix([\"interspecies\",\"interstellar\",\"interstate\"]) == \"inters\""
] | Certainly! You can implement a function to find the longest common prefix among an array of strings using the following approach:
1. Check if the array is empty. If it is, return an empty string.
2. Assume the first string is the prefix and compare it with the other strings.
3. Keep reducing the prefix until it matche... | 10,453 | [
{
"from": "human",
"value": "Write a python function to find the longest common prefix string amongst an array of strings."
},
{
"from": "gpt",
"value": "Certainly! You can implement a function to find the longest common prefix among an array of strings using the following approach:\n\n1. Check ... |
Write a python function to replace all the occurrences of a given substring in a string with another given substring. | Here is the code to solve this problem:
```python
def replace_substring(s: str, old: str, new: str) -> str:
return s.replace(old, new)
``` | [
"assert replace_substring(\"hello world\", \"world\", \"python\") == \"hello python\"",
"assert replace_substring(\"this is a test\", \"is\", \"was\") == \"thwas was a test\"",
"assert replace_substring(\"the quick brown fox\", \"quick\", \"slow\") == \"the slow brown fox\""
] | You can create a Python function to replace all occurrences of a given substring within a string using the built-in `replace()` method of string objects. Here's a simple implementation of such a function:
```python
def replace_substring(original_string, old_substring, new_substring):
"""
Replace all occurrence... | 10,454 | [
{
"from": "human",
"value": "Write a python function to replace all the occurrences of a given substring in a string with another given substring."
},
{
"from": "gpt",
"value": "You can create a Python function to replace all occurrences of a given substring within a string using the built-in `r... |
Write a python function to convert a list of words into a list of their corresponding lengths. | Here is the code to solve this problem:
```python
def word_lengths(lst):
return [len(word) for word in lst]
``` | [
"assert word_lengths([\"python\", \"java\", \"c++\"]) == [6, 4, 3]",
"assert word_lengths([\"apple\", \"banana\", \"cherry\"]) == [5, 6, 6]",
"assert word_lengths([\"hello\", \"world\", \"programming\"]) == [5, 5, 11]"
] | You can create a Python function to convert a list of words into a list of their corresponding lengths using a simple list comprehension. Here’s how you can implement it:
```python
def words_to_lengths(words):
"""
Convert a list of words into a list of their corresponding lengths.
Parameters:
words (l... | 10,455 | [
{
"from": "human",
"value": "Write a python function to convert a list of words into a list of their corresponding lengths."
},
{
"from": "gpt",
"value": "You can create a Python function to convert a list of words into a list of their corresponding lengths using a simple list comprehension. Her... |
Write a python function to rearrange the given list such that all elements less than the pivot comes before the pivot, and all elements greater than the pivot comes after it. | Here is the code to solve this problem:
```python
def pivotArray(nums, pivot):
n = len(nums)
ans = [pivot] * n
left, right = 0, -1
for i, num in enumerate(nums):
if num < pivot:
ans[left], left = num, left + 1
if nums[~i] > pivot:
ans[right], right = nums[~i... | [
"assert pivotArray([-3, 4, 3, 2], 2) == [-3, 2, 4, 3]",
"assert pivotArray([9, 12, 5, 10, 14, 1, 10], 10) == [9, 5, 1, 10, 10, 12, 14]",
"assert pivotArray([1, 2, 3, 4], 3) == [1, 2, 3, 4]"
] | You can implement a function in Python to rearrange the given list based on a pivot. The function will take two arguments: the list and the pivot value. It will return a new list where all elements less than the pivot are placed before it and all elements greater than the pivot are placed after it. Here's one way to do... | 10,456 | [
{
"from": "human",
"value": "Write a python function to rearrange the given list such that all elements less than the pivot comes before the pivot, and all elements greater than the pivot comes after it."
},
{
"from": "gpt",
"value": "You can implement a function in Python to rearrange the given... |
Write a python function to check whether 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. For example, 6 is a perfect number because its divisors are 1, 2, and 3, and 1 + 2 + 3 = 6. | Here is the code to solve this problem:
```python
def check_perfect_number(num):
if num < 1:
return False
sum_divisors = 0
for i in range(1, num):
if num % i == 0:
sum_divisors += i
return sum_divisors == num
``` | [
"assert check_perfect_number(28) == True",
"assert check_perfect_number(97) == False",
"assert check_perfect_number(6) == True",
"assert check_perfect_number(12) == False",
"assert check_perfect_number(496) == True"
] | You can create a function in Python to check if a number is a perfect number by following these steps:
1. Find the proper divisors of the number (which are all the divisors excluding the number itself).
2. Sum those proper divisors.
3. Compare the sum with the original number to determine if it is a perfect number.
H... | 10,457 | [
{
"from": "human",
"value": "Write a python function to check whether 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. For example, 6 is a perfect number because its divisors are 1, 2, and 3, and 1 + 2 + 3 = 6."
},
{
"... |
Write a python function to find the minimum absolute difference between any two elements in a given array. | Here is the code to solve this problem:
```python
def min_abs_diff(arr):
arr.sort()
min_diff = abs(arr[1] - arr[0])
for i in range(2, len(arr)):
diff = abs(arr[i] - arr[i-1])
if diff < min_diff:
min_diff = diff
return min_diff
``` | [
"assert min_abs_diff([10, 20, 30, 40, 50]) == 10",
"assert min_abs_diff([4, 2, 1, 3]) == 1",
"assert min_abs_diff([1, 5, 3, 19, 18, 25]) == 1"
] | You can find the minimum absolute difference between any two elements in an array by sorting the array first and then finding the minimum difference between consecutive elements. This approach is efficient because the smallest difference must occur between some pair of adjacent elements in a sorted array.
Here is a Py... | 10,458 | [
{
"from": "human",
"value": "Write a python function to find the minimum absolute difference between any two elements in a given array."
},
{
"from": "gpt",
"value": "You can find the minimum absolute difference between any two elements in an array by sorting the array first and then finding the... |
Write a Python function to find the most common element in a given list. | Here is the code to solve this problem:
```python
def find_most_common(lst):
return max(set(lst), key=lst.count)
``` | [
"assert find_most_common(['a', 'b', 'b', 'c', 'c', 'c', 'c']) == 'c'",
"assert find_most_common([1, 2, 2, 3, 3, 3]) == 3",
"assert find_most_common([1.1, 2.2, 2.2, 3.3, 3.3, 3.3]) == 3.3"
] | You can find the most common element in a list by using the `collections.Counter` class, which makes it easy to count the occurrences of each element in the list. Here's a Python function that implements this:
```python
from collections import Counter
def most_common_element(lst):
if not lst:
return None ... | 10,459 | [
{
"from": "human",
"value": "Write a Python function to find the most common element in a given list."
},
{
"from": "gpt",
"value": "You can find the most common element in a list by using the `collections.Counter` class, which makes it easy to count the occurrences of each element in the list. ... |
Write a python function to simulate a traffic light system. The traffic light has two states: green and red. The traffic light stays green for a certain amount of time, then switches to red for a certain amount of time, and then back to green again. The function should return the state of the traffic light at a certain... | Here is the code to solve this problem:
```python
def traffic_light(t):
green = 2 # green light duration
red = 3 # red light duration
if t % (green + red) < green:
return "green"
else:
return "red"
``` | [
"assert traffic_light(5) == \"green\"",
"assert traffic_light(3) == \"red\"",
"assert traffic_light(1) == \"green\""
] | You can simulate a traffic light system using a simple Python function that takes the total duration of the green light, the total duration of the red light, and a specific time `t` for which you would like to determine the traffic light state.
Here is a sample implementation:
```python
def traffic_light_state(green... | 10,460 | [
{
"from": "human",
"value": "Write a python function to simulate a traffic light system. The traffic light has two states: green and red. The traffic light stays green for a certain amount of time, then switches to red for a certain amount of time, and then back to green again. The function should return th... |
Write a python function to find the length of the longest subsequence of a given sequence for which the elements of the sequence are strictly increasing. | Here is the code to solve this problem:
```python
def length_of_lis(nums):
if not nums:
return 0
dp = [1]*len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
``` | [
"assert length_of_lis([0,1,0,3,2,3]) == 4",
"assert length_of_lis([10,9,2,5,3,7,101,18]) == 4",
"assert length_of_lis([7,7,7,7,7,7,7]) == 1"
] | You can determine the length of the longest strictly increasing subsequence (LIS) using a dynamic programming approach. Here's a Python function that implements this:
```python
def length_of_longest_increasing_subsequence(sequence):
if not sequence:
return 0
n = len(sequence)
# dp[i] will hold the... | 10,461 | [
{
"from": "human",
"value": "Write a python function to find the length of the longest subsequence of a given sequence for which the elements of the sequence are strictly increasing."
},
{
"from": "gpt",
"value": "You can determine the length of the longest strictly increasing subsequence (LIS) ... |
Write a function to return the count of the most frequent item in a given array. | Here is the code to solve this problem:
```python
from collections import Counter
def most_frequent_item_count(collection):
counter = Counter(collection)
max_count = max(counter.values())
return max_count
``` | [
"assert most_frequent_item_count([1, 2, 2, 3, 3, 3]) == 3",
"assert most_frequent_item_count([5, 5, 5, 1, 2, 2, 6, 6, 6, 6]) == 4",
"assert most_frequent_item_count([1, 2, 3, 4, 5]) == 1"
] | Certainly! You can create a function in Python to count the most frequent item in an array by utilizing the `collections.Counter` class, which makes it easy to count hashable objects. Here's a sample implementation:
```python
from collections import Counter
def count_most_frequent(arr):
if not arr: # Check if th... | 10,462 | [
{
"from": "human",
"value": "Write a function to return the count of the most frequent item in a given array."
},
{
"from": "gpt",
"value": "Certainly! You can create a function in Python to count the most frequent item in an array by utilizing the `collections.Counter` class, which makes it eas... |
Write a Python function to find the least common multiple (LCM) of two numbers. | Here is the code to solve this problem:
```python
def gcd(x, y):
while(y):
x, y = y, x % y
return x
def least_common_multiple(x, y):
lcm = (x*y)//gcd(x,y)
return lcm
``` | [
"assert least_common_multiple(21, 6) == 42",
"assert least_common_multiple(4, 6) == 12",
"assert least_common_multiple(5, 7) == 35"
] | Certainly! The least common multiple (LCM) of two numbers can be calculated using the relationship between LCM and the greatest common divisor (GCD). Specifically, the formula to find the LCM is:
\[
\text{LCM}(a, b) = \frac{|a \times b|}{\text{GCD}(a, b)}
\]
Here's a Python function that implements this:
```python
i... | 10,463 | [
{
"from": "human",
"value": "Write a Python function to find the least common multiple (LCM) of two numbers."
},
{
"from": "gpt",
"value": "Certainly! The least common multiple (LCM) of two numbers can be calculated using the relationship between LCM and the greatest common divisor (GCD). Specif... |
Write a python function to filter out the odd numbers from a list and return a list with only even numbers. | Here is the code to solve this problem:
```python
def filter_odd_numbers(lst):
return [num for num in lst if num % 2 == 0]
``` | [
"assert filter_odd_numbers([1,2,3,4,5,6]) == [2,4,6]",
"assert filter_odd_numbers([11,22,33,44,55]) == [22,44]",
"assert filter_odd_numbers([10,15,20,25,30]) == [10,20,30]"
] | Certainly! You can create a simple Python function that takes a list of numbers as input, filters out the odd numbers, and returns a list containing only the even numbers. Here's one way to do that:
```python
def filter_even_numbers(numbers):
"""Filters out odd numbers from a list and returns only even numbers."""... | 10,464 | [
{
"from": "human",
"value": "Write a python function to filter out the odd numbers from a list and return a list with only even numbers."
},
{
"from": "gpt",
"value": "Certainly! You can create a simple Python function that takes a list of numbers as input, filters out the odd numbers, and retur... |
Write a function to find the top 3 users with the highest scores based on a given list of invitation pairs. The scoring system is as follows:
- For each new user, the inviter gets +10 points.
- For each direct invitee of a user, the inviter gets +3 points.
- For each indirect invitee (invitee's invitee) of a user, the ... | Here is the code to solve this problem:
```python
from collections import defaultdict
def find_top_users(invitationPairs):
users = defaultdict(list)
score = defaultdict(int)
# New user +10
for pair in invitationPairs:
users[pair[0]].append(pair[1])
score[pair[0]] += 10
# Direct i... | [
"assert find_top_users([[1, 2], [1, 3], [3, 4], [4, 5], [4, 6], [4, 6]]) == [4, 1, 3]",
"assert find_top_users([[1, 2], [2, 3], [2, 4], [2, 5], [5, 6], [5, 7], [6, 8], [2, 9]]) == [2, 1, 5]",
"assert find_top_users([[1, 2], [3, 4]]) == [1, 3]"
] | To solve the problem of scoring users based on a given list of invitation pairs, we can create a function in Python. This function will compute the score for each user according to the specified scoring system and then return the top 3 users with the highest scores.
Here's how we can implement this:
1. Create a dicti... | 10,465 | [
{
"from": "human",
"value": "Write a function to find the top 3 users with the highest scores based on a given list of invitation pairs. The scoring system is as follows:\n- For each new user, the inviter gets +10 points.\n- For each direct invitee of a user, the inviter gets +3 points.\n- For each indirect... |
Write a function to calculate the number of distinct rotations of a given number that form a different number. | Here is the code to solve this problem:
```python
def count_rotations(N):
"""
:type N: int
:rtype: int
"""
cnt = 0
num = str(N)
length = len(num)
for i in range(1,length):
rotated_num = num[i:] + num[:i]
if rotated_num != num:
cnt += 1
return cnt
``` | [
"assert count_rotations(123)==2",
"assert count_rotations(555)==0",
"assert count_rotations(489)==2"
] | To calculate the number of distinct rotations of a given number that form a different number, you can follow these steps:
1. Convert the number to a string to facilitate rotation.
2. Generate all possible rotations of the string representation of the number.
3. Check each rotation to see if it forms a distinct number ... | 10,466 | [
{
"from": "human",
"value": "Write a function to calculate the number of distinct rotations of a given number that form a different number."
},
{
"from": "gpt",
"value": "To calculate the number of distinct rotations of a given number that form a different number, you can follow these steps:\n\n... |
Write a function that determines whether a given list of integers can be made into a palindrome by removing at most one element. | Here is the code to solve this problem:
```python
def can_form_palindrome(arr):
def is_palindrome(i, j):
while i < j:
if arr[i] != arr[j]:
return False
i += 1
j -= 1
return True
i, j = 0, len(arr) - 1
while i < j:
if arr[i] != arr... | [
"assert can_form_palindrome([1,2,3,2,1])==True",
"assert can_form_palindrome([1,2,3,2,2,1])==True",
"assert can_form_palindrome([1,2,3,4,5])==False"
] | To determine whether a given list of integers can be made into a palindrome by removing at most one element, we can use a two-pointer technique. A palindrome reads the same forwards and backwards, so we can compare elements from the beginning and end of the list moving towards the center. If we find a mismatch, we can ... | 10,467 | [
{
"from": "human",
"value": "Write a function that determines whether a given list of integers can be made into a palindrome by removing at most one element."
},
{
"from": "gpt",
"value": "To determine whether a given list of integers can be made into a palindrome by removing at most one element... |
Write a function to find the product of all odd numbers in a given list. If there are no odd numbers, return 0. | Here is the code to solve this problem:
```python
def product_of_odds(lst):
product = 1
found_odd = False
for num in lst:
if num % 2 != 0:
product *= num
found_odd = True
return product if found_odd else 0
``` | [
"assert product_of_odds([1, 2, 3, 4, 5]) == 15",
"assert product_of_odds([2, 4, 6, 8]) == 0",
"assert product_of_odds([11, 13, 15]) == 2145"
] | Here's a Python function that achieves this. It takes a list of numbers as input, finds all the odd numbers, and calculates their product. If there are no odd numbers in the list, it returns 0.
```python
def product_of_odd_numbers(numbers):
product = 1
has_odd = False
for number in numbers:
i... | 10,468 | [
{
"from": "human",
"value": "Write a function to find the product of all odd numbers in a given list. If there are no odd numbers, return 0."
},
{
"from": "gpt",
"value": "Here's a Python function that achieves this. It takes a list of numbers as input, finds all the odd numbers, and calculates ... |
Write a python function to find the number of ways to reach the top of a staircase if you can either climb 1 or 2 steps at a time. | Here is the code to solve this problem:
```python
def staircase_climbing_ways(n):
if n <= 2:
return n
first = 1
second = 2
for _ in range(2, n):
third = first + second
first = second
second = third
return second
``` | [
"assert staircase_climbing_ways(4) == 5",
"assert staircase_climbing_ways(3) == 3",
"assert staircase_climbing_ways(5) == 8"
] | You can solve this problem using a dynamic programming approach, where the number of ways to reach the top of the staircase depends on the ways to reach the two previous steps. Here’s how you can implement this in Python:
```python
def climb_stairs(n: int) -> int:
# Base cases
if n == 0:
return 1 # Th... | 10,469 | [
{
"from": "human",
"value": "Write a python function to find the number of ways to reach the top of a staircase if you can either climb 1 or 2 steps at a time."
},
{
"from": "gpt",
"value": "You can solve this problem using a dynamic programming approach, where the number of ways to reach the to... |
Create a Python function that checks if a given list of integers contains a subarray with a sum equal to zero. If such a subarray exists, the function should return True, otherwise, it should return False. | Here is the code to solve this problem:
```python
def has_zero_sum_subarray(nums):
# Initialize a set to store the cumulative sums
cumulative_sums = set()
cumulative_sum = 0
for num in nums:
cumulative_sum += num
# If the cumulative sum is zero or we have seen this sum before, we have a... | [
"assert has_zero_sum_subarray([4, 2, 8, 1]) == False",
"assert has_zero_sum_subarray([1, 2, -3, 4]) == True",
"assert has_zero_sum_subarray([1, 2, 3]) == False",
"assert has_zero_sum_subarray([0, 1, 2, 3]) == True",
"assert has_zero_sum_subarray([-1, 1, 2, 3]) == True"
] | You can check if a given list of integers contains a subarray with a sum equal to zero by using a method that involves maintaining a running sum and checking if that sum has been seen before in a set. If the running sum is zero at any point, or if it has been seen before, then a subarray with a sum of zero exists.
Her... | 10,470 | [
{
"from": "human",
"value": "Create a Python function that checks if a given list of integers contains a subarray with a sum equal to zero. If such a subarray exists, the function should return True, otherwise, it should return False."
},
{
"from": "gpt",
"value": "You can check if a given list ... |
Write a python function to find the smallest positive number that cannot be represented as sum of any subset of a given array. | Here is the code to solve this problem:
```python
def smallest_miss(arr,n):
arr.sort()
smallest = 1
for i in range(n):
if arr[i] <= smallest:
smallest += arr[i]
return smallest
``` | [
"assert smallest_miss([1, 2, 6, 10, 11, 15],6) == 4",
"assert smallest_miss([1, 1, 1, 1],4) == 5",
"assert smallest_miss([1, 2, 3],3) == 7"
] | You can solve this problem using a greedy algorithm. The idea is to sort the array and then iterate through it while maintaining a variable that keeps track of the smallest positive integer that cannot be formed as a sum of the subsets considered so far.
Here’s how the algorithm works:
1. Sort the array.
2. Initializ... | 10,471 | [
{
"from": "human",
"value": "Write a python function to find the smallest positive number that cannot be represented as sum of any subset of a given array."
},
{
"from": "gpt",
"value": "You can solve this problem using a greedy algorithm. The idea is to sort the array and then iterate through i... |
Write a function that takes a list of integers as input and returns a list of unique elements from the input list, sorted in ascending order. | Here is the code to solve this problem:
```python
def unique_sorted(lst):
return sorted(set(lst))
``` | [
"assert unique_sorted([-1, -2, -3, -4, -4, -3, -2, -1]) == [-4, -3, -2, -1]",
"assert unique_sorted([10, 20, 20, 10, 30]) == [10, 20, 30]",
"assert unique_sorted([1, 2, 3, 4, 5, 5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]"
] | You can achieve this in Python by creating a function that utilizes a `set` to remove duplicates, and then convert it back to a sorted list. Here’s an example of how you might implement such a function:
```python
def unique_sorted_list(input_list):
# Use a set to get unique elements
unique_elements = set(input... | 10,472 | [
{
"from": "human",
"value": "Write a function that takes a list of integers as input and returns a list of unique elements from the input list, sorted in ascending order."
},
{
"from": "gpt",
"value": "You can achieve this in Python by creating a function that utilizes a `set` to remove duplicat... |
Write a python function to rearrange positive and negative numbers in an array such that all negative integers appear before all the positive integers without using any additional data structure. | Here is the code to solve this problem:
```python
def rearrange_pos_neg(arr):
def rearrange(arr, start, end):
if(start == end):
return
rearrange(arr, (start+1), end)
if(arr[start] >=0):
reverse(arr, (start +1), end)
reverse(arr, start, end)
def revers... | [
"assert rearrange_pos_neg([-12, 11, -13, -5, 6, -7, 5, -3, -6]) == [-12, -13, -5, -7, -3, -6, 11, 6, 5]",
"assert rearrange_pos_neg([1, 2, 3, 4, -5, -6, -7, -8]) == [-5, -6, -7, -8, 1, 2, 3, 4]",
"assert rearrange_pos_neg([-1, -2, -3, -4, 5, 6, 7, 8]) == [-1, -2, -3, -4, 5, 6, 7, 8]"
] | You can achieve rearranging positive and negative numbers in an array without using any additional data structures by using a two-pointer approach. Here is a Python function to do that:
```python
def rearrange(arr):
left = 0 # Pointer for the next position for negative number
right = 0 # Point... | 10,473 | [
{
"from": "human",
"value": "Write a python function to rearrange positive and negative numbers in an array such that all negative integers appear before all the positive integers without using any additional data structure."
},
{
"from": "gpt",
"value": "You can achieve rearranging positive and... |
Write a function to find the pairs of indices (i, j) in an array where arr[i] + arr[j] is divisible by a given number k, and i < j. The function should return the count of such pairs. | Here is the code to solve this problem:
```python
def find_divisible_pairs(nums, k):
count = 0
remainder_counts = [0] * k
for num in nums:
remainder = num % k
complement = k - remainder
if remainder == 0:
count += remainder_counts[0]
else:
count += ... | [
"assert find_divisible_pairs([4, 3, 5, 1, 2], 7) == 2",
"assert find_divisible_pairs([10, 20, 30, 40, 50], 10) == 10",
"assert find_divisible_pairs([1, 3, 2, 6, 1, 2], 3) == 5"
] | Sure! Below is a Python function that takes an array and a number `k`, and counts the pairs of indices (i, j) such that `arr[i] + arr[j]` is divisible by `k`, and `i < j`.
```python
def count_divisible_pairs(arr, k):
count = 0
n = len(arr)
# Iterate through all pairs (i, j)
for i in range(n):
... | 10,474 | [
{
"from": "human",
"value": "Write a function to find the pairs of indices (i, j) in an array where arr[i] + arr[j] is divisible by a given number k, and i < j. The function should return the count of such pairs."
},
{
"from": "gpt",
"value": "Sure! Below is a Python function that takes an array... |
Write a function that checks whether a list of integers is sorted in ascending order using recursion. | Here is the code to solve this problem:
```python
def is_list_sorted(arr):
if len(arr) <= 1:
return True
return arr[0] <= arr[1] and is_list_sorted(arr[1:])
``` | [
"assert is_list_sorted([1, 2, 3, 4, 4]) == True",
"assert is_list_sorted([1]) == True",
"assert is_list_sorted([1, 2, 3, 4, 5]) == True",
"assert is_list_sorted([5, 4, 3, 2, 1]) == False",
"assert is_list_sorted([1, 3, 2, 4, 5]) == False"
] | You can create a recursive function in Python to check if a list of integers is sorted in ascending order. Below is an example of how you might implement this function:
```python
def is_sorted_ascending(lst):
# Base case: If the list has 0 or 1 element, it is sorted
if len(lst) <= 1:
return True
# ... | 10,475 | [
{
"from": "human",
"value": "Write a function that checks whether a list of integers is sorted in ascending order using recursion."
},
{
"from": "gpt",
"value": "You can create a recursive function in Python to check if a list of integers is sorted in ascending order. Below is an example of how ... |
Write a function to find the number of ways to tile a 2xn rectangle using 2x1 tiles. | Here is the code to solve this problem:
```python
def tile_ways(n):
if n == 0 or n == 1:
return 1
a, b = 1, 2
for _ in range(2, n):
a, b = b, a + b
return b
``` | [
"assert tile_ways(3) == 3",
"assert tile_ways(5) == 8",
"assert tile_ways(4) == 5"
] | To find the number of ways to tile a 2xN rectangle using 2x1 tiles, we can use a recursive approach. The main idea is to recognize that we can fill the rectangle in one of two ways:
1. Place a vertical tile at the start, which leaves us with a 2x(N-1) rectangle.
2. Place two horizontal tiles at the start, which leaves... | 10,476 | [
{
"from": "human",
"value": "Write a function to find the number of ways to tile a 2xn rectangle using 2x1 tiles."
},
{
"from": "gpt",
"value": "To find the number of ways to tile a 2xN rectangle using 2x1 tiles, we can use a recursive approach. The main idea is to recognize that we can fill the... |
Write a function to find the number of unique binary search trees (BSTs) that store values 1...n. | Here is the code to solve this problem:
```python
def num_unique_bst(n):
if n <= 1:
return 1
dp = [0] * (n + 1)
dp[0] = 1
dp[1] = 1
for i in range(2, n + 1):
for j in range(i):
dp[i] += dp[j] * dp[i - j - 1]
return dp[n]
``` | [
"assert num_unique_bst(3) == 5",
"assert num_unique_bst(4) == 14",
"assert num_unique_bst(5) == 42"
] | To count the number of unique binary search trees (BSTs) that can be formed using values from 1 to n, we can use a dynamic programming approach based on the concept of Catalan numbers.
The number of unique BSTs for `n` nodes can be determined using the following recurrence relation:
- For each value `i` from `1` to `n... | 10,477 | [
{
"from": "human",
"value": "Write a function to find the number of unique binary search trees (BSTs) that store values 1...n."
},
{
"from": "gpt",
"value": "To count the number of unique binary search trees (BSTs) that can be formed using values from 1 to n, we can use a dynamic programming app... |
Write a function that takes a list of words and returns a list of words that consist of only unique characters. | Here is the code to solve this problem:
```python
def unique_char_words(words):
unique_words = []
for word in words:
if len(set(word)) == len(word):
unique_words.append(word)
return unique_words
``` | [
"assert unique_char_words([\"aa\", \"bb\", \"cc\", \"dd\"]) == []",
"assert unique_char_words([\"apple\", \"banana\", \"cherry\", \"date\"]) == [\"date\"]",
"assert unique_char_words([\"hello\", \"world\", \"python\", \"programming\"]) == [\"world\", \"python\"]"
] | Here's a Python function that takes a list of words and returns a list of words that consist of only unique characters:
```python
def has_unique_characters(word):
# Create a set to store characters we've seen
seen = set()
for char in word:
if char in seen:
return False
seen.add(... | 10,478 | [
{
"from": "human",
"value": "Write a function that takes a list of words and returns a list of words that consist of only unique characters."
},
{
"from": "gpt",
"value": "Here's a Python function that takes a list of words and returns a list of words that consist of only unique characters:\n\n`... |
Write a function to find the smallest number in a list that is greater than a given number. | Here is the code to solve this problem:
```python
def find_next_larger(lst, num):
result = None
for i in lst:
if i > num:
if result is None or i < result:
result = i
return result
``` | [
"assert find_next_larger([2, 3, 4, 5, 1], 2) == 3",
"assert find_next_larger([5, 1, 3], 6) == None",
"assert find_next_larger([10, 20, 30, 40, 50], 25) == 30"
] | To find the smallest number in a list that is greater than a given number, you can use the following Python function. This function iterates through the list and maintains a variable to keep track of the smallest number found that is greater than the specified number.
Here's how you can implement it:
```python
def f... | 10,479 | [
{
"from": "human",
"value": "Write a function to find the smallest number in a list that is greater than a given number."
},
{
"from": "gpt",
"value": "To find the smallest number in a list that is greater than a given number, you can use the following Python function. This function iterates thr... |
Write a python function to find the second largest number in a list. | Here is the code to solve this problem:
```python
def find_Second_Largest(lst):
lst.sort()
return lst[-2]
``` | [
"assert find_Second_Largest([1,2,3,4,5]) == 4",
"assert find_Second_Largest([5,1,2,3,4]) == 4",
"assert find_Second_Largest([1,2]) == 1"
] | Certainly! Below is a Python function that finds the second largest number in a list. This function handles cases where there may be duplicates and returns `None` if the list has fewer than two unique values.
```python
def second_largest(numbers):
if len(numbers) < 2:
return None # Not enough elements for... | 10,480 | [
{
"from": "human",
"value": "Write a python function to find the second largest number in a list."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that finds the second largest number in a list. This function handles cases where there may be duplicates and returns `None` if t... |
Write a function to find the maximum number of points that can be observed from a given location and angle in a 2D plane. Given a list of points on the plane, the observer's location, and the angle of observation, return the maximum number of points that can be observed. A point is considered observable if it falls wit... | Here is the code to solve this problem:
```python
from math import atan2, pi
from bisect import bisect_right
def max_visible_points(points, angle, location):
sameCnt = 0
polarDegrees = []
for p in points:
if p == location:
sameCnt += 1
else:
polarDegrees.append(atan... | [
"assert max_visible_points([[2,1],[2,2],[3,4],[1,1]], 90, [1,1]) == 4",
"assert max_visible_points([[2,1],[2,2],[3,3]], 90, [1,1]) == 3",
"assert max_visible_points([[1,0],[2,1]], 13, [1,1]) == 1"
] | To solve this problem, we can follow these steps:
1. **Convert Points to Angles**: For each point in the plane, calculate the angle formed with respect to the observer's location. This can be done using the `atan2` function to compute the angle of the point relative to the observer.
2. **Sort Angles**: Sort the cal... | 10,481 | [
{
"from": "human",
"value": "Write a function to find the maximum number of points that can be observed from a given location and angle in a 2D plane. Given a list of points on the plane, the observer's location, and the angle of observation, return the maximum number of points that can be observed. A point... |
Create a Python function to check if the concatenation of two given strings in any order forms a palindrome. | Here is the code to solve this problem:
```python
def is_palindrome_concat(s1, s2):
return (s1 + s2) == (s1 + s2)[::-1] or (s2 + s1) == (s2 + s1)[::-1]
``` | [
"assert is_palindrome_concat(\"race\", \"car\") == True",
"assert is_palindrome_concat(\"madam\", \"\") == True",
"assert is_palindrome_concat(\"hello\", \"world\") == False"
] | Certainly! You can create a Python function that checks if the concatenation of two strings in any order forms a palindrome by following these steps:
1. Concatenate the two strings in both possible orders (i.e., `s1 + s2` and `s2 + s1`).
2. Check if either concatenated string is a palindrome.
A string is considered a... | 10,482 | [
{
"from": "human",
"value": "Create a Python function to check if the concatenation of two given strings in any order forms a palindrome."
},
{
"from": "gpt",
"value": "Certainly! You can create a Python function that checks if the concatenation of two strings in any order forms a palindrome by ... |
Write a Python function that takes a list of integers as input and returns a new list that contains only the odd numbers from the original list, sorted in ascending order. | Here is the code to solve this problem:
```python
def sort_odd(numbers):
odd_numbers = [num for num in numbers if num % 2 != 0]
odd_numbers.sort()
return odd_numbers
``` | [
"assert sort_odd([1, 2, 3, 4, 5]) == [1, 3, 5]",
"assert sort_odd([8, 6, 4, 2, 0]) == []",
"assert sort_odd([10, 21, 32, 43, 54, 65]) == [21, 43, 65]"
] | You can achieve this by creating a function that filters out the odd numbers from the list and then sorts them. Here's a Python function that does exactly that:
```python
def filter_and_sort_odds(numbers):
# Filter out the odd numbers
odd_numbers = [num for num in numbers if num % 2 != 0]
# Sort the odd nu... | 10,483 | [
{
"from": "human",
"value": "Write a Python function that takes a list of integers as input and returns a new list that contains only the odd numbers from the original list, sorted in ascending order."
},
{
"from": "gpt",
"value": "You can achieve this by creating a function that filters out the... |
Write a python function to find the k most frequent elements in a list of numbers. | Here is the code to solve this problem:
```python
import collections
import heapq
def topKFrequent(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
count = collections.Counter(nums) # Get the frequency of each element
return heapq.nlargest(k, count.keys(), key=count.g... | [
"assert topKFrequent([1,1,1,2,2,3], 2) == [1, 2]",
"assert topKFrequent([1], 1) == [1]",
"assert topKFrequent([4,1,-2,4,5,1,5,5,-2], 3) == [5, 4, 1]"
] | You can find the k most frequent elements in a list using the `collections.Counter` class to count the occurrences of each element, and then use the `most_common` method to retrieve the k most common elements. Here’s how you can implement this in a Python function:
```python
from collections import Counter
def k_most... | 10,484 | [
{
"from": "human",
"value": "Write a python function to find the k most frequent elements in a list of numbers."
},
{
"from": "gpt",
"value": "You can find the k most frequent elements in a list using the `collections.Counter` class to count the occurrences of each element, and then use the `mos... |
Write a python function to find the intersection of two given arrays. | Here is the code to solve this problem:
```python
def intersection_arrays(arr1, arr2):
result = []
for num in arr1:
if num in arr2 and num not in result:
result.append(num)
return result
``` | [
"assert intersection_arrays([10, 15, 20, 25], [20, 25, 30, 35]) == [20, 25]",
"assert intersection_arrays([1, 2, 3, 4], [3, 4, 5, 6]) == [3, 4]",
"assert intersection_arrays([2, 4, 6, 8], [1, 3, 5, 7]) == []"
] | You can find the intersection of two arrays in Python using various methods. Below is a simple function that uses sets to achieve this:
```python
def intersection(arr1, arr2):
# Convert both lists to sets
set1 = set(arr1)
set2 = set(arr2)
# Find intersection using set intersect operation
inter... | 10,485 | [
{
"from": "human",
"value": "Write a python function to find the intersection of two given arrays."
},
{
"from": "gpt",
"value": "You can find the intersection of two arrays in Python using various methods. Below is a simple function that uses sets to achieve this:\n\n```python\ndef intersection... |
Write a python function to find the longest substring without repeating characters in a given string. | Here is the code to solve this problem:
```python
def longest_Substring(s):
charSet = set()
left = 0
res = ""
for right in range(len(s)):
while s[right] in charSet:
charSet.remove(s[left])
left += 1
charSet.add(s[right])
if right - left + 1 > len(res):
... | [
"assert longest_Substring(\"abcabcbb\") == \"abc\"",
"assert longest_Substring(\"bbbbb\") == \"b\"",
"assert longest_Substring(\"pwwkew\") == \"wke\""
] | Certainly! You can find the longest substring without repeating characters using a sliding window approach. Here's a Python function that implements this approach:
```python
def longest_unique_substring(s: str) -> str:
char_index_map = {}
start = 0
max_length = 0
longest_substring = ""
for end... | 10,486 | [
{
"from": "human",
"value": "Write a python function to find the longest substring without repeating characters in a given string."
},
{
"from": "gpt",
"value": "Certainly! You can find the longest substring without repeating characters using a sliding window approach. Here's a Python function t... |
Create a python function to find the maximum distance from any cell to its nearest land in a given grid. The grid is a 2D list of 0s and 1s, where 1 represents land and 0 represents water. If there is no land in the grid, return -1. | Here is the code to solve this problem:
```python
import collections
def max_distance(grid):
n = len(grid)
queue = collections.deque()
visited = collections.defaultdict(lambda: False)
res = -1
for i in range(n):
for j in range(n):
if grid[i][j] == 1:
queue.appen... | [
"assert max_distance([[1,0,1],[0,0,0],[1,0,1]]) == 2",
"assert max_distance([[0,0,0],[0,0,0],[0,0,0]]) == -1",
"assert max_distance([[1,0,0],[0,0,0],[0,0,0]]) == 4"
] | You can solve the problem of finding the maximum distance from any water cell to its nearest land cell in a grid using a breadth-first search (BFS) approach. The algorithm involves starting from all land cells and then expanding outwards to all water cells until all reachable water cells have been processed. Below is a... | 10,487 | [
{
"from": "human",
"value": "Create a python function to find the maximum distance from any cell to its nearest land in a given grid. The grid is a 2D list of 0s and 1s, where 1 represents land and 0 represents water. If there is no land in the grid, return -1."
},
{
"from": "gpt",
"value": "You... |
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 excluding the number itself. For example, 6 is a perfect number because its divisors are 1, 2, and 3, and 1 + 2 + 3 = 6. | Here is the code to solve this problem:
```python
def check_perfect_number(n):
sum = 0
for i in range(1, n):
if (n % i == 0):
sum = sum + i
if (sum == n):
return True
else:
return False
``` | [
"assert check_perfect_number(6) == True",
"assert check_perfect_number(12) == False",
"assert check_perfect_number(28) == True"
] | Certainly! Below is a Python function that checks if a given positive integer is a perfect number:
```python
def is_perfect_number(n):
if n <= 0:
return False # Perfect numbers are positive integers
# Initialize the sum of proper divisors
sum_of_divisors = 0
# Find proper divisors from 1... | 10,488 | [
{
"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 excluding the number itself. For example, 6 is a perfect number because its divisors are 1, 2, and 3, and 1 + 2 +... |
Write a function that takes a string as input and returns the string with every word capitalized. | Here is the code to solve this problem:
```python
def capitalize_words(s):
return ' '.join(word.capitalize() for word in s.split())
``` | [
"assert capitalize_words(\"this is a test\") == \"This Is A Test\"",
"assert capitalize_words(\"python programming\") == \"Python Programming\"",
"assert capitalize_words(\"hello world\") == \"Hello World\""
] | You can achieve this in Python by defining a function that uses the `str.title()` method, which capitalizes the first letter of each word in a string. Here's one way to implement such a function:
```python
def capitalize_words(input_string):
return input_string.title()
```
Alternatively, if you want a more manual... | 10,489 | [
{
"from": "human",
"value": "Write a function that takes a string as input and returns the string with every word capitalized."
},
{
"from": "gpt",
"value": "You can achieve this in Python by defining a function that uses the `str.title()` method, which capitalizes the first letter of each word ... |
Write a python function that takes two lists of integers and merges them into a single list, sorting the combined list in ascending order. The first list has 'm' elements and the second list has 'n' elements. The function should modify the first list in-place to accommodate the merged and sorted result. | Here is the code to solve this problem:
```python
def merge_lists(nums1, m, nums2, n):
while m > 0 and n > 0:
if nums1[m - 1] >= nums2[n - 1]:
nums1[m + n - 1] = nums1[m - 1]
m -= 1
else:
nums1[m + n - 1] = nums2[n - 1]
n -= 1
while n > 0:
... | [
"assert merge_lists([1,2,3,0,0,0], 3, [2,5,6], 3) == [1,2,2,3,5,6]",
"assert merge_lists([1,0], 1, [2], 1) == [1,2]",
"assert merge_lists([0], 0, [1], 1) == [1]"
] | To merge two lists of integers while sorting them in ascending order and modifying the first list in-place, we can use the following approach:
1. Concatenate the second list to the first list.
2. Sort the merged list.
3. Modify the first list in-place to reflect the sorted combined values.
Here's a Python function th... | 10,490 | [
{
"from": "human",
"value": "Write a python function that takes two lists of integers and merges them into a single list, sorting the combined list in ascending order. The first list has 'm' elements and the second list has 'n' elements. The function should modify the first list in-place to accommodate the ... |
Write a function to find the number of unique paths in a grid with obstacles. There is a robot initially located at the top-left corner (0, 0). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner (m-1, n-1). Now consider if some obstacles are added to ... | Here is the code to solve this problem:
```python
def unique_paths_with_obstacles(obstacleGrid):
m = len(obstacleGrid)
n = len(obstacleGrid[0])
dp = [[0]*n for _ in range(m)]
dp[0][0] = 1-obstacleGrid[0][0]
for i in range(m):
for j in range(n):
if obstacleGrid[i][j] == 1:
... | [
"assert unique_paths_with_obstacles([[0,0,0],[0,1,0],[0,0,0]]) == 2",
"assert unique_paths_with_obstacles([[0,1],[0,0]]) == 1",
"assert unique_paths_with_obstacles([[1,0]]) == 0"
] | To solve the problem of finding the number of unique paths in a grid with obstacles, we can use dynamic programming. The idea is to maintain a 2D array (or grid) that represents the number of ways to reach each cell in the grid. If a cell contains an obstacle, we can't reach that cell, and if it's a free space, we will... | 10,491 | [
{
"from": "human",
"value": "Write a function to find the number of unique paths in a grid with obstacles. There is a robot initially located at the top-left corner (0, 0). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner (m-1, n-1). Now... |
Write a function to find the largest product of three elements from a given list. | Here is the code to solve this problem:
```python
def largest_product_three_elements(nums):
nums.sort()
return max(nums[0]*nums[1]*nums[-1], nums[-1]*nums[-2]*nums[-3])
``` | [
"assert largest_product_three_elements([-10, -10, 5, 2]) == 500",
"assert largest_product_three_elements([1, 10, 2, 6, 5, 3]) == 300",
"assert largest_product_three_elements([-1, -2, -3, -4]) == -6"
] | You can find the largest product of three elements from a given list in Python by sorting the list and considering the largest three numbers as well as the two smallest numbers (in case there are negative numbers). Here's a Python function that does this:
```python
def largest_product_of_three(nums):
if len(nums) ... | 10,492 | [
{
"from": "human",
"value": "Write a function to find the largest product of three elements from a given list."
},
{
"from": "gpt",
"value": "You can find the largest product of three elements from a given list in Python by sorting the list and considering the largest three numbers as well as th... |
Write a function that takes a list of integers and returns the index of the first occurrence of the maximum number in the list. If there are multiple occurrences of the maximum number, return the index of the first occurrence. | Here is the code to solve this problem:
```python
def first_max_index(numbers):
if len(numbers) == 0:
return None
max_index = 0
for i in range(1, len(numbers)):
if numbers[i] > numbers[max_index]:
max_index = i
return max_index
``` | [
"assert first_max_index([1, 1, 1, 1, 1]) == 0",
"assert first_max_index([2, 2, 1, 3, 1]) == 3",
"assert first_max_index([1, 2, 3, 2, 3]) == 2",
"assert first_max_index([1]) == 0"
] | You can achieve this by defining a function that iterates through the list to find the maximum value, and then returns the index of its first occurrence. Here's a simple implementation in Python:
```python
def index_of_first_max(nums):
if not nums:
return -1 # Return -1 if the list is empty
max_v... | 10,493 | [
{
"from": "human",
"value": "Write a function that takes a list of integers and returns the index of the first occurrence of the maximum number in the list. If there are multiple occurrences of the maximum number, return the index of the first occurrence."
},
{
"from": "gpt",
"value": "You can a... |
Write a function that finds the most common word in a given sentence and returns it. The function should ignore punctuation and be case-insensitive. If there is a tie for the most common word, the function should return the first one in the sentence. | Here is the code to solve this problem:
```python
import re
from collections import Counter
def most_common_word(sentence):
# Remove punctuation and convert to lowercase
cleaned_sentence = re.sub(r'[^\w\s]', '', sentence).lower()
# Split the sentence into words
words = cleaned_sentence.split()
# C... | [
"assert most_common_word(\"To be or not to be, that is the question.\") == \"to\"",
"assert most_common_word(\"Hello world, hello everyone!\") == \"hello\"",
"assert most_common_word(\"This is a test. This is only a test.\") == \"this\""
] | Certainly! Below is a Python function that accomplishes the task of finding the most common word in a given sentence. It ignores punctuation and is case-insensitive. If there is a tie in frequency, it returns the first one that appears in the sentence.
```python
import string
from collections import Counter
def most_... | 10,494 | [
{
"from": "human",
"value": "Write a function that finds the most common word in a given sentence and returns it. The function should ignore punctuation and be case-insensitive. If there is a tie for the most common word, the function should return the first one in the sentence."
},
{
"from": "gpt",... |
Write a function that takes a positive integer as an argument and returns the reverse of its binary representation. | Here is the code to solve this problem:
```python
def reverse_binary(num):
# Convert the number to binary representation
binary = bin(num)[2:]
# Reverse the binary representation
reversed_binary = binary[::-1]
# Convert the reversed binary representation back to decimal
reversed_decim... | [
"assert reverse_binary(15) == 15",
"assert reverse_binary(9) == 9",
"assert reverse_binary(13) == 11"
] | Certainly! Below is a Python function that takes a positive integer as an argument, converts it to its binary representation, and then returns the reverse of that binary string.
```python
def reverse_binary(n):
# Check that the input is a positive integer
if n <= 0:
raise ValueError("Input must be a po... | 10,495 | [
{
"from": "human",
"value": "Write a function that takes a positive integer as an argument and returns the reverse of its binary representation."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that takes a positive integer as an argument, converts it to its binary representa... |
Write a Python function to count the number of lists present inside a given list. | Here is the code to solve this problem:
```python
def count_lists(lst):
count = 0
for item in lst:
if isinstance(item, list):
count += 1
count += count_lists(item)
return count
``` | [
"assert count_lists([1, 2, [3, 4], 5, [6, [7, 8]]]) == 3",
"assert count_lists([[], [1, [2, [3]]]]) == 4",
"assert count_lists([1, 2, 3, 4, 5]) == 0",
"assert count_lists([[1], [2], [3], [4]]) == 4"
] | You can create a Python function that counts the number of lists present within a given list by checking each element to see if it is a list. Here's a simple implementation of this function:
```python
def count_lists(input_list):
count = 0
for element in input_list:
if isinstance(element, list):
... | 10,496 | [
{
"from": "human",
"value": "Write a Python function to count the number of lists present inside a given list."
},
{
"from": "gpt",
"value": "You can create a Python function that counts the number of lists present within a given list by checking each element to see if it is a list. Here's a sim... |
Write a python function that takes a list of unsorted integers and returns a list of integers sorted in ascending order using Merge Sort algorithm. | Here is the code to solve this problem:
```python
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
return merge(merge_sort(left_half), merge_sort(right_half))
def merge(left, right):
sorted_list = []
left_index = 0
... | [
"assert merge_sort([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]) == [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]",
"assert merge_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]",
"assert merge_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]"
] | Certainly! Below is a Python function that implements the Merge Sort algorithm to sort a list of unsorted integers in ascending order.
```python
def merge_sort(arr):
# Base case: a list of zero or one elements is already sorted
if len(arr) <= 1:
return arr
# Find the middle point to divide the... | 10,497 | [
{
"from": "human",
"value": "Write a python function that takes a list of unsorted integers and returns a list of integers sorted in ascending order using Merge Sort algorithm."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that implements the Merge Sort algorithm to sort a... |
Write a python function to find the next closest number to a given number with the same set of digits. | Here is the code to solve this problem:
```python
def nextClosest(n):
digits = list(str(n))
length = len(digits)
for i in range(length - 2, -1, -1):
if digits[i] < digits[i + 1]:
break
if i == -1:
return -1
for j in range(length - 1, i, -1):
if digits[j] > digits... | [
"assert nextClosest(1234) == 1243",
"assert nextClosest(4321) == -1",
"assert nextClosest(534976) == 536479"
] | To find the next closest number with the same set of digits as a given number, you can implement a function that uses the following approach:
1. Convert the number into a list of its digits.
2. Find the rightmost pair of consecutive digits where the first digit is less than the second digit (let's call these two digit... | 10,498 | [
{
"from": "human",
"value": "Write a python function to find the next closest number to a given number with the same set of digits."
},
{
"from": "gpt",
"value": "To find the next closest number with the same set of digits as a given number, you can implement a function that uses the following a... |
Write a Python function to find the maximum profit that can be obtained by buying and selling stocks given a list of daily prices. The function should return the maximum profit that can be achieved, assuming you can only make one transaction (i.e., buy one and sell one share of the stock), and you must buy before you s... | Here is the code to solve this problem:
```python
def calculate_max_profit(prices):
if not prices:
return 0
min_price = prices[0]
max_profit = 0
for price in prices:
min_price = min(min_price, price)
profit = price - min_price
max_profit = max(max_profit, profit)
ret... | [
"assert calculate_max_profit([7, 1, 5, 3, 6, 4]) == 5",
"assert calculate_max_profit([7, 6, 4, 3, 1]) == 0",
"assert calculate_max_profit([1, 2, 3, 4, 5]) == 4"
] | You can calculate the maximum profit from buying and selling stocks by iterating through the list of daily prices and keeping track of the minimum price found so far and the maximum profit that can be achieved. Here's how you can implement the `calculate_max_profit` function in Python:
```python
def calculate_max_prof... | 10,499 | [
{
"from": "human",
"value": "Write a Python function to find the maximum profit that can be obtained by buying and selling stocks given a list of daily prices. The function should return the maximum profit that can be achieved, assuming you can only make one transaction (i.e., buy one and sell one share of ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.