instruction_seed stringlengths 42 1.67k | response_seed stringlengths 83 5.94k | testcase listlengths 3 39 | response stringlengths 46 5.35k | __original_row_idx int64 0 50k | conversations listlengths 2 2 |
|---|---|---|---|---|---|
Write a python function to check if a given number is a perfect square. | Here is the code to solve this problem:
```python
def is_Perfect_Square(n):
if n < 0:
return False
if n == 0:
return True
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x*x == n
``` | [
"assert is_Perfect_Square(14) == False",
"assert is_Perfect_Square(16) == True",
"assert is_Perfect_Square(25) == True"
] | You can check if a given number is a perfect square by taking the square root of the number, converting it to an integer, and then squaring that integer to see if you get the original number back. Here’s a Python function to do this:
```python
import math
def is_perfect_square(n):
if n < 0:
return False ... | 4,700 | [
{
"from": "human",
"value": "Write a python function to check if a given number is a perfect square."
},
{
"from": "gpt",
"value": "You can check if a given number is a perfect square by taking the square root of the number, converting it to an integer, and then squaring that integer to see if y... |
Write a python function to validate if a given credit card number is valid or not. The validation follows the Luhn algorithm which is as follows:
1. Double every second digit from right to left. If doubling of a digit results in a two-digit number, add up the two digits to get a single-digit number.
2. Now add all sing... | Here is the code to solve this problem:
```python
def validate_credit_card(num):
num = list(map(int, str(num)))
for i in range(len(num) - 2, -1, -2):
num[i] *= 2
if num[i] > 9:
num[i] = num[i] // 10 + num[i] % 10
return sum(num) % 10 == 0
``` | [
"assert validate_credit_card(\"1234567890123456\") == False",
"assert validate_credit_card(\"6011514433546201\") == True",
"assert validate_credit_card(\"4532015112830366\") == True"
] | You can implement the Luhn algorithm in Python to validate credit card numbers with the following function:
```python
def validate_credit_card(card_number):
# Convert the card number to a string and remove any spaces or non-digit characters
card_number = ''.join(filter(str.isdigit, str(card_number)))
... | 4,701 | [
{
"from": "human",
"value": "Write a python function to validate if a given credit card number is valid or not. The validation follows the Luhn algorithm which is as follows:\n1. Double every second digit from right to left. If doubling of a digit results in a two-digit number, add up the two digits to get ... |
Write a python function to convert a given string to uppercase without using inbuilt `upper()` function. | Here is the code to solve this problem:
```python
def to_uppercase(str1):
uppercase = ""
for char in str1:
if 97 <= ord(char) <= 122:
uppercase += chr(ord(char) - 32)
else:
uppercase += char
return uppercase
``` | [
"assert to_uppercase('language')=='LANGUAGE'",
"assert to_uppercase('python')=='PYTHON'",
"assert to_uppercase('program')=='PROGRAM'"
] | You can convert a string to uppercase in Python without using the built-in `upper()` function by iterating through each character in the string and converting lowercase letters to uppercase using their ASCII values. Here's a function that does this:
```python
def to_uppercase(s):
result = ''
for char in s:
... | 4,702 | [
{
"from": "human",
"value": "Write a python function to convert a given string to uppercase without using inbuilt `upper()` function."
},
{
"from": "gpt",
"value": "You can convert a string to uppercase in Python without using the built-in `upper()` function by iterating through each character i... |
Write a python function that takes a string as input and returns the string with its digits reversed. If the string does not contain any digits, return the original string. | Here is the code to solve this problem:
```python
def reverse_digits(s):
digits = []
for char in s:
if char.isdigit():
digits.append(char)
digits = digits[::-1]
result = []
digit_index = 0
for char in s:
if char.isdigit():
result.append(digits[digit_index... | [
"assert reverse_digits(\"12345\") == \"54321\"",
"assert reverse_digits(\"abc\") == \"abc\"",
"assert reverse_digits(\"Hello123\") == \"Hello321\"",
"assert reverse_digits(\"a1b2c3\") == \"a3b2c1\""
] | Certainly! You can create a Python function that checks for digits in the input string and reverses them while keeping the other characters in their original positions. If there are no digits, it simply returns the original string.
Here's a function that accomplishes this:
```python
def reverse_digits_in_string(input... | 4,703 | [
{
"from": "human",
"value": "Write a python function that takes a string as input and returns the string with its digits reversed. If the string does not contain any digits, return the original string."
},
{
"from": "gpt",
"value": "Certainly! You can create a Python function that checks for dig... |
Write a function, `find_max_profit`, that takes in a list of stock prices and returns the maximum profit that can be made from buying and selling at most once. If no profit can be made, return 0. | Here is the code to solve this problem:
```python
def find_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)
retur... | [
"assert find_max_profit([7, 6, 4, 3, 1]) == 0",
"assert find_max_profit([1, 2, 3, 4, 5]) == 4",
"assert find_max_profit([7, 1, 5, 3, 6, 4]) == 5"
] | To solve the problem of finding the maximum profit from a list of stock prices, we can use a single pass algorithm. The idea is to keep track of the minimum price seen so far and calculate the potential profit at each price point by subtracting the minimum price from the current price. We'll update the maximum profit w... | 4,704 | [
{
"from": "human",
"value": "Write a function, `find_max_profit`, that takes in a list of stock prices and returns the maximum profit that can be made from buying and selling at most once. If no profit can be made, return 0."
},
{
"from": "gpt",
"value": "To solve the problem of finding the maxi... |
Write a python function to replace all 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,old,new):
return s.replace(old,new)
``` | [
"assert replace_substring(\"hello world\",\"world\",\"python\") == \"hello python\"",
"assert replace_substring(\"python is awesome\",\"python\",\"java\") == \"java is awesome\"",
"assert replace_substring(\"I love programming\",\"programming\",\"coding\") == \"I love coding\""
] | You can create a Python function to replace all occurrences of a given substring in a string with another substring using the built-in `str.replace()` method. Here’s a simple implementation of such a function:
```python
def replace_substring(original_string, old_substring, new_substring):
"""
Replace all occur... | 4,705 | [
{
"from": "human",
"value": "Write a python function to replace all 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 in a string with another substring using ... |
Write a python function to find the number of ways to climb a staircase with n steps, given that you can take a step of 1, 2, or 3 at a time. | Here is the code to solve this problem:
```python
def count_ways_to_climb(n):
if n == 0 or n == 1:
return 1
if n == 2:
return 2
dp = [0] * (n+1)
dp[0], dp[1], dp[2] = 1, 1, 2
for i in range(3, n+1):
dp[i] = dp[i-1] + dp[i-2] + dp[i-3]
return dp[n]
``` | [
"assert count_ways_to_climb(3) == 4",
"assert count_ways_to_climb(4) == 7",
"assert count_ways_to_climb(5) == 13"
] | You can solve the problem of climbing a staircase with `n` steps using dynamic programming. The idea is to calculate the number of ways to reach each step based on the previous three steps, since you can take 1, 2, or 3 steps at a time.
Here's a Python function that implements this logic:
```python
def count_ways(n)... | 4,706 | [
{
"from": "human",
"value": "Write a python function to find the number of ways to climb a staircase with n steps, given that you can take a step of 1, 2, or 3 at a time."
},
{
"from": "gpt",
"value": "You can solve the problem of climbing a staircase with `n` steps using dynamic programming. Th... |
Write a python function to find duplicated elements in a list of strings. The strings represent paths to files, and the function should return a list of lists, where each inner list contains paths to files that have the same content.
For example, if the input list is ['root/a 1.txt(abcd)', 'root/c 3.txt(abcd)', 'root/... | Here is the code to solve this problem:
```python
from collections import defaultdict
def find_duplicate(paths):
hash_map = defaultdict(list)
for path in paths:
path_list = path.split(" ")
n = len(path_list)
for i in range(1,n):
idx = path_list[i].index("(")
has... | [
"assert find_duplicate(['root/a 1.txt(abcd)', 'root/b 2.txt(abcd)', 'root/c 3.txt(abcd)', 'root/d 4.txt(abcd)', 'root/e 5.txt(abcd)'])==[['root/a/1.txt', 'root/b/2.txt', 'root/c/3.txt', 'root/d/4.txt', 'root/e/5.txt']]",
"assert find_duplicate(['root/a 1.txt(abcd)', 'root/c 3.txt(abcd)', 'root/c 4.txt(efgh)', 'ro... | To find duplicated elements in a list of strings representing file paths, we can follow these steps:
1. Parse each string to extract the file path and its content.
2. Use a dictionary to map the content to a list of file paths.
3. Finally, filter out the entries in the dictionary where the list of file paths has more ... | 4,707 | [
{
"from": "human",
"value": "Write a python function to find duplicated elements in a list of strings. The strings represent paths to files, and the function should return a list of lists, where each inner list contains paths to files that have the same content.\n\nFor example, if the input list is ['root/a... |
Write a function in Python that takes a list of tuples representing a linked list and an index, then returns the value of the node at that index. If the index is out of bounds, return 'Index out of bounds'. | Here is the code to solve this problem:
```python
def get_node_val(linked_list, index):
if index < 0 or index >= len(linked_list):
return 'Index out of bounds'
return linked_list[index][1]
``` | [
"assert get_node_val([(1, 2), (3, 4), (5, 6)], 1) == 4",
"assert get_node_val([(13, 14), (15, 16), (17, 18)], 2) == 18",
"assert get_node_val([(7, 8), (9, 10), (11, 12)], 0) == 8",
"assert get_node_val([(19, 20), (21, 22), (23, 24)], 3) == 'Index out of bounds'"
] | Certainly! Below is a Python function that takes a list of tuples representing a linked list and an index. The function returns the value of the node at that index, or 'Index out of bounds' if the index is invalid.
In this implementation, we will assume that each tuple in the list contains two elements: the value of t... | 4,708 | [
{
"from": "human",
"value": "Write a function in Python that takes a list of tuples representing a linked list and an index, then returns the value of the node at that index. If the index is out of bounds, return 'Index out of bounds'."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python ... |
Write a function to find the intersection of two sets. | Here is the code to solve this problem:
```python
def set_intersection(set1, set2):
return set1 & set2
``` | [
"assert set_intersection({1, 2, 3, 4, 5}, {4, 5, 6, 7, 8})=={4, 5}",
"assert set_intersection({10, 20, 30, 40, 50}, {20, 30, 50, 60, 70})=={20, 30, 50}",
"assert set_intersection({1, 2, 3}, {4, 5, 6})==set()"
] | You can find the intersection of two sets in Python using the built-in `set` data type. Here is a simple function that achieves this:
```python
def intersect_sets(set1, set2):
"""
Returns the intersection of two sets.
Parameters:
set1 (set): The first set.
set2 (set): The second set.
... | 4,709 | [
{
"from": "human",
"value": "Write a function to find the intersection of two sets."
},
{
"from": "gpt",
"value": "You can find the intersection of two sets in Python using the built-in `set` data type. Here is a simple function that achieves this:\n\n```python\ndef intersect_sets(set1, set2):\n... |
Write a function to check if a given sentence is a pangram. A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence "The quick brown fox jumps over the lazy dog" is a pangram, because it uses the letters A-Z at least once (case is irrelevant). | Here is the code to solve this problem:
```python
def checkIfPangram(sentence):
alphabet_set = set('abcdefghijklmnopqrstuvwxyz')
sentence_set = set(sentence.lower())
return alphabet_set.issubset(sentence_set)
``` | [
"assert checkIfPangram(\"thequickbrownfoxjumpsoverthelazydog\")==True",
"assert checkIfPangram(\"abcdefghijklmnopqrstuvwxyz\")==True",
"assert checkIfPangram(\"thissentenceisnotapangram\")==False",
"assert checkIfPangram(\"thisisaverylongsentencebutitisnotapangrambecauseitdoesnotcontaineveryletterofthealphabe... | You can check if a sentence is a pangram by writing a function that examines whether all letters from 'a' to 'z' are present in the input string. Below is a Python function that accomplishes this:
```python
def is_pangram(sentence):
# Define the alphabet set
alphabet = set('abcdefghijklmnopqrstuvwxyz')
... | 4,710 | [
{
"from": "human",
"value": "Write a function to check if a given sentence is a pangram. A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence \"The quick brown fox jumps over the lazy dog\" is a pangram, because it uses the letters A-Z at least o... |
Write a function to find the maximum product of the adjacent elements after decrementing each element by 1 in a given list of integers. | Here is the code to solve this problem:
```python
def product_after_decrement(nums):
nums.sort()
return max((x-1)*(y-1) for x, y in zip(nums[:-1], nums[1:]))
assert product_after_decrement([3,4,5,2])==12
assert product_after_decrement([1,5,4,5])==16
assert product_after_decrement([3,7])==12
``` | [
"assert product_after_decrement([1,5,4,5])==16",
"assert product_after_decrement([3,4,5,2])==12",
"assert product_after_decrement([3,7])==12"
] | You can achieve this by creating a function that first decrements each element in the list by 1, and then computes the maximum product of adjacent elements in the modified list. Here is a Python function that implements this approach:
```python
def max_product_of_adjacent_decremented(arr):
# Decrement each element... | 4,711 | [
{
"from": "human",
"value": "Write a function to find the maximum product of the adjacent elements after decrementing each element by 1 in a given list of integers."
},
{
"from": "gpt",
"value": "You can achieve this by creating a function that first decrements each element in the list by 1, and... |
Write a function to check if a given string can be segmented into a space-separated sequence of one or more dictionary words. | Here is the code to solve this problem:
```python
def word_segment(s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
dpi 前i个元素为结尾的子串是否能拆分
"""
if not wordDict:
return False
dp = [False for _ in range(len(s) + 1)]
dp[0] = True
wordDict = set(wordDict)
... | [
"assert word_segment(\"catsandog\", [\"cats\", \"dog\", \"sand\", \"and\", \"cat\"]) == False",
"assert word_segment(\"applepenapple\", [\"apple\", \"pen\"]) == True",
"assert word_segment(\"leetcode\", [\"leet\", \"code\"]) == True"
] | You can solve the problem of checking if a given string can be segmented into a space-separated sequence of words from a dictionary using dynamic programming.
The basic idea is to iterate through the string and at each index, check if there's a dictionary word that ends at that index. If such a word is found, then che... | 4,712 | [
{
"from": "human",
"value": "Write a function to check if a given string can be segmented into a space-separated sequence of one or more dictionary words."
},
{
"from": "gpt",
"value": "You can solve the problem of checking if a given string can be segmented into a space-separated sequence of wo... |
Write a function to find the number of buses required to reach a destination from a source, given the routes of the buses. Each route is a list of stops. The function should return the minimum number of buses required to reach the destination, or -1 if it is not possible. | Here is the code to solve this problem:
```python
from collections import defaultdict
def num_buses_to_destination(routes, source, target):
if source == target: return 0
if source not in {stop for route in routes for stop in route}: return -1
graph = defaultdict(set)
for i, route in enumerate(routes)... | [
"assert num_buses_to_destination([[1, 2, 7], [3, 6, 7]], 1, 6) == 2",
"assert num_buses_to_destination([[7, 12], [4, 5, 15], [6], [15, 19], [9, 12, 13]], 15, 12) == -1",
"assert num_buses_to_destination([[1, 7], [3, 2], [3, 4], [5, 6], [7, 6]], 1, 6) == 2"
] | To solve the problem of finding the minimum number of buses required to reach a destination from a source given a list of bus routes, you can utilize a graph traversal approach, specifically the Breadth-First Search (BFS) algorithm. Each bus route can be considered as a node, and you can connect different bus routes th... | 4,713 | [
{
"from": "human",
"value": "Write a function to find the number of buses required to reach a destination from a source, given the routes of the buses. Each route is a list of stops. The function should return the minimum number of buses required to reach the destination, or -1 if it is not possible."
},
... |
Write a Python function that takes a list of integers as input and returns the list sorted in ascending order using the Bubble Sort algorithm. | Here is the code to solve this problem:
```python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
``` | [
"assert bubble_sort([5, 1, 4, 2, 8]) == [1, 2, 4, 5, 8]",
"assert bubble_sort([64, 34, 25, 12, 22, 11, 90]) == [11, 12, 22, 25, 34, 64, 90]",
"assert bubble_sort([3, 0, 2, 5, -1, 4, 1]) == [-1, 0, 1, 2, 3, 4, 5]"
] | Certainly! Below is a Python function that implements the Bubble Sort algorithm to sort a list of integers in ascending order:
```python
def bubble_sort(arr):
n = len(arr)
# Traverse through all elements in the list
for i in range(n):
# Last i elements are already in place, no need to check them
... | 4,714 | [
{
"from": "human",
"value": "Write a Python function that takes a list of integers as input and returns the list sorted in ascending order using the Bubble Sort algorithm."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that implements the Bubble Sort algorithm to sort a lis... |
Write a python function to find the number of unique triplets in an array that sum up to zero. | Here is the code to solve this problem:
```python
def find_triplets(nums):
nums.sort()
n = len(nums)
triplets = 0
for i in range(n):
if i > 0 and nums[i] == nums[i-1]:
continue
l, r = i+1, n-1
while l < r:
s = nums[i] + nums[l] + nums[r]
if s ... | [
"assert find_triplets([0, 0, 0, 0]) == 1",
"assert find_triplets([0, 1, 1]) == 0",
"assert find_triplets([-1, 0, 1, 2, -1, -4]) == 2"
] | To find the number of unique triplets in an array that sum up to zero, we can use a combination of sorting and a two-pointer approach. Here's a Python function that implements this logic:
```python
def three_sum(nums):
nums.sort() # Sort the array
triplets = set() # Use a set to store unique triplets
n =... | 4,715 | [
{
"from": "human",
"value": "Write a python function to find the number of unique triplets in an array that sum up to zero."
},
{
"from": "gpt",
"value": "To find the number of unique triplets in an array that sum up to zero, we can use a combination of sorting and a two-pointer approach. Here's... |
Write a function to find the height of a binary tree. | Here is the code to solve this problem:
```python
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def tree_height(root: Optional[TreeNode]) -> int:
if not root:
return 0
return... | [
"assert tree_height(TreeNode(1))==1",
"assert tree_height(TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3)))==3",
"assert tree_height(TreeNode(1, TreeNode(2), TreeNode(3)))==2"
] | To find the height of a binary tree, we can use a recursive approach where we compute the height of the left and right subtrees and then determine the height of the tree based on the heights of these subtrees. The height of a binary tree is defined as the number of edges on the longest path from the root node to a leaf... | 4,716 | [
{
"from": "human",
"value": "Write a function to find the height of a binary tree."
},
{
"from": "gpt",
"value": "To find the height of a binary tree, we can use a recursive approach where we compute the height of the left and right subtrees and then determine the height of the tree based on the... |
Write a python function to find the maximum consecutive ones in a binary array. | Here is the code to solve this problem:
```python
def find_max_consecutive_ones(nums):
max_ones = 0
current_ones = 0
for num in nums:
if num == 1:
current_ones += 1
max_ones = max(max_ones, current_ones)
else:
current_ones = 0
return max_ones
``` | [
"assert find_max_consecutive_ones([1, 1, 0, 1, 1, 1]) == 3",
"assert find_max_consecutive_ones([1,0,1,1,0,1]) == 2",
"assert find_max_consecutive_ones([0,0,0,0]) == 0"
] | Certainly! You can find the maximum number of consecutive ones in a binary array using a simple Python function. Here's a function that accomplishes that:
```python
def max_consecutive_ones(binary_array):
max_count = 0
current_count = 0
for num in binary_array:
if num == 1:
current_cou... | 4,717 | [
{
"from": "human",
"value": "Write a python function to find the maximum consecutive ones in a binary array."
},
{
"from": "gpt",
"value": "Certainly! You can find the maximum number of consecutive ones in a binary array using a simple Python function. Here's a function that accomplishes that:\n... |
Write a python function to find the length of the longest increasing subsequence in a given list of numbers. | Here is the code to solve this problem:
```python
def length_of_LIS(nums):
if not nums:
return 0
tails = [0] * len(nums)
size = 0
for x in nums:
i, j = 0, size
while i != j:
m = (i + j) // 2
if tails[m] < x:
i = m + 1
else:
... | [
"assert length_of_LIS([7, 7, 7, 7, 7, 7, 7])==1",
"assert length_of_LIS([0, 1, 0, 3, 2, 3])==4",
"assert length_of_LIS([10, 9, 2, 5, 3, 7, 101, 18])==4"
] | Certainly! Here is a Python function that finds the length of the longest increasing subsequence (LIS) in a given list of numbers. This function uses dynamic programming to efficiently calculate the result.
```python
def length_of_lis(nums):
if not nums:
return 0
# dp[i] will hold the length of th... | 4,718 | [
{
"from": "human",
"value": "Write a python function to find the length of the longest increasing subsequence in a given list of numbers."
},
{
"from": "gpt",
"value": "Certainly! Here is a Python function that finds the length of the longest increasing subsequence (LIS) in a given list of numbe... |
Write a function to find the largest binary gap within a positive integer N. A binary gap is the maximum sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. | Here is the code to solve this problem:
```python
def binary_gap(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
current_gap = 0
... | [
"assert binary_gap(9) == 2",
"assert binary_gap(20) == 1",
"assert binary_gap(529) == 4",
"assert binary_gap(15) == 0"
] | To find the largest binary gap in a positive integer \( N \), we first need to convert the number into its binary representation, then identify the gaps of zeros that are surrounded by ones. Here's how you can implement this in Python:
```python
def largest_binary_gap(N):
# Convert the number to binary representat... | 4,719 | [
{
"from": "human",
"value": "Write a function to find the largest binary gap within a positive integer N. A binary gap is the maximum sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N."
},
{
"from": "gpt",
"value": "To find the largest binary... |
Write a python function to check if a given word can be typed using only one row of a QWERTY keyboard. | Here is the code to solve this problem:
```python
def check_one_row_word(word):
row1 = set('qwertyuiop')
row2 = set('asdfghjkl')
row3 = set('zxcvbnm')
word = word.lower()
if set(word) <= row1 or set(word) <= row2 or set(word) <= row3:
return True
else:
return False
``` | [
"assert check_one_row_word(\"Dad\")==True",
"assert check_one_row_word(\"Alaska\")==True",
"assert check_one_row_word(\"Hello\")==False"
] | Certainly! To determine if a given word can be typed using only one row of a QWERTY keyboard, we can create a function that compares each character of the word to the characters in each row of the keyboard.
The QWERTY keyboard is typically laid out as follows:
- Top row: "qwertyuiop"
- Home row: "asdfghjkl"
- Bottom ... | 4,720 | [
{
"from": "human",
"value": "Write a python function to check if a given word can be typed using only one row of a QWERTY keyboard."
},
{
"from": "gpt",
"value": "Certainly! To determine if a given word can be typed using only one row of a QWERTY keyboard, we can create a function that compares ... |
Write a python function to find the kth smallest element in an unsorted array using the QuickSelect algorithm. | Here is the code to solve this problem:
```python
def quickSelect(arr, k):
def partition(left, right, pivot_index):
pivot = arr[pivot_index]
arr[pivot_index], arr[right] = arr[right], arr[pivot_index]
store_index = left
for i in range(left, right):
if arr[i] < pivot:
... | [
"assert quickSelect([3,2,1], 2) == 2",
"assert quickSelect([7, 10, 4, 3, 20, 15], 3) == 7",
"assert quickSelect([0,1,2,1], 1) == 0"
] | Certainly! The QuickSelect algorithm is an efficient way to find the k-th smallest (or largest) element in an unsorted array with an average time complexity of O(n). Below is a Python function implementing the QuickSelect algorithm to find the k-th smallest element in an unsorted array:
```python
import random
def pa... | 4,721 | [
{
"from": "human",
"value": "Write a python function to find the kth smallest element in an unsorted array using the QuickSelect algorithm."
},
{
"from": "gpt",
"value": "Certainly! The QuickSelect algorithm is an efficient way to find the k-th smallest (or largest) element in an unsorted array ... |
Write a python function to find the single number in an array of integers where every element appears twice except for one. Your function should return the single number. | Here is the code to solve this problem:
```python
def find_single_number(nums):
"""
Finds the single number in an array where every other number appears twice.
:param nums: List[int] -- List of integers where every element appears twice except for one.
:return: int -- The single number that appears on... | [
"assert find_single_number([2, 2, 1]) == 1",
"assert find_single_number([4, 1, 2, 1, 2]) == 4",
"assert find_single_number([1]) == 1"
] | You can solve this problem efficiently using the XOR operation. The idea is that when you XOR two identical numbers, they cancel each other out (i.e., `x ^ x = 0`), and when you XOR a number with 0, it remains unchanged (i.e., `x ^ 0 = x`). Therefore, if you XOR all the numbers in the array together, the result will be... | 4,722 | [
{
"from": "human",
"value": "Write a python function to find the single number in an array of integers where every element appears twice except for one. Your function should return the single number."
},
{
"from": "gpt",
"value": "You can solve this problem efficiently using the XOR operation. T... |
Write a python function to find the smallest missing positive integer from an unsorted array. | Here is the code to solve this problem:
```python
def smallestMissingPositive(nums):
max_size = len(nums)
for i in range(max_size):
while 1 <= nums[i] <= max_size and nums[nums[i] - 1] != nums[i]:
nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]
for i in range(max_size):
... | [
"assert smallestMissingPositive([7, 8, 9, 11, 12]) == 1",
"assert smallestMissingPositive([1, 2, 0]) == 3",
"assert smallestMissingPositive([3, 4, -1, 1]) == 2"
] | You can find the smallest missing positive integer from an unsorted array using a set to keep track of the positive integers in the array. Here's a Python function that implements this approach:
```python
def find_smallest_missing_positive(nums):
if not nums:
return 1
# Create a set of the numbers in ... | 4,723 | [
{
"from": "human",
"value": "Write a python function to find the smallest missing positive integer from an unsorted array."
},
{
"from": "gpt",
"value": "You can find the smallest missing positive integer from an unsorted array using a set to keep track of the positive integers in the array. Her... |
Write a python function to check if a given string contains all the substrings from a given list. | Here is the code to solve this problem:
```python
def check_substrings(string, substrings):
for substring in substrings:
if substring not in string:
return False
return True
``` | [
"assert check_substrings(\"hello world\", [\"hello\", \"world\"]) == True",
"assert check_substrings(\"good morning\", [\"good\", \"afternoon\"]) == False",
"assert check_substrings(\"python programming\", [\"python\", \"programming\", \"code\"]) == False"
] | Certainly! To create a Python function that checks if a given string contains all the substrings from a specified list, you can follow this approach:
1. Define a function that takes two parameters: the input string and the list of substrings.
2. Iterate through each substring in the list and check if it is present in ... | 4,724 | [
{
"from": "human",
"value": "Write a python function to check if a given string contains all the substrings from a given list."
},
{
"from": "gpt",
"value": "Certainly! To create a Python function that checks if a given string contains all the substrings from a specified list, you can follow thi... |
Write a python function to find the median of two sorted arrays. The overall run time complexity should be O(log(min(m,n))). | Here is the code to solve this problem:
```python
from typing import List
def findMedianSortedArrays(nums1: List[int], nums2: List[int]) -> float:
n, m = len(nums1), len(nums2)
if n > m:
nums1, nums2, n, m = nums2, nums1, m, n
imin, imax, half_len = 0, n, (m + n + 1) // 2
while imin <= imax:
... | [
"assert findMedianSortedArrays([1, 3], [2]) == 2.0",
"assert findMedianSortedArrays([1,3], [2,7,9]) == 3.0",
"assert findMedianSortedArrays([1, 2], [3, 4]) == 2.5"
] | To find the median of two sorted arrays in O(log(min(m,n))) time complexity, you can use a binary search approach. Here is the Python function that implements this algorithm:
```python
def findMedianSortedArrays(nums1, nums2):
# Ensure nums1 is the smaller array
if len(nums1) > len(nums2):
nums1, nums2... | 4,725 | [
{
"from": "human",
"value": "Write a python function to find the median of two sorted arrays. The overall run time complexity should be O(log(min(m,n)))."
},
{
"from": "gpt",
"value": "To find the median of two sorted arrays in O(log(min(m,n))) time complexity, you can use a binary search approa... |
Write a python function to find the sub-array with the maximum sum from all sub-arrays using Kadane's algorithm. | Here is the code to solve this problem:
```python
def max_sub_array(nums):
if not nums:
return 0
cur_sum = max_sum = nums[0]
for num in nums[1:]:
cur_sum = max(num, cur_sum + num)
max_sum = max(max_sum, cur_sum)
return max_sum
``` | [
"assert max_sub_array([-2,1,-3,4,-1,2,1,-5,4]) == 6",
"assert max_sub_array([5,4,-1,7,8]) == 23",
"assert max_sub_array([1]) == 1"
] | Sure! Kadane's algorithm is an efficient way to find the maximum sum sub-array in linear time. Below is a Python function that implements Kadane's algorithm:
```python
def max_sub_array(arr):
if not arr:
return 0 # Return 0 if the array is empty
max_current = max_global = arr[0]
for i in range(1... | 4,726 | [
{
"from": "human",
"value": "Write a python function to find the sub-array with the maximum sum from all sub-arrays using Kadane's algorithm."
},
{
"from": "gpt",
"value": "Sure! Kadane's algorithm is an efficient way to find the maximum sum sub-array in linear time. Below is a Python function t... |
Write a function that accepts a list of strings and returns a dictionary where the keys are the unique strings from the list and the values are the number of occurrences of each string. | Here is the code to solve this problem:
```python
def count_strings(lst):
result = {}
for word in lst:
if word in result:
result[word] += 1
else:
result[word] = 1
return result
``` | [
"assert count_strings([\"apple\", \"orange\", \"apple\", \"banana\", \"apple\"]) == {\"apple\": 3, \"orange\": 1, \"banana\": 1}",
"assert count_strings([\"a\", \"b\", \"c\", \"a\", \"b\", \"a\"]) == {\"a\": 3, \"b\": 2, \"c\": 1}",
"assert count_strings([\"hello\", \"world\", \"hello\", \"python\"]) == {\"hell... | You can create a function in Python that accomplishes this using a simple loop or the `collections.Counter` class. Here's an example of how to implement such a function:
```python
def count_occurrences(string_list):
"""
Count the occurrences of each string in the provided list.
:param string_list: List of... | 4,727 | [
{
"from": "human",
"value": "Write a function that accepts a list of strings and returns a dictionary where the keys are the unique strings from the list and the values are the number of occurrences of each string."
},
{
"from": "gpt",
"value": "You can create a function in Python that accomplis... |
Write a python function to find the next greater element for each element in the given list. If no such element exists, return -1 for that index. | Here is the code to solve this problem:
```python
def next_greater_element(lst):
res = [-1] * len(lst)
stack = []
for i in range(len(lst)):
while stack and lst[stack[-1]] < lst[i]:
cur = stack.pop()
res[cur] = lst[i]
stack.append(i)
return res
``` | [
"assert next_greater_element([1, 2, 3, 4]) == [2, 3, 4, -1]",
"assert next_greater_element([2, 1, 2, 4, 3]) == [4, 2, 4, -1, -1]",
"assert next_greater_element([4, 3, 2, 1]) == [-1, -1, -1, -1]"
] | You can solve the problem of finding the next greater element for each element in a given list by using a stack. The idea is to traverse the list from right to left and use the stack to keep track of the elements for which we are still looking for the next greater element. Here is a function that implements this logic:... | 4,728 | [
{
"from": "human",
"value": "Write a python function to find the next greater element for each element in the given list. If no such element exists, return -1 for that index."
},
{
"from": "gpt",
"value": "You can solve the problem of finding the next greater element for each element in a given ... |
Write a function to find the number of days in a given month of a given year, taking into account leap years. | Here is the code to solve this problem:
```python
def is_leap_year(year: int) -> bool:
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def days_in_month(year: int, month: int) -> int:
if month in [4, 6, 9, 11]:
return 30
if month == 2:
return 29 if is_leap_year(year) else 28
... | [
"assert days_in_month(2019, 2) == 28",
"assert days_in_month(2020, 2) == 29",
"assert days_in_month(2020, 4) == 30"
] | Sure! Below is a Python function that takes a month and a year as input and returns the number of days in that month, properly accounting for leap years.
```python
def days_in_month(year, month):
# Validate the input month
if month < 1 or month > 12:
return "Invalid month. Month must be between 1 and 1... | 4,729 | [
{
"from": "human",
"value": "Write a function to find the number of days in a given month of a given year, taking into account leap years."
},
{
"from": "gpt",
"value": "Sure! Below is a Python function that takes a month and a year as input and returns the number of days in that month, properly... |
Write a python function to find the total number of ways to reach the top of a staircase, given that you can climb either 1 or 2 steps at a time. | Here is the code to solve this problem:
```python
def stairs_climb(n):
if n <= 1:
return n
first, second = 1, 2
for i in range(2, n):
first, second = second, first + second
return second
``` | [
"assert stairs_climb(3) == 3",
"assert stairs_climb(4) == 5",
"assert stairs_climb(5) == 8"
] | To solve the problem of finding the total number of ways to reach the top of a staircase where you can climb either 1 or 2 steps at a time, you can think of it recursively.
The number of ways to reach the top of a staircase of height `n` can be expressed as:
- If you take one step from `n-1`, the number of ways to re... | 4,730 | [
{
"from": "human",
"value": "Write a python function to find the total number of ways to reach the top of a staircase, given that you can climb either 1 or 2 steps at a time."
},
{
"from": "gpt",
"value": "To solve the problem of finding the total number of ways to reach the top of a staircase w... |
Write a function to check if a given matrix is a magic square. A magic square is a square matrix in which the sums of every row, every column, and both main diagonals are all equal. The function should return True if the matrix is a magic square and False otherwise. | Here is the code to solve this problem:
```python
def is_magic_square(matrix):
n = len(matrix)
if n == 0:
return False
# Calculate the sum of the first row to use as a reference
magic_sum = sum(matrix[0])
# Check sums of rows
for row in matrix:
if sum(row) != magic_sum:
... | [
"assert is_magic_square([[2, 7, 6], [9, 5, 1], [4, 3, 8]]) == True",
"assert is_magic_square([[4, 9, 2], [3, 5, 7], [8, 1, 6]]) == True",
"assert is_magic_square([[16, 23, 17], [75, 14, 1], [15, 8, 1]]) == False"
] | Certainly! Below is a Python function that checks if a given matrix is a magic square:
```python
def is_magic_square(matrix):
# Check if the matrix is square
if not matrix or len(matrix) != len(matrix[0]):
return False
n = len(matrix)
# Calculate the sum of the first row as the magic ... | 4,731 | [
{
"from": "human",
"value": "Write a function to check if a given matrix is a magic square. A magic square is a square matrix in which the sums of every row, every column, and both main diagonals are all equal. The function should return True if the matrix is a magic square and False otherwise."
},
{
... |
Write a python function to find all substrings of a given string. | Here is the code to solve this problem:
```python
def find_substrings(s):
substrings = []
for i in range(len(s)):
for j in range(i+1, len(s)+1):
substrings.append(s[i:j])
return substrings
``` | [
"assert find_substrings(\"abc\") == [\"a\", \"ab\", \"abc\", \"b\", \"bc\", \"c\"]",
"assert find_substrings(\"xyz\") == [\"x\", \"xy\", \"xyz\", \"y\", \"yz\", \"z\"]",
"assert find_substrings(\"a\") == [\"a\"]"
] | You can create a Python function to find all substrings of a given string using nested loops. Here's a simple implementation:
```python
def all_substrings(s):
"""Return a list of all substrings of the given string."""
substrings = []
length = len(s)
for i in range(length):
for j in range(i... | 4,732 | [
{
"from": "human",
"value": "Write a python function to find all substrings of a given string."
},
{
"from": "gpt",
"value": "You can create a Python function to find all substrings of a given string using nested loops. Here's a simple implementation:\n\n```python\ndef all_substrings(s):\n \"... |
Write a function to find the nth heptagonal number. A heptagonal number represents a figurate number that extends the concept of triangular and square numbers to the heptagon. The nth heptagonal number is given by the formula: H_n = n(5n - 3)/2. | Here is the code to solve this problem:
```python
def is_heptagonal(n):
return n * (5 * n - 3) // 2
``` | [
"assert is_heptagonal(2) == 7",
"assert is_heptagonal(1) == 1",
"assert is_heptagonal(3) == 18",
"assert is_heptagonal(5) == 55",
"assert is_heptagonal(4) == 34"
] | To find the nth heptagonal number using the provided formula \( H_n = \frac{n(5n - 3)}{2} \), we can create a simple function in Python. Here's how you can write this function:
```python
def heptagonal_number(n):
"""Calculate the nth heptagonal number."""
if n < 1:
raise ValueError("n must be a positiv... | 4,733 | [
{
"from": "human",
"value": "Write a function to find the nth heptagonal number. A heptagonal number represents a figurate number that extends the concept of triangular and square numbers to the heptagon. The nth heptagonal number is given by the formula: H_n = n(5n - 3)/2."
},
{
"from": "gpt",
... |
Create a function to reverse the words in a sentence while keeping the order of the words intact. | Here is the code to solve this problem:
```python
def reverse_words_in_sentence(sentence):
words = sentence.split()
reversed_words = [word[::-1] for word in words]
return ' '.join(reversed_words)
``` | [
"assert reverse_words_in_sentence(\"Hello world\") == \"olleH dlrow\"",
"assert reverse_words_in_sentence(\"Coding is fun\") == \"gnidoC si nuf\"",
"assert reverse_words_in_sentence(\"The quick brown fox\") == \"ehT kciuq nworb xof\""
] | Certainly! If you want to reverse the individual characters in each word while keeping the order of the words intact in a sentence, you can use the following Python function:
```python
def reverse_words_in_sentence(sentence):
# Split the sentence into words
words = sentence.split()
# Reverse each word... | 4,734 | [
{
"from": "human",
"value": "Create a function to reverse the words in a sentence while keeping the order of the words intact."
},
{
"from": "gpt",
"value": "Certainly! If you want to reverse the individual characters in each word while keeping the order of the words intact in a sentence, you ca... |
Write a function to check if a given list of numbers is in strictly ascending order. A list is in strictly ascending order if each element is greater than the preceding one and there are no duplicate elements. If the list meets this condition, return True; otherwise, return False. | Here is the code to solve this problem:
```python
def is_strictly_ascending(lst):
if len(lst) <= 1:
return True
for i in range(1, len(lst)):
if lst[i] <= lst[i-1]:
return False
return True
``` | [
"assert is_strictly_ascending([1, 2, 4, 6, 8]) == True",
"assert is_strictly_ascending([1, 2, 2, 3, 4]) == False",
"assert is_strictly_ascending([1]) == True",
"assert is_strictly_ascending([]) == True",
"assert is_strictly_ascending([1, 1, 1, 1, 1]) == False",
"assert is_strictly_ascending([1, 3, 5, 7, 9... | Certainly! Below is a Python function that checks if a given list of numbers is in strictly ascending order:
```python
def is_strictly_ascending(numbers):
# Loop through the list and check if each element is greater than the previous one
for i in range(1, len(numbers)):
if numbers[i] <= numbers[i - 1]:... | 4,735 | [
{
"from": "human",
"value": "Write a function to check if a given list of numbers is in strictly ascending order. A list is in strictly ascending order if each element is greater than the preceding one and there are no duplicate elements. If the list meets this condition, return True; otherwise, return Fals... |
Write a python function to check if a given list of integers is sorted in ascending order. | Here is the code to solve this problem:
```python
def is_sorted(nums):
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
return False
return True
``` | [
"assert is_sorted([1, 2, 3, 4, 5]) == True",
"assert is_sorted([1, 3, 2, 4, 5]) == False",
"assert is_sorted([5, 4, 3, 2, 1]) == False"
] | You can create a simple Python function to check if a list of integers is sorted in ascending order by comparing each element with the next one. Here's a function that does that:
```python
def is_sorted_ascending(lst):
"""
Check if the given list of integers is sorted in ascending order.
Parameters:
... | 4,736 | [
{
"from": "human",
"value": "Write a python function to check if a given list of integers is sorted in ascending order."
},
{
"from": "gpt",
"value": "You can create a simple Python function to check if a list of integers is sorted in ascending order by comparing each element with the next one. ... |
Write a function to find the number of times a substring appears in a string, including overlapping occurrences. | Here is the code to solve this problem:
```python
def substring_count(string, substring):
count = 0
start = 0
while True:
start = string.find(substring, start) + 1
if start > 0:
count += 1
else:
return count
``` | [
"assert substring_count(\"banana\", \"ana\") == 2",
"assert substring_count(\"hello\", \"l\") == 2",
"assert substring_count(\"mississippi\", \"issi\") == 2"
] | You can find the number of times a substring appears in a string, including overlapping occurrences, using a Python function. Here's how you can do it:
```python
def count_overlapping_substrings(string, substring):
count = 0
start = 0
while True:
# Find the next occurrence of the substring
... | 4,737 | [
{
"from": "human",
"value": "Write a function to find the number of times a substring appears in a string, including overlapping occurrences."
},
{
"from": "gpt",
"value": "You can find the number of times a substring appears in a string, including overlapping occurrences, using a Python functio... |
Write a python function to find the prime numbers in a given range. | Here is the code to solve this problem:
```python
def find_prime_numbers(start, end):
prime_numbers = []
for num in range(start, end + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
prime_numbers.append(... | [
"assert find_prime_numbers(11, 20) == [11, 13, 17, 19]",
"assert find_prime_numbers(1, 10) == [2, 3, 5, 7]",
"assert find_prime_numbers(22, 30) == [23, 29]"
] | Certainly! A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. In other words, a prime number has no positive divisors other than 1 and itself.
Here's a simple Python function to find all prime numbers in a given range:
```python
def is_prime(num):
"... | 4,738 | [
{
"from": "human",
"value": "Write a python function to find the prime numbers in a given range."
},
{
"from": "gpt",
"value": "Certainly! A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. In other words, a prime number has no pos... |
Write a python function to generate all possible combinations of parentheses.
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
] | Here is the code to solve this problem:
```python
def generate_parentheses(n):
def generate(p, left, right, parens=[]):
if left: generate(p + '(', left-1, right)
if right > left: generate(p + ')', left, right-1)
if not right: parens.append(p)
return parens
return gene... | [
"assert generate_parentheses(3) == [\"((()))\", \"(()())\", \"(())()\", \"()(())\", \"()()()\"]",
"assert generate_parentheses(2) == [\"(())\", \"()()\"]",
"assert generate_parentheses(1) == [\"()\"]"
] | You can generate all possible combinations of well-formed parentheses using a backtracking approach. Here's how you can implement this in Python:
```python
def generate_parenthesis(n):
def backtrack(current, open_count, close_count):
if len(current) == 2 * n:
result.append(current)
... | 4,739 | [
{
"from": "human",
"value": "Write a python function to generate all possible combinations of parentheses.\n\nGiven n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.\n\nFor example, given n = 3, a solution set is:\n\n[\n \"((()))\",\n \"(()())\",\n \"(())()... |
Write a python function to replace all occurrences of a substring in a given string with another substring. | Here is the code to solve this problem:
```python
def replace_substring(string, old_substring, new_substring):
return string.replace(old_substring, new_substring)
``` | [
"assert replace_substring(\"Hello World\", \"World\", \"Python\") == \"Hello Python\"",
"assert replace_substring(\"Hello World World\", \"World\", \"Python\") == \"Hello Python Python\"",
"assert replace_substring(\"Hello\", \"World\", \"Python\") == \"Hello\""
] | You can create a Python function to replace all occurrences of a substring in a given string with another substring using the built-in `str.replace()` method. Here’s an example of such a function:
```python
def replace_substring(original_string, old_substring, new_substring):
"""
Replace all occurrences of old... | 4,740 | [
{
"from": "human",
"value": "Write a python function to replace all occurrences of a substring in a given string with another substring."
},
{
"from": "gpt",
"value": "You can create a Python function to replace all occurrences of a substring in a given string with another substring using the bu... |
Write a python function to generate all possible permutations of a given string. | Here is the code to solve this problem:
```python
def str_permutations(str1):
if len(str1) == 1:
return [str1]
permutations = []
for i in range(len(str1)):
char = str1[i]
remaining = str1[:i] + str1[i+1:]
for perm in str_permutations(remaining):
permutations.appe... | [
"assert str_permutations('a') == ['a']",
"assert str_permutations('ab') == ['ab', 'ba']",
"assert str_permutations('abc') == ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']"
] | Certainly! You can use the `itertools` module in Python, which provides a convenient function called `permutations` to generate permutations of a given iterable. Here's how you can create a function to generate all possible permutations of a given string:
```python
from itertools import permutations
def generate_perm... | 4,741 | [
{
"from": "human",
"value": "Write a python function to generate all possible permutations of a given string."
},
{
"from": "gpt",
"value": "Certainly! You can use the `itertools` module in Python, which provides a convenient function called `permutations` to generate permutations of a given ite... |
Write a function to calculate the Levenshtein distance between two strings. The Levenshtein distance is a string metric for measuring the difference between two sequences. It is calculated as the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one word into the othe... | Here is the code to solve this problem:
```python
def calculate_levenshtein_distance(str1, str2):
len_str1 = len(str1)
len_str2 = len(str2)
distance = [[0 for _ in range(len_str2+1)] for _ in range(len_str1+1)]
for i in range(len_str1+1):
distance[i][0] = i
for j in range(len_str2+1):
distance[0][... | [
"assert calculate_levenshtein_distance('kitten', 'sitting') == 3",
"assert calculate_levenshtein_distance('flaw', 'lawn') == 2",
"assert calculate_levenshtein_distance('intention', 'execution') == 5"
] | Certainly! The Levenshtein distance can be calculated using dynamic programming. Below is a Python function that implements this algorithm to compute the Levenshtein distance between two strings:
```python
def levenshtein_distance(s1, s2):
# Create a matrix to store the distances
len_s1 = len(s1) + 1
len_s... | 4,742 | [
{
"from": "human",
"value": "Write a function to calculate the Levenshtein distance between two strings. The Levenshtein distance is a string metric for measuring the difference between two sequences. It is calculated as the minimum number of single-character edits (insertions, deletions, or substitutions) ... |
Write a function to find all the anagrams of a given string in a given list of strings. | Here is the code to solve this problem:
```python
def find_anagrams(word_list, word):
word_sorted = sorted(word)
anagrams = []
for w in word_list:
if sorted(w) == word_sorted:
anagrams.append(w)
return anagrams
``` | [
"assert find_anagrams(['act', 'cat', 'tac', 'god', 'dog', 'odg', 'the', 'aet'], 'act') == ['act', 'cat', 'tac']",
"assert find_anagrams(['act', 'cat', 'tac', 'god', 'dog', 'odg', 'the', 'aet'], 'god') == ['god', 'dog', 'odg']",
"assert find_anagrams(['act', 'cat', 'tac', 'god', 'dog', 'odg', 'the', 'aet'], 'the... | You can find all anagrams of a given string in a list of strings by comparing the sorted versions of the strings. If two strings are anagrams of each other, their sorted characters will be the same.
Here’s a Python function to do that:
```python
def find_anagrams(word, words_list):
# Sort the input word to create... | 4,743 | [
{
"from": "human",
"value": "Write a function to find all the anagrams of a given string in a given list of strings."
},
{
"from": "gpt",
"value": "You can find all anagrams of a given string in a list of strings by comparing the sorted versions of the strings. If two strings are anagrams of eac... |
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(num_list):
n = len(num_list)
mid = n // 2
if n % 2 == 0:
return [num_list[mid - 1], num_list[mid]]
else:
return num_list[mid]
``` | [
"assert find_middle([2,4,6,8,10,12,14]) == 8",
"assert find_middle([1,2,3,4,5,6]) == [3,4]",
"assert find_middle([1,2,3,4,5]) == 3"
] | You can create a Python function to find the middle element(s) of a given list like this:
```python
def find_middle_elements(lst):
size = len(lst)
if size == 0:
return None # return None for an empty list
mid_index = size // 2
if size % 2 == 0: # even number of elements
... | 4,744 | [
{
"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 create a Python function to find the middle element(s) of a given list like this:\n\... |
Write a python function to find the maximum and minimum value from a given list of dictionaries based on a specific key. | Here is the code to solve this problem:
```python
def max_min_value(dict_list, key):
if not dict_list or key not in dict_list[0]:
return None, None
max_value = max(dict_list, key=lambda x: x[key])[key]
min_value = min(dict_list, key=lambda x: x[key])[key]
return max_value, min_value
``` | [
"assert max_min_value([{'score': 85}, {'score': 92}, {'score': 78}, {'score': 90}], 'score') == (92, 78)",
"assert max_min_value([{'price': 100}, {'price': 150}, {'price': 200}, {'price': 50}], 'price') == (200, 50)",
"assert max_min_value([{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Cha... | Certainly! Below is a Python function that takes a list of dictionaries and a specific key, and returns both the minimum and maximum values associated with that key from the dictionaries.
```python
def find_min_max(data_list, key):
"""
Find the minimum and maximum values in a list of dictionaries based on a sp... | 4,745 | [
{
"from": "human",
"value": "Write a python function to find the maximum and minimum value from a given list of dictionaries based on a specific key."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that takes a list of dictionaries and a specific key, and returns both the mi... |
Write a python function to find the shortest repeating pattern within a given string. | Here is the code to solve this problem:
```python
def find_shortest_repeating_pattern(s: str) -> str:
length = len(s)
for cut in range(1, length // 2 + 1):
if length % cut != 0:
continue
if s[:cut] * (length // cut) == s:
return s[:cut]
return s
``` | [
"assert find_shortest_repeating_pattern(\"abababab\") == \"ab\"",
"assert find_shortest_repeating_pattern(\"abcabcabcabc\") == \"abc\"",
"assert find_shortest_repeating_pattern(\"abcdabcdabcdabcd\") == \"abcd\"",
"assert find_shortest_repeating_pattern(\"abcabcabcabcabc\") == \"abc\""
] | To find the shortest repeating pattern within a given string, we can use a function that iterates through potential substring lengths and checks if the original string can be constructed by repeating that substring. Here is one way to implement such a function in Python:
```python
def shortest_repeating_pattern(s: str... | 4,746 | [
{
"from": "human",
"value": "Write a python function to find the shortest repeating pattern within a given string."
},
{
"from": "gpt",
"value": "To find the shortest repeating pattern within a given string, we can use a function that iterates through potential substring lengths and checks if th... |
Write a python function to find the smallest element in a list of numbers. | Here is the code to solve this problem:
```python
def smallest_element(lst):
return min(lst)
``` | [
"assert smallest_element([1, 3, 5, 7, 9]) == 1",
"assert smallest_element([3, 2, 1]) == 1",
"assert smallest_element([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) == 0"
] | Certainly! Here’s a Python function that finds the smallest element in a list of numbers:
```python
def find_smallest(numbers):
if not numbers:
raise ValueError("The list is empty.")
# Initialize the smallest element as the first element of the list
smallest = numbers[0]
# Iterate thr... | 4,747 | [
{
"from": "human",
"value": "Write a python function to find the smallest element in a list of numbers."
},
{
"from": "gpt",
"value": "Certainly! Here’s a Python function that finds the smallest element in a list of numbers:\n\n```python\ndef find_smallest(numbers):\n if not numbers:\n ... |
Write a python function to find the duplicate number in a given list of numbers from 1 to n, where one number is duplicated. | Here is the code to solve this problem:
```python
def duplicate_number(nums):
res = 0
for num in nums:
res ^= num
for i in range(1, len(nums)):
res ^= i
return res
``` | [
"assert duplicate_number([3, 1, 3, 4, 2]) == 3",
"assert duplicate_number([1, 3, 4, 2, 2]) == 2",
"assert duplicate_number([1, 3, 4, 4, 2]) == 4"
] | You can find the duplicate number in a list of numbers from 1 to \( n \) using various approaches. One efficient way is to use the Floyd's Tortoise and Hare (Cycle Detection) algorithm. Here is a Python function that implements this algorithm:
```python
def find_duplicate(nums):
# Using Floyd's Tortoise and Hare a... | 4,748 | [
{
"from": "human",
"value": "Write a python function to find the duplicate number in a given list of numbers from 1 to n, where one number is duplicated."
},
{
"from": "gpt",
"value": "You can find the duplicate number in a list of numbers from 1 to \\( n \\) using various approaches. One effici... |
Write a python function to find the number of distinct subsequences of a given string. | Here is the code to solve this problem:
```python
def numDistinct(s: str, t: str) -> int:
m, n = len(s), len(t)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = 1
for i in range(1, m + 1):
for j in range(1, n + 1):
if s[i - 1] == t[j - 1... | [
"assert numDistinct(\"abc\", \"abc\") == 1",
"assert numDistinct(\"babgbag\", \"bag\") == 5",
"assert numDistinct(\"rabbbit\", \"rabbit\") == 3"
] | To find the number of distinct subsequences of a given string, we can use dynamic programming. Here's a Python function that calculates the number of distinct subsequences for a given string:
```python
def distinct_subseq_count(s: str) -> int:
# Length of the input string.
n = len(s)
# Array to store ... | 4,749 | [
{
"from": "human",
"value": "Write a python function to find the number of distinct subsequences of a given string."
},
{
"from": "gpt",
"value": "To find the number of distinct subsequences of a given string, we can use dynamic programming. Here's a Python function that calculates the number of... |
Write a python function to find the maximum sum of a subarray with a given length. | Here is the code to solve this problem:
```python
def max_Subarray_Sum(arr, k):
max_sum = 0
window_sum = 0
window_start = 0
for window_end in range(len(arr)):
window_sum += arr[window_end]
if window_end >= k-1:
if window_sum > max_sum:
max_sum = window_sum
... | [
"assert max_Subarray_Sum([1,3,-1,-3,5,3,6,7], 3) == 16",
"assert max_Subarray_Sum([1,-1,5,2,-4], 2) == 7",
"assert max_Subarray_Sum([2,3,4,1,5], 2) == 7"
] | You can find the maximum sum of a subarray with a given length using a sliding window approach. This method is efficient and works in linear time. Below is a Python function that implements this algorithm:
```python
def max_sum_subarray(arr, k):
# Check if the array length is less than k
if len(arr) < k or k <... | 4,750 | [
{
"from": "human",
"value": "Write a python function to find the maximum sum of a subarray with a given length."
},
{
"from": "gpt",
"value": "You can find the maximum sum of a subarray with a given length using a sliding window approach. This method is efficient and works in linear time. Below ... |
Write a python function to find the total number of continuous subarrays whose sum equals to k. | Here is the code to solve this problem:
```python
def subarray_sum(nums, k):
sum_occurrence = {0: 1}
total, current_sum = 0, 0
for num in nums:
current_sum += num
if current_sum - k in sum_occurrence:
total += sum_occurrence[current_sum - k]
sum_occurrence[current_s... | [
"assert subarray_sum([1,2,3],3)==2",
"assert subarray_sum([1,1,1],2)==2",
"assert subarray_sum([1],0)==0"
] | To find the total number of continuous subarrays whose sum equals a given value `k`, we can use a hash map (dictionary in Python) to keep track of the cumulative sums. The approach is based on the following idea:
1. As we iterate through the array, we maintain a running sum of the elements we've seen so far.
2. For ea... | 4,751 | [
{
"from": "human",
"value": "Write a python function to find the total number of continuous subarrays whose sum equals to k."
},
{
"from": "gpt",
"value": "To find the total number of continuous subarrays whose sum equals a given value `k`, we can use a hash map (dictionary in Python) to keep tr... |
Write a python function to check if a given number is a perfect square or not. | Here is the code to solve this problem:
```python
import math
def checkPerfectSquare(num):
if (int(math.sqrt(num))**2) == num:
return "Yes"
else:
return "No"
``` | [
"assert checkPerfectSquare(16) == \"Yes\"",
"assert checkPerfectSquare(25) == \"Yes\"",
"assert checkPerfectSquare(26) == \"No\"",
"assert checkPerfectSquare(9) == \"Yes\"",
"assert checkPerfectSquare(15) == \"No\""
] | Certainly! You can check if a given number is a perfect square by taking the integer square root of the number and squaring it again to see if you get the original number. Here's a simple Python function that does this:
```python
import math
def is_perfect_square(n):
if n < 0:
return False # Negative num... | 4,752 | [
{
"from": "human",
"value": "Write a python function to check if a given number is a perfect square or not."
},
{
"from": "gpt",
"value": "Certainly! You can check if a given number is a perfect square by taking the integer square root of the number and squaring it again to see if you get the or... |
Write a python function to count the number of unique characters in a given string. | Here is the code to solve this problem:
```python
def count_unique_characters(string1):
unique_chars = set(string1)
return len(unique_chars)
``` | [
"assert count_unique_characters(\"hello\") == 4",
"assert count_unique_characters(\"abcdefg\") == 7",
"assert count_unique_characters(\"aabbcc\") == 3"
] | You can count the number of unique characters in a string by using a set, which inherently only keeps distinct elements. Here's a simple Python function to achieve this:
```python
def count_unique_characters(s):
# Use a set to store unique characters
unique_characters = set(s)
# Return the length of the se... | 4,753 | [
{
"from": "human",
"value": "Write a python function to count the number of unique characters in a given string."
},
{
"from": "gpt",
"value": "You can count the number of unique characters in a string by using a set, which inherently only keeps distinct elements. Here's a simple Python function... |
Write a python function to find the maximum number of points that lie on the same straight line. | Here is the code to solve this problem:
```python
from collections import defaultdict
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def max_points_on_line(points):
if not points:
return 0
ans = 1
for i in range(len(points) - 1):
start = Point(points[i][0... | [
"assert max_points_on_line([(1,1),(3,2),(5,3),(4,1),(2,3),(1,4)]) == 4",
"assert max_points_on_line([(1,1),(2,2),(3,3)]) == 3",
"assert max_points_on_line([(0,0),(1,1),(0,0)]) == 3"
] | To solve the problem of finding the maximum number of points that lie on the same straight line, we can use the concept of slopes to determine collinearity among points. Here's a step-by-step approach:
1. For each point, calculate the slopes between that point and every other point.
2. Use a hash map to count how many... | 4,754 | [
{
"from": "human",
"value": "Write a python function to find the maximum number of points that lie on the same straight line."
},
{
"from": "gpt",
"value": "To solve the problem of finding the maximum number of points that lie on the same straight line, we can use the concept of slopes to determ... |
Write a function to find the least number of operations required to make two strings equal. An operation is defined as deleting a character from one of the strings. The function should return the minimum number of deletions required. | Here is the code to solve this problem:
```python
def least_operations(str1, str2):
len1, len2 = len(str1), len(str2)
dp = [[0] * (len2 + 1) for _ in range(len1 + 1)]
for i in range(len1):
for j in range(len2):
if str1[i] == str2[j]:
dp[i + 1][j + 1] = dp[i][j] + 1
... | [
"assert least_operations(\"sea\", \"eat\") == 2",
"assert least_operations(\"leetcode\", \"etco\") == 4",
"assert least_operations(\"abc\", \"abc\") == 0"
] | To solve the problem of making two strings equal by performing the least number of character deletions, we can leverage the concept of the longest common subsequence (LCS). The LCS gives us the length of the largest sequence that appears in both strings in the same order, and thus, we can determine how many characters ... | 4,755 | [
{
"from": "human",
"value": "Write a function to find the least number of operations required to make two strings equal. An operation is defined as deleting a character from one of the strings. The function should return the minimum number of deletions required."
},
{
"from": "gpt",
"value": "To... |
Write a function to generate the powerset of a given list. The powerset is the set of all possible subsets of the list, including the empty set and the list itself. | Here is the code to solve this problem:
```python
def powerset(lst):
result = [[]]
for elem in lst:
result.extend([subset + [elem] for subset in result])
return result
``` | [
"assert powerset([]) == [[]]",
"assert powerset(['a','b']) == [[], ['a'], ['b'], ['a', 'b']]",
"assert powerset([1,2]) == [[], [1], [2], [1, 2]]"
] | To generate the powerset of a given list, you can use a recursive approach or an iterative method. Here, I will provide a Python function that uses an iterative approach to generate the powerset.
Here’s the function:
```python
def powerset(lst):
"""Generate the powerset of a given list."""
result = [[]] # St... | 4,756 | [
{
"from": "human",
"value": "Write a function to generate the powerset of a given list. The powerset is the set of all possible subsets of the list, including the empty set and the list itself."
},
{
"from": "gpt",
"value": "To generate the powerset of a given list, you can use a recursive appro... |
Write a function to filter out strings from a list that contain the substring 'bad'. | Here is the code to solve this problem:
```python
def filter_bad_strings(strings):
return [string for string in strings if 'bad' not in string]
``` | [
"assert filter_bad_strings(['badapple', 'goodberry', 'badcherry', 'good']) == ['goodberry', 'good']",
"assert filter_bad_strings(['bad', 'bad', 'worsebad', 'worstbad']) == []",
"assert filter_bad_strings(['good', 'bad', 'goodbad', 'badgood', 'best']) == ['good', 'best']"
] | Certainly! Below is a Python function that filters out strings from a list that contain the substring 'bad'. It takes a list of strings as input and returns a new list containing only the strings that do not have the substring 'bad'.
```python
def filter_bad_strings(string_list):
# Use a list comprehension to filt... | 4,757 | [
{
"from": "human",
"value": "Write a function to filter out strings from a list that contain the substring 'bad'."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that filters out strings from a list that contain the substring 'bad'. It takes a list of strings as input and re... |
Write a Python function to check if a given matrix is a Toeplitz matrix. A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. | Here is the code to solve this problem:
```python
def is_toeplitz(matrix):
ROWS = len(matrix)
COLS = len(matrix[0])
c = 1
r = ROWS - 1
ans = True
while r >= 0:
ans = ans and check_diagonal(matrix,r,0)
r -=1
while c < COLS:
ans = ans and check_diagonal(matrix,0,... | [
"assert is_toeplitz([[1,2,3,4],[5,1,2,3],[9,5,1,2]]) == True",
"assert is_toeplitz([[1,2],[2,2]]) == False",
"assert is_toeplitz([[3,7,0],[5,3,7],[2,5,3]]) == True"
] | A Toeplitz matrix is a matrix where each descending diagonal from left to right is constant, meaning every element on the same diagonal is the same.
Here’s a Python function to check if a given matrix is a Toeplitz matrix:
```python
def isToeplitzMatrix(matrix):
if not matrix:
return True
num_ro... | 4,758 | [
{
"from": "human",
"value": "Write a Python function to check if a given matrix is a Toeplitz matrix. A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element."
},
{
"from": "gpt",
"value": "A Toeplitz matrix is a matrix where each descending diagonal from left t... |
Write a python function to check if a number is a strobogrammatic number or not. A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). | Here is the code to solve this problem:
```python
def isStrobogrammatic(num):
for c in num:
if c in '23457':
return False
nmap = {'6':'9', '9':'6', '0':'0', '1':'1', '8':'8'}
i = 0
j = len(num) - 1
while i <= j:
if nmap[num[i]] != num[j]:
return False
... | [
"assert isStrobogrammatic(\"962\") == False",
"assert isStrobogrammatic(\"88\") == True",
"assert isStrobogrammatic(\"69\") == True"
] | To check if a number is a strobogrammatic number, we need to ensure that each digit in the number can be rotated 180 degrees and still look like a valid digit. The digits that are considered strobogrammatic when rotated are as follows:
- 0 stays as 0
- 1 stays as 1
- 6 becomes 9
- 8 stays as 8
- 9 becomes 6
Other dig... | 4,759 | [
{
"from": "human",
"value": "Write a python function to check if a number is a strobogrammatic number or not. A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down)."
},
{
"from": "gpt",
"value": "To check if a number is a strobogrammatic number... |
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(nums1, nums2):
nums = sorted(nums1 + nums2)
length = len(nums)
if length % 2 == 0:
return (nums[length // 2 - 1] + nums[length // 2]) / 2
else:
return nums[length // 2]
``` | [
"assert median_two_sorted_arrays([1, 2], [3, 4]) == 2.5",
"assert median_two_sorted_arrays([], [1]) == 1.0",
"assert median_two_sorted_arrays([1, 3], [2]) == 2.0",
"assert median_two_sorted_arrays([0, 0], [0, 0]) == 0.0",
"assert median_two_sorted_arrays([2], []) == 2.0"
] | To find the median of two sorted arrays, you can use a binary search approach. This algorithm is efficient and works in \(O(\log(\min(n, m)))\) time complexity, where \(n\) and \(m\) are the lengths of the two arrays.
Here's a Python function that implements this approach:
```python
def findMedianSortedArrays(nums1, ... | 4,760 | [
{
"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. This algorithm is efficient and works in \\(O(\\log(\\min(n, m)))\\) time complexity, where \\(n\\)... |
Write a function to convert a given decimal number to base 7. | Here is the code to solve this problem:
```python
def convertToBase7(num):
if num < 0:
return '-' + convertToBase7(-num)
if num < 7:
return str(num)
return convertToBase7(num // 7) + str(num % 7)
``` | [
"assert convertToBase7(7) == \"10\"",
"assert convertToBase7(100) == \"202\"",
"assert convertToBase7(49) == \"100\""
] | You can convert a decimal number to base 7 by repeatedly dividing the number by 7 and keeping track of the remainders. The base 7 representation will be formed by the remainders obtained in reverse order. Below is a Python function that performs this conversion:
```python
def decimal_to_base7(n):
# Handle the spec... | 4,761 | [
{
"from": "human",
"value": "Write a function to convert a given decimal number to base 7."
},
{
"from": "gpt",
"value": "You can convert a decimal number to base 7 by repeatedly dividing the number by 7 and keeping track of the remainders. The base 7 representation will be formed by the remaind... |
Write a function that finds the most common character in a given string and returns it. If there are multiple characters with the highest frequency, return the one that appears first in the string. If the input string is empty, return None. | Here is the code to solve this problem:
```python
def most_common_char(s):
if not s:
return None
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
max_count = 0
max_char = None
for char in s:
... | [
"assert most_common_char(\"hello world\")==\"l\"",
"assert most_common_char(\"\")==None",
"assert most_common_char(\"aabbcc\")==\"a\""
] | Certainly! Below is a Python function that accomplishes the task of finding the most common character in a given string. If there are ties in frequency, it returns the character that appears first in the string. If the input string is empty, it will return `None`.
```python
def most_common_char(s):
if not s:
... | 4,762 | [
{
"from": "human",
"value": "Write a function that finds the most common character in a given string and returns it. If there are multiple characters with the highest frequency, return the one that appears first in the string. If the input string is empty, return None."
},
{
"from": "gpt",
"valu... |
Write a function to find the smallest window in a given string containing all characters of another string. | Here is the code to solve this problem:
```python
from collections import Counter
def smallest_window(str1, str2):
str2_count = Counter(str2)
required = len(str2_count)
formed = 0
window_counts = {}
ans = float("inf"), None, None
l = 0
for r in range(len(str1)):
char = str1[r]
... | [
"assert smallest_window(\"geeksforgeeks\", \"ork\") == \"ksfor\"",
"assert smallest_window(\"this is a test string\", \"tist\") == \"t stri\"",
"assert smallest_window(\"zoom\", \"mo\") == \"om\""
] | Certainly! You can solve the problem of finding the smallest window in a given string that contains all characters of another string using the sliding window technique. Below is a Python function that implements this approach.
```python
from collections import Counter, defaultdict
def min_window(s: str, t: str) -> st... | 4,763 | [
{
"from": "human",
"value": "Write a function to find the smallest window in a given string containing all characters of another string."
},
{
"from": "gpt",
"value": "Certainly! You can solve the problem of finding the smallest window in a given string that contains all characters of another st... |
Write a function to find the number of days between two dates. | Here is the code to solve this problem:
```python
from datetime import datetime
def date_diff(date1, date2):
date_format = "%Y-%m-%d"
a = datetime.strptime(date1, date_format)
b = datetime.strptime(date2, date_format)
delta = b - a
return delta.days
``` | [
"assert date_diff(\"2020-01-01\", \"2020-01-02\") == 1",
"assert date_diff(\"2020-01-01\", \"2020-01-03\") == 2",
"assert date_diff(\"2020-01-01\", \"2020-02-01\") == 31"
] | Certainly! You can use Python's built-in `datetime` module to calculate the number of days between two dates. Here's a simple function to achieve that:
```python
from datetime import datetime
def days_between_dates(date1, date2):
"""
Calculate the number of days between two dates.
Args:
date1 (str): ... | 4,764 | [
{
"from": "human",
"value": "Write a function to find the number of days between two dates."
},
{
"from": "gpt",
"value": "Certainly! You can use Python's built-in `datetime` module to calculate the number of days between two dates. Here's a simple function to achieve that:\n\n```python\nfrom da... |
Write a python function that takes a string and returns a new string with the first and last character swapped. | Here is the code to solve this problem:
```python
def swap_edge_chars(s):
if len(s) <= 1:
return s
return s[-1] + s[1:-1] + s[0]
``` | [
"assert swap_edge_chars(\"hello\") == \"oellh\"",
"assert swap_edge_chars(\"a\") == \"a\"",
"assert swap_edge_chars(\"ab\") == \"ba\""
] | Certainly! Here’s a Python function that takes a string as input and returns a new string with the first and last characters swapped. If the string is empty or has only one character, it simply returns the string itself.
```python
def swap_first_and_last(s):
# Check if the string is empty or has only one character... | 4,765 | [
{
"from": "human",
"value": "Write a python function that takes a string and returns a new string with the first and last character swapped."
},
{
"from": "gpt",
"value": "Certainly! Here’s a Python function that takes a string as input and returns a new string with the first and last characters... |
Write a python function to convert a given number to its binary representation and return the number of ones in it. | Here is the code to solve this problem:
```python
def count_ones_in_binary(n):
binary = bin(n).replace("0b", "")
return binary.count("1")
``` | [
"assert count_ones_in_binary(7) == 3",
"assert count_ones_in_binary(10) == 2",
"assert count_ones_in_binary(15) == 4"
] | You can create a Python function that converts a given number to its binary representation using the built-in `bin()` function and then counts the number of ones (`1`s`) in that binary representation. Here's how you can do it:
```python
def count_ones_in_binary(n):
# Convert the number to binary using bin(), slice... | 4,766 | [
{
"from": "human",
"value": "Write a python function to convert a given number to its binary representation and return the number of ones in it."
},
{
"from": "gpt",
"value": "You can create a Python function that converts a given number to its binary representation using the built-in `bin()` fu... |
Write a python function to find if a directed graph contains a cycle or not using DFS.
Input:
- num_nodes: An integer representing the number of nodes in the graph.
- edges: A list of lists where each sublist contains two integers u and v representing a directed edge from u to v.
Output:
- Return True if the graph co... | Here is the code to solve this problem:
```python
from typing import List
def has_cycle(num_nodes: int, edges: List[List[int]]) -> bool:
graph = {i: [] for i in range(num_nodes)}
for u, v in edges:
graph[u].append(v)
visited = [False] * num_nodes
rec_stack = [False] * num_nodes
def dfs(n... | [
"assert has_cycle(3, [[0, 1], [1, 2], [2, 0]]) == True",
"assert has_cycle(5, [[0, 1], [1, 2], [2, 3], [3, 4], [4, 0]]) == True",
"assert has_cycle(4, [[0, 1], [1, 2], [2, 3]]) == False"
] | You can check for cycles in a directed graph using Depth First Search (DFS) by keeping track of visited nodes and nodes currently in the recursion stack. If we revisit a node that is already in the recursion stack, this indicates the presence of a cycle.
Here’s how you can implement this in Python:
```python
def has_... | 4,767 | [
{
"from": "human",
"value": "Write a python function to find if a directed graph contains a cycle or not using DFS.\n\nInput:\n- num_nodes: An integer representing the number of nodes in the graph.\n- edges: A list of lists where each sublist contains two integers u and v representing a directed edge from u... |
Write a python function to find the number of connected components in an undirected graph. The graph is represented in adjacency list format. | Here is the code to solve this problem:
```python
from collections import defaultdict
def count_components(n, edges):
graph = defaultdict(list)
for edge in edges:
graph[edge[0]].append(edge[1])
graph[edge[1]].append(edge[0])
visited = set()
def dfs(node):
if node in visited:
... | [
"assert count_components(3, []) == 3",
"assert count_components(5, [[0, 1], [1, 2], [3, 4]]) == 2",
"assert count_components(5, [[0, 1], [1, 2], [2, 3], [3, 4]]) == 1"
] | Certainly! In order to find the number of connected components in an undirected graph represented by an adjacency list, we can perform a depth-first search (DFS) or breadth-first search (BFS) starting from each unvisited node. Each time we start a new search from an unvisited node, it indicates that we've found a new c... | 4,768 | [
{
"from": "human",
"value": "Write a python function to find the number of connected components in an undirected graph. The graph is represented in adjacency list format."
},
{
"from": "gpt",
"value": "Certainly! In order to find the number of connected components in an undirected graph represen... |
Write a function to check if a given list of integers is strictly increasing. | Here is the code to solve this problem:
```python
def is_strictly_increasing(lst):
return all(lst[i] < lst[i+1] for i in range(len(lst)-1))
``` | [
"assert is_strictly_increasing([1, 2, 2, 3, 4]) == False",
"assert is_strictly_increasing([1, 2, 3, 4, 5]) == True",
"assert is_strictly_increasing([5, 4, 3, 2, 1]) == False"
] | You can check if a list of integers is strictly increasing by iterating through the list and comparing each element to the next one. A strictly increasing list is defined as one where each element is less than the element that follows it.
Here's a Python function that accomplishes this:
```python
def is_strictly_incr... | 4,769 | [
{
"from": "human",
"value": "Write a function to check if a given list of integers is strictly increasing."
},
{
"from": "gpt",
"value": "You can check if a list of integers is strictly increasing by iterating through the list and comparing each element to the next one. A strictly increasing lis... |
Write a function that takes a list of integers and returns the product of all prime numbers in the list. | Here is the code to solve this problem:
```python
def prime_product(nums):
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
product = 1
for num in nums:
if is_... | [
"assert prime_product([2, 3, 4, 5, 6, 7]) == 210",
"assert prime_product([10, 11, 12, 13, 14]) == 143",
"assert prime_product([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 210"
] | You can write a Python function that computes the product of all prime numbers in a given list of integers by following these steps:
1. Define a helper function to determine if a number is prime.
2. Iterate through the list of integers, checking each number to see if it is prime.
3. If it is prime, multiply it to a ru... | 4,770 | [
{
"from": "human",
"value": "Write a function that takes a list of integers and returns the product of all prime numbers in the list."
},
{
"from": "gpt",
"value": "You can write a Python function that computes the product of all prime numbers in a given list of integers by following these steps... |
Write a python function to calculate the total number of ways to distribute n identical objects among r groups such that each group can receive 0 to n objects. This is a classic problem of distributing identical objects into distinct groups and is a direct application of the stars and bars theorem from combinatorics. | Here is the code to solve this problem:
```python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def stars_and_bars(n, r):
return factorial(n + r - 1) // (factorial(r - 1) * factorial(n))
``` | [
"assert stars_and_bars(3, 2) == 4",
"assert stars_and_bars(4, 2) == 5",
"assert stars_and_bars(5, 3) == 21"
] | Certainly! The problem of distributing \( n \) identical objects among \( r \) distinct groups such that each group can receive anywhere from \( 0 \) to \( n \) objects can be solved using the "stars and bars" theorem from combinatorics.
According to the stars and bars theorem, the number of ways to distribute \( n \)... | 4,771 | [
{
"from": "human",
"value": "Write a python function to calculate the total number of ways to distribute n identical objects among r groups such that each group can receive 0 to n objects. This is a classic problem of distributing identical objects into distinct groups and is a direct application of the sta... |
Write a function to sort a list of tuples according to the second value in each tuple. | Here is the code to solve this problem:
```python
def sort_tuples(tup):
return sorted(tup, key=lambda x: x[1])
``` | [
"assert sort_tuples([(1, 2), (4, 1), (3, 5), (2, 4)]) == [(4, 1), (1, 2), (2, 4), (3, 5)]",
"assert sort_tuples([(1, 3), (3, 2), (2, 1), (4, 4)]) == [(2, 1), (3, 2), (1, 3), (4, 4)]",
"assert sort_tuples([(5, 5), (1, 1), (2, 2)]) == [(1, 1), (2, 2), (5, 5)]"
] | You can sort a list of tuples by the second element in each tuple using the built-in `sorted()` function with a custom key. Here's how you can do it in Python:
```python
def sort_tuples_by_second(tuples_list):
return sorted(tuples_list, key=lambda x: x[1])
# Example usage:
tuples_list = [(1, 3), (2, 1), (3, 2)]
s... | 4,772 | [
{
"from": "human",
"value": "Write a function to sort a list of tuples according to the second value in each tuple."
},
{
"from": "gpt",
"value": "You can sort a list of tuples by the second element in each tuple using the built-in `sorted()` function with a custom key. Here's how you can do it ... |
Write a function to find the transpose of a given matrix. The transpose of a matrix is obtained by swapping the rows and columns. | Here is the code to solve this problem:
```python
def matrix_transpose(matrix):
# transpose the matrix
result = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
return result
``` | [
"assert matrix_transpose([[10, 20], [30, 40]])==[[10, 30], [20, 40]]",
"assert matrix_transpose([[1]])==[[1]]",
"assert matrix_transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9]])==[[1, 4, 7], [2, 5, 8], [3, 6, 9]]"
] | Certainly! Below is a Python function that takes a matrix as input and returns its transpose. The function assumes that the input matrix is represented as a list of lists, where each inner list represents a row of the matrix.
```python
def transpose(matrix):
# Check if the input is a valid matrix
if not matrix... | 4,773 | [
{
"from": "human",
"value": "Write a function to find the transpose of a given matrix. The transpose of a matrix is obtained by swapping the rows and columns."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that takes a matrix as input and returns its transpose. The function... |
Write a function to find the first non-repeating character in a given string. If there is no non-repeating character, return an empty string. | Here is the code to solve this problem:
```python
def first_non_repeating(s: str) -> str:
if not s:
return ""
tableSize = 256
hashTable = [0]*tableSize
for i in range(len(s)):
hashTable[ord(s[i])]+=1
for i in range(len(s)):
if hashTable[ord(s[i])]==1:
return s[i]... | [
"assert first_non_repeating(\"\") == \"\"",
"assert first_non_repeating(\"abaccdeff\") == \"b\"",
"assert first_non_repeating(\"aabbcc\") == \"\"",
"assert first_non_repeating(\"python\") == \"p\""
] | Certainly! Below is a Python function that finds the first non-repeating character in a given string. If there is no non-repeating character, it returns an empty string.
```python
def first_non_repeating_character(s: str) -> str:
# Create a dictionary to count occurrences of each character
char_count = {}
... | 4,774 | [
{
"from": "human",
"value": "Write a function to find the first non-repeating character in a given string. If there is no non-repeating character, return an empty string."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that finds the first non-repeating character in a given ... |
Write a python function to rotate an array to the right by k steps, where k is non-negative. | Here is the code to solve this problem:
```python
def rotate(nums, k):
k = k % len(nums)
nums[:] = nums[-k:] + nums[:-k]
return nums
``` | [
"assert rotate([1,2,3,4,5,6,7], 3) == [5,6,7,1,2,3,4]",
"assert rotate([-1,-100,3,99], 2) == [3,99,-1,-100]",
"assert rotate([1,2,3], 2) == [2,3,1]"
] | You can rotate an array to the right by `k` steps using the following Python function. This function modifies the array in place and handles cases where `k` is greater than the length of the array:
```python
def rotate(nums, k):
n = len(nums)
# Handle the case where k is greater than n
k = k % n
# If ... | 4,775 | [
{
"from": "human",
"value": "Write a python function to rotate an array to the right by k steps, where k is non-negative."
},
{
"from": "gpt",
"value": "You can rotate an array to the right by `k` steps using the following Python function. This function modifies the array in place and handles ca... |
Write a python function to find the number of ways to reach the nth step by taking either 1, 2, or 3 steps at a time. | Here is the code to solve this problem:
```python
def count_steps(n):
if n == 1:
return 1
elif n == 2:
return 2
elif n == 3:
return 4
else:
return count_steps(n-1) + count_steps(n-2) + count_steps(n-3)
``` | [
"assert count_steps(5) == 13",
"assert count_steps(4) == 7",
"assert count_steps(3) == 4"
] | You can utilize dynamic programming to solve the problem of finding the number of ways to reach the nth step by taking either 1, 2, or 3 steps at a time. Here is a Python function that implements this approach:
```python
def count_ways(n):
# Base cases
if n == 0:
return 1 # 1 way to stay at the ground... | 4,776 | [
{
"from": "human",
"value": "Write a python function to find the number of ways to reach the nth step by taking either 1, 2, or 3 steps at a time."
},
{
"from": "gpt",
"value": "You can utilize dynamic programming to solve the problem of finding the number of ways to reach the nth step by taking... |
Write a function to find the number of subarrays with sum equals to k. | Here is the code to solve this problem:
```python
def subarray_sum(arr, k):
count = 0
current_sum = 0
sum_dict = {0: 1}
for i in range(len(arr)):
current_sum += arr[i]
if current_sum - k in sum_dict:
count += sum_dict[current_sum - k]
if current_sum in sum_dict:
... | [
"assert subarray_sum([10, 2, -2, -20, 10], -10) == 3",
"assert subarray_sum([1, 2, 3], 3) == 2",
"assert subarray_sum([1, 1, 1], 2) == 2"
] | To find the number of subarrays with a sum equal to a given integer \( k \), you can use a hashmap (dictionary) to keep track of the cumulative sums and their frequencies. This approach has an average time complexity of \( O(n) \), where \( n \) is the number of elements in the array.
Here's a Python function that imp... | 4,777 | [
{
"from": "human",
"value": "Write a function to find the number of subarrays with sum equals to k."
},
{
"from": "gpt",
"value": "To find the number of subarrays with a sum equal to a given integer \\( k \\), you can use a hashmap (dictionary) to keep track of the cumulative sums and their freq... |
Write a python function to find the largest palindrome made from the product of two n-digit numbers. | Here is the code to solve this problem:
```python
def largest_palindrome(n):
def is_palindrome(num):
return str(num) == str(num)[::-1]
max_num = 10 ** n - 1
min_num = 10 ** (n - 1)
max_palindrome = 0
for i in range(max_num, min_num - 1, -1):
for j in range(i, min_num - 1, -1):
... | [
"assert largest_palindrome(2) == 9009",
"assert largest_palindrome(4) == 99000099",
"assert largest_palindrome(3) == 906609"
] | Certainly! To find the largest palindrome made from the product of two n-digit numbers, you can implement a function in Python. Here's a possible solution:
```python
def is_palindrome(num):
"""Check if a number is a palindrome."""
return str(num) == str(num)[::-1]
def largest_palindrome_product(n):
"""Fin... | 4,778 | [
{
"from": "human",
"value": "Write a python function to find the largest palindrome made from the product of two n-digit numbers."
},
{
"from": "gpt",
"value": "Certainly! To find the largest palindrome made from the product of two n-digit numbers, you can implement a function in Python. Here's ... |
Write a function to check if a given array can form a palindrome by rearranging its elements. | Here is the code to solve this problem:
```python
from collections import Counter
def can_form_palindrome(arr):
count_dict = Counter(arr)
odd_count = 0
for count in count_dict.values():
if count % 2 != 0:
odd_count += 1
if odd_count > 1:
return False
return True... | [
"assert can_form_palindrome([1, 3, 3, 1, 2])==True",
"assert can_form_palindrome([1, 1, 2, 2, 3, 3, 4])==True",
"assert can_form_palindrome([1, 2, 3, 4, 5])==False"
] | To determine if the elements of an array can be rearranged to form a palindrome, we need to consider the occurrences of each element. A palindrome reads the same forwards and backwards, which imposes certain conditions on the elements' counts:
1. If the length of the array is even, every element must occur an even num... | 4,779 | [
{
"from": "human",
"value": "Write a function to check if a given array can form a palindrome by rearranging its elements."
},
{
"from": "gpt",
"value": "To determine if the elements of an array can be rearranged to form a palindrome, we need to consider the occurrences of each element. A palind... |
Write a function to find the number of times a given pattern appears in a string. | Here is the code to solve this problem:
```python
def find_pattern(s, pattern):
if not pattern or not s:
return 0
count = start = 0
while start < len(s):
pos = s.find(pattern, start)
if pos != -1:
start = pos + 1
count += 1
else:
break
... | [
"assert find_pattern(\"hello world\", \"o\") == 2",
"assert find_pattern(\"abracadabra\", \"abra\") == 2",
"assert find_pattern(\"mississippi\", \"issi\") == 2"
] | You can write a function in Python to count the occurrences of a given pattern in a string using the built-in string method `.count()`. Below is a simple implementation of such a function:
```python
def count_pattern_in_string(string, pattern):
return string.count(pattern)
# Example usage:
input_string = "abcabca... | 4,780 | [
{
"from": "human",
"value": "Write a function to find the number of times a given pattern appears in a string."
},
{
"from": "gpt",
"value": "You can write a function in Python to count the occurrences of a given pattern in a string using the built-in string method `.count()`. Below is a simple ... |
Write a function to determine if a given year is a leap year. | Here is the code to solve this problem:
```python
def is_leap_year(year):
if year % 4 != 0:
return False
elif year % 100 != 0:
return True
elif year % 400 != 0:
return False
else:
return True
``` | [
"assert is_leap_year(2100) == False",
"assert is_leap_year(2000) == True",
"assert is_leap_year(2004) == True",
"assert is_leap_year(1900) == False",
"assert is_leap_year(1996) == True"
] | Certainly! A leap year is determined by the following rules:
1. A year is a leap year if it is divisible by 4.
2. However, if the year is divisible by 100, it is *not* a leap year, unless:
3. The year is also divisible by 400, in which case it *is* a leap year.
Based on these rules, here's a function in Python to det... | 4,781 | [
{
"from": "human",
"value": "Write a function to determine if a given year is a leap year."
},
{
"from": "gpt",
"value": "Certainly! A leap year is determined by the following rules:\n\n1. A year is a leap year if it is divisible by 4.\n2. However, if the year is divisible by 100, it is *not* a ... |
Write a function to find the maximum subarray sum in a given array. | Here is the code to solve this problem:
```python
def maxSubArray(nums):
if not nums:
return 0
cur_sum = max_sum = nums[0]
for num in nums[1:]:
cur_sum = max(num, cur_sum + num)
max_sum = max(max_sum, cur_sum)
return max_sum
``` | [
"assert maxSubArray([1]) == 1",
"assert maxSubArray([-2,1,-3,4,-1,2,1,-5,4]) == 6",
"assert maxSubArray([5,4,-1,7,8]) == 23"
] | Certainly! To find the maximum subarray sum in a given array, you can use Kadane's Algorithm, which operates in O(n) time complexity. Here's a Python function that implements this algorithm:
```python
def max_subarray_sum(arr):
if not arr:
return 0 # Return 0 for empty array
max_current = max_global ... | 4,782 | [
{
"from": "human",
"value": "Write a function to find the maximum subarray sum in a given array."
},
{
"from": "gpt",
"value": "Certainly! To find the maximum subarray sum in a given array, you can use Kadane's Algorithm, which operates in O(n) time complexity. Here's a Python function that impl... |
Write a python function to find the longest sequence of consecutive ones in a binary array. | Here is the code to solve this problem:
```python
def longestOnes(nums):
c=0
max=0
for i in nums:
if i==1:
c=c+1
if max<c:
max=c
else:
c=0
return max
``` | [
"assert longestOnes([1,0,1,1,0,1])==2",
"assert longestOnes([0,0,0,0,0])==0",
"assert longestOnes([1,1,1,1,0])==4"
] | You can find the longest sequence of consecutive ones in a binary array by iterating through the array and keeping track of the current count of consecutive ones. Whenever you encounter a zero, you compare the current count with the maximum count found so far and reset the current count. Here's a simple implementation ... | 4,783 | [
{
"from": "human",
"value": "Write a python function to find the longest sequence of consecutive ones in a binary array."
},
{
"from": "gpt",
"value": "You can find the longest sequence of consecutive ones in a binary array by iterating through the array and keeping track of the current count of... |
Write a python function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". | Here is the code to solve this problem:
```python
def common_prefix(strs):
if not strs:
return ""
shortest_str = min(strs, key=len)
for i, char in enumerate(shortest_str):
for other in strs:
if other[i] != char:
return shortest_str[:i]
return shortest_str
``` | [
"assert common_prefix([\"dog\",\"racecar\",\"car\"]) == \"\"",
"assert common_prefix([\"flower\",\"flow\",\"flight\"]) == \"fl\"",
"assert common_prefix([\"interspecies\",\"interstellar\",\"interstate\"]) == \"inters\""
] | Certainly! You can implement the function to find the longest common prefix in an array of strings by comparing characters from the start of each string. Here’s a straightforward approach using Python:
```python
def longestCommonPrefix(strs):
if not strs:
return ""
# Start with the first string as the... | 4,784 | [
{
"from": "human",
"value": "Write a python function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string \"\"."
},
{
"from": "gpt",
"value": "Certainly! You can implement the function to find the longest common prefix in an a... |
Write a python function to find the highest product of two numbers in a given array. | Here is the code to solve this problem:
```python
def highest_product(arr):
if len(arr) < 2:
return None
arr.sort()
return max(arr[-1] * arr[-2], arr[0] * arr[1])
``` | [
"assert highest_product([1, 2, 3, 4, 5]) == 20",
"assert highest_product([-1, -2, -3, 1]) == 6",
"assert highest_product([4, 3, 5]) == 20"
] | You can find the highest product of two numbers in an array by iterating through the array and keeping track of the two largest numbers. Below is a Python function that implements this logic:
```python
def highest_product(arr):
if len(arr) < 2:
raise ValueError("Array must contain at least two numbers.")
... | 4,785 | [
{
"from": "human",
"value": "Write a python function to find the highest product of two numbers in a given array."
},
{
"from": "gpt",
"value": "You can find the highest product of two numbers in an array by iterating through the array and keeping track of the two largest numbers. Below is a Pyt... |
Write a function to find the number of connected components in an undirected graph represented as an adjacency list. | Here is the code to solve this problem:
```python
from collections import defaultdict
def num_connected_components(graph):
def dfs(node, visited):
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
dfs(neighbor, visited)
visited = set()
... | [
"assert num_connected_components({\"0\": [\"1\", \"2\"], \"1\": [\"0\", \"2\"], \"2\": [\"0\", \"1\"], \"3\": []}) == 2",
"assert num_connected_components({\"0\": [], \"1\": [], \"2\": [], \"3\": []}) == 4",
"assert num_connected_components({\"0\": [\"1\"], \"1\": [\"0\"], \"2\": [\"3\"], \"3\": [\"2\"], \"4\":... | To find the number of connected components in an undirected graph represented as an adjacency list, you can use Depth-First Search (DFS) or Breadth-First Search (BFS). The idea is to visit all nodes reachable from any starting node and mark them as visited. Each time you initiate a DFS or BFS from an unvisited node, it... | 4,786 | [
{
"from": "human",
"value": "Write a function to find the number of connected components in an undirected graph represented as an adjacency list."
},
{
"from": "gpt",
"value": "To find the number of connected components in an undirected graph represented as an adjacency list, you can use Depth-F... |
Write a python function to calculate the factorial of a given number using recursion. | Here is the code to solve this problem:
```python
def calculate_factorial(n):
if n == 0:
return 1
else:
return n * calculate_factorial(n-1)
``` | [
"assert calculate_factorial(0) == 1",
"assert calculate_factorial(5) == 120",
"assert calculate_factorial(10) == 3628800"
] | Certainly! Here's a Python function that calculates the factorial of a given number using recursion:
```python
def factorial(n):
# Base case: factorial of 0 is 1
if n == 0:
return 1
# Recursive case: n! = n * (n-1)!
elif n > 0:
return n * factorial(n - 1)
else:
raise ValueEr... | 4,787 | [
{
"from": "human",
"value": "Write a python function to calculate the factorial of a given number using recursion."
},
{
"from": "gpt",
"value": "Certainly! Here's a Python function that calculates the factorial of a given number using recursion:\n\n```python\ndef factorial(n):\n # Base case:... |
Write a function to find the minimum number of moves required to move all balls of the same color into a consecutive block. | Here is the code to solve this problem:
```python
def min_moves(boxes):
size = len(boxes)
answer = [0]*size
for i in range(size):
for j in range(size):
if boxes[j] == "1":
answer[i] += abs(j-i)
return min(answer)
``` | [
"assert min_moves(\"110\") == 1",
"assert min_moves(\"001011\") == 3",
"assert min_moves(\"10101\") == 4"
] | To solve the problem of finding the minimum number of moves required to rearrange balls of the same color into a consecutive block, you can follow these steps. This example assumes you have a string representing the colors of the balls where each character represents a different color.
We can use a greedy approach to... | 4,788 | [
{
"from": "human",
"value": "Write a function to find the minimum number of moves required to move all balls of the same color into a consecutive block."
},
{
"from": "gpt",
"value": "To solve the problem of finding the minimum number of moves required to rearrange balls of the same color into a... |
Write a function to reverse the bits of a given 32 bits unsigned integer. | Here is the code to solve this problem:
```python
def reverse_bits(n):
res = 0
for i in range(32):
res <<= 1
res |= n & 1
n >>= 1
return res
``` | [
"assert reverse_bits(4294967293) == 3221225471",
"assert reverse_bits(0) == 0",
"assert reverse_bits(43261596) == 964176192"
] | Certainly! You can reverse the bits of a 32-bit unsigned integer using a simple function in Python. Below is one way to implement this:
```python
def reverse_bits(n: int) -> int:
result = 0
for i in range(32):
# Shift result to the left to make space for the next bit
result <<= 1
# If t... | 4,789 | [
{
"from": "human",
"value": "Write a function to reverse the bits of a given 32 bits unsigned integer."
},
{
"from": "gpt",
"value": "Certainly! You can reverse the bits of a 32-bit unsigned integer using a simple function in Python. Below is one way to implement this:\n\n```python\ndef reverse_... |
Write a python function that calculates the minimum number of operations required to convert one string into another, given the costs of insert, delete, and replace operations. | Here is the code to solve this problem:
```python
def min_edit_cost(str1, str2, ic, dc, rc):
dp = [[0] * (len(str2) + 1) for _ in range(len(str1) + 1)]
for i in range(len(str1) + 1):
dp[i][0] = i * dc
for j in range(len(str2) + 1):
dp[0][j] = j * ic
for i in range... | [
"assert min_edit_cost(\"abc\",\"adc\",5,3,2) == 2",
"assert min_edit_cost(\"kitten\",\"sitting\",1,1,1) == 3",
"assert min_edit_cost(\"abc\",\"adc\",5,3,100) == 8"
] | You can solve the problem of converting one string to another using the concept of dynamic programming. The problem is often referred to as "edit distance" and requires you to compute the minimum cost of transformations between the two strings based on the costs of insertion, deletion, and replacement.
Here's a Python... | 4,790 | [
{
"from": "human",
"value": "Write a python function that calculates the minimum number of operations required to convert one string into another, given the costs of insert, delete, and replace operations."
},
{
"from": "gpt",
"value": "You can solve the problem of converting one string to anoth... |
Write a python function to find the first non-repeating character in a given string. | Here is the code to solve this problem:
```python
def find_first_non_repeating(s):
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
for char in s:
if char_count[char] == 1:
return char
retu... | [
"assert find_first_non_repeating('programming') == 'p'",
"assert find_first_non_repeating('geeksforgeeks') == 'f'",
"assert find_first_non_repeating('aabbcc') == None"
] | Certainly! Below is a Python function that finds the first non-repeating character in a given string. The function uses a dictionary to count the occurrences of each character and then identifies the first character with a count of one.
```python
def first_non_repeating_character(s: str) -> str:
char_count = {}
... | 4,791 | [
{
"from": "human",
"value": "Write a python function to find the first non-repeating character in a given string."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that finds the first non-repeating character in a given string. The function uses a dictionary to count the occur... |
Write a function that converts a string to a list of characters, but only includes characters that are letters or digits. All other characters should be ignored. | Here is the code to solve this problem:
```python
def convert_to_list(s):
result = []
for char in s:
if char.isalnum():
result.append(char)
return result
``` | [
"assert convert_to_list(\"Hello, World! 123\") == ['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd', '1', '2', '3']",
"assert convert_to_list(\"!@#$%^&*()\") == []",
"assert convert_to_list(\"Python3.8\") == ['P', 'y', 't', 'h', 'o', 'n', '3', '8']"
] | You can create a function that takes a string as input and returns a list of characters, filtering out any non-letter and non-digit characters. Here's how you might implement such a function in Python:
```python
def filter_string_to_list(input_string):
# Initialize an empty list to store the valid characters.
... | 4,792 | [
{
"from": "human",
"value": "Write a function that converts a string to a list of characters, but only includes characters that are letters or digits. All other characters should be ignored."
},
{
"from": "gpt",
"value": "You can create a function that takes a string as input and returns a list ... |
Write a python function to find the number of connected components in an undirected graph. The graph is represented as an adjacency matrix. | Here is the code to solve this problem:
```python
def count_connected_components(n, computers):
answer = 0
visited = [0] * n
def checkNetwork(node):
for i in range(n):
if computers[node][i] == 1 and not visited[i]:
visited[i] = 1
checkNetwork(i)
for... | [
"assert count_connected_components(3, [[1, 1, 0], [1, 1, 0], [0, 0, 1]]) == 2",
"assert count_connected_components(5, [[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 1, 1]]) == 3",
"assert count_connected_components(3, [[1, 1, 0], [1, 1, 1], [0, 1, 1]]) == 1"
] | To find the number of connected components in an undirected graph represented by an adjacency matrix, we can perform a depth-first search (DFS) or breadth-first search (BFS) to explore the graph. Each time we start a new search from an unvisited node, we identify a new connected component.
Here's a Python function tha... | 4,793 | [
{
"from": "human",
"value": "Write a python function to find the number of connected components in an undirected graph. The graph is represented as an adjacency matrix."
},
{
"from": "gpt",
"value": "To find the number of connected components in an undirected graph represented by an adjacency ma... |
Write a python function to find the sum of all even Fibonacci numbers up to a given limit. | Here is the code to solve this problem:
```python
def sum_even_fibonacci(limit):
a, b = 1, 2
total_sum = 0
while b <= limit:
if b % 2 == 0:
total_sum += b
a, b = b, a + b
return total_sum
``` | [
"assert sum_even_fibonacci(10) == 10",
"assert sum_even_fibonacci(34) == 44",
"assert sum_even_fibonacci(60) == 44"
] | Certainly! Below is a Python function that computes the sum of all even Fibonacci numbers up to a given limit.
```python
def sum_even_fibonacci(limit):
a, b = 0, 1 # Initial Fibonacci numbers
even_sum = 0 # Sum of even Fibonacci numbers
while a <= limit:
if a % 2 == 0: # Check if the Fibonacci ... | 4,794 | [
{
"from": "human",
"value": "Write a python function to find the sum of all even Fibonacci numbers up to a given limit."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that computes the sum of all even Fibonacci numbers up to a given limit.\n\n```python\ndef sum_even_fibonac... |
Write a function that checks whether a given string is a valid password. A valid password must satisfy the following conditions:
1. It must be at least 8 characters long.
2. It must contain at least one uppercase letter, one lowercase letter, one digit, and one special character (from the set: !@#$%^&*). | Here is the code to solve this problem:
```python
import re
def password_check(password):
if len(password) < 8:
return False
if not re.search("[a-z]", password):
return False
if not re.search("[A-Z]", password):
return False
if not re.search("[0-9]", password):
return F... | [
"assert password_check(\"Pass123\") == False",
"assert password_check(\"Passw!@#\") == False",
"assert password_check(\"Passw0rd!\") == True",
"assert password_check(\"password\") == False"
] | Certainly! Below is a Python function that checks whether a given string is a valid password based on the specified conditions:
```python
import re
def is_valid_password(password):
# Check the length condition
if len(password) < 8:
return False
# Check for at least one uppercase letter
if... | 4,795 | [
{
"from": "human",
"value": "Write a function that checks whether a given string is a valid password. A valid password must satisfy the following conditions:\n1. It must be at least 8 characters long.\n2. It must contain at least one uppercase letter, one lowercase letter, one digit, and one special charact... |
Write a python function to find the number of times a given pattern is found in a string, including overlapping cases. | Here is the code to solve this problem:
```python
def count_pattern_occurrences(text, pattern):
count = 0
index = 0
while index < len(text):
index = text.find(pattern, index)
if index == -1:
break
count += 1
index += 1
return count
``` | [
"assert count_pattern_occurrences(\"hello\", \"ll\") == 1",
"assert count_pattern_occurrences(\"ababababa\", \"aba\") == 4",
"assert count_pattern_occurrences(\"abcabcabc\", \"abc\") == 3"
] | To find the number of times a given pattern occurs in a string, including overlapping cases, you can use a straightforward approach with the `str.find()` method in a loop. Here's a Python function that accomplishes this:
```python
def count_overlapping_occurrences(string, pattern):
count = 0
start = 0
whi... | 4,796 | [
{
"from": "human",
"value": "Write a python function to find the number of times a given pattern is found in a string, including overlapping cases."
},
{
"from": "gpt",
"value": "To find the number of times a given pattern occurs in a string, including overlapping cases, you can use a straightfo... |
Write a python function to find the intersection of two given lists of integers. | Here is the code to solve this problem:
```python
def intersect_lists(list1, list2):
return list(set(list1) & set(list2))
``` | [
"assert intersect_lists([1, 2, 3, 4, 5], [3, 4, 5, 6, 7]) == [3, 4, 5]",
"assert intersect_lists([20, 21, 22], [23, 24, 25]) == []",
"assert intersect_lists([10, 11, 12, 13], [12, 13, 14, 15]) == [12, 13]"
] | You can find the intersection of two lists in Python using several approaches. Here’s a simple function that uses set operations to find the intersection of two lists of integers:
```python
def intersection(list1, list2):
# Convert both lists to sets and find the intersection
return list(set(list1) & set(list2... | 4,797 | [
{
"from": "human",
"value": "Write a python function to find the intersection of two given lists of integers."
},
{
"from": "gpt",
"value": "You can find the intersection of two lists in Python using several approaches. Here’s a simple function that uses set operations to find the intersection o... |
Write a function to generate a list of all permutations of a given string. The function should return all permutations as a list of strings. You can assume that the input string will not contain duplicate characters. | Here is the code to solve this problem:
```python
from itertools import permutations
def string_permutations(s):
return [''.join(p) for p in permutations(s)]
``` | [
"assert string_permutations('abc') == ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']",
"assert string_permutations('a') == ['a']",
"assert string_permutations('ab') == ['ab', 'ba']"
] | You can generate all permutations of a given string using a recursive approach or by utilizing the built-in `itertools` library. Below, I'll provide a simple implementation using recursion:
```python
def generate_permutations(s):
# Base case: if the string is empty, return a list with an empty string
if len(s)... | 4,798 | [
{
"from": "human",
"value": "Write a function to generate a list of all permutations of a given string. The function should return all permutations as a list of strings. You can assume that the input string will not contain duplicate characters."
},
{
"from": "gpt",
"value": "You can generate al... |
Write a python function that checks if a given number is a self-dividing number. A self-dividing number is a number that is divisible by every digit it contains. Also, a self-dividing number is not allowed to contain the digit zero. | Here is the code to solve this problem:
```python
def is_self_dividing(num):
digits = [int(digit) for digit in str(num)]
if 0 in digits:
return False
for digit in digits:
if num % digit != 0:
return False
return True
``` | [
"assert is_self_dividing(123456789) == False",
"assert is_self_dividing(102) == False",
"assert is_self_dividing(128) == True"
] | Certainly! Below is a Python function that checks if a given number is a self-dividing number:
```python
def is_self_dividing(num):
# A self-dividing number must not contain the digit zero
# and must be divisible by each of its digits.
original_num = num # keep the original number for reference
i... | 4,799 | [
{
"from": "human",
"value": "Write a python function that checks if a given number is a self-dividing number. A self-dividing number is a number that is divisible by every digit it contains. Also, a self-dividing number is not allowed to contain the digit zero."
},
{
"from": "gpt",
"value": "Cer... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.