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 string is a palindrome or not. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward.
Here is the code to solve this problem: ```python def isPalindrome(s): return s == s[::-1] print(isPalindrome("radar")) print(isPalindrome("12321")) print(isPalindrome("test")) print(isPalindrome("123456")) ```
[ "assert isPalindrome(\"test\") == False", "assert isPalindrome(\"123456\") == False", "assert isPalindrome(\"12321\") == True", "assert isPalindrome(\"radar\") == True" ]
Certainly! To check if a given string is a palindrome, you can write a simple Python function that compares the string to its reverse. Here's one way to do that: ```python def is_palindrome(s): # Normalize the string: remove spaces and convert to lowercase normalized_str = ''.join(s.split()).lower() # Chec...
2,700
[ { "from": "human", "value": "Write a python function to check if a given string is a palindrome or not.\n\nA palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward." }, { "from": "gpt", "value": "Certainly! To check if a given string is a p...
Write a python function to find the number of ways to reach the nth stair if you can climb 1 or 2 steps at a time.
Here is the code to solve this problem: ```python def stair_climb(n): if n <= 1: return n a, b = 1, 2 for _ in range(2, n): a, b = b, a + b return b ```
[ "assert stair_climb(3) == 3", "assert stair_climb(5) == 8", "assert stair_climb(4) == 5" ]
You can solve the problem of counting the number of ways to reach the nth stair using dynamic programming or by using recursion with memoization. Here’s a straightforward way using dynamic programming: ```python def count_ways(n): # Handle base cases if n == 0: return 1 # There's one way to stay at th...
2,701
[ { "from": "human", "value": "Write a python function to find the number of ways to reach the nth stair if you can climb 1 or 2 steps at a time." }, { "from": "gpt", "value": "You can solve the problem of counting the number of ways to reach the nth stair using dynamic programming or by using rec...
Write a python function to check if a given list of integers can form an arithmetic progression.
Here is the code to solve this problem: ```python def can_make_arithmetic_progression(A): if len(A) == 2: return True A.sort() for i in range(1, len(A) - 1): if A[i + 1] - A[i] != A[i] - A[i - 1]: return False return True ```
[ "assert can_make_arithmetic_progression([1, 2, 4]) == False", "assert can_make_arithmetic_progression([3, 5, 7]) == True", "assert can_make_arithmetic_progression([10, 10, 10]) == True" ]
To check if a given list of integers can form an arithmetic progression (AP), we need to ensure that the difference between consecutive elements in the sorted list is constant. Here's a Python function that accomplishes this: ```python def can_form_arithmetic_progression(arr): if len(arr) < 2: return True ...
2,702
[ { "from": "human", "value": "Write a python function to check if a given list of integers can form an arithmetic progression." }, { "from": "gpt", "value": "To check if a given list of integers can form an arithmetic progression (AP), we need to ensure that the difference between consecutive ele...
Write a function to find the index of the last occurrence of a given number in a sorted array.
Here is the code to solve this problem: ```python def find_last_occurrence(A, x): (left, right) = (0, len(A) - 1) result = -1 while left <= right: mid = (left + right) // 2 if x == A[mid]: result = mid left = mid + 1 elif x < A[mid]: right = mid -...
[ "assert find_last_occurrence([2, 4, 1, 5, 6, 6, 8, 9, 9, 9], 6) == 5", "assert find_last_occurrence([2, 5, 5, 5, 6, 6, 8, 9, 9, 9], 5) == 3", "assert find_last_occurrence([2, 3, 5, 5, 6, 6, 8, 9, 9, 9], 5) == 3" ]
To find the index of the last occurrence of a given number in a sorted array, you can implement a binary search algorithm, which is efficient with a time complexity of O(log n). Here's a Python function that demonstrates this approach: ```python def find_last_occurrence(arr, target): left, right = 0, len(arr) - 1 ...
2,703
[ { "from": "human", "value": "Write a function to find the index of the last occurrence of a given number in a sorted array." }, { "from": "gpt", "value": "To find the index of the last occurrence of a given number in a sorted array, you can implement a binary search algorithm, which is efficient...
Write a function to find the most frequent element in a list. If there are multiple elements with the same highest frequency, return all of them in a list.
Here is the code to solve this problem: ```python def most_frequent_elements(lst): from collections import Counter count = Counter(lst) max_count = max(list(count.values())) result = [item for item, freq in count.items() if freq == max_count] return result ```
[ "assert most_frequent_elements([1, 2, 2, 3, 3, 3]) == [3]", "assert most_frequent_elements(['apple', 'banana', 'apple', 'orange', 'banana', 'banana']) == ['banana']", "assert most_frequent_elements([1, 1, 2, 2, 3, 3]) == [1, 2, 3]" ]
Certainly! Below is a Python function that finds the most frequent elements in a list. If there are multiple elements with the same highest frequency, it returns all of them as a list. ```python from collections import Counter def most_frequent_elements(lst): if not lst: # handle empty list return [] ...
2,704
[ { "from": "human", "value": "Write a function to find the most frequent element in a list. If there are multiple elements with the same highest frequency, return all of them in a list." }, { "from": "gpt", "value": "Certainly! Below is a Python function that finds the most frequent elements in a...
Write a python function to find the smallest window in a string containing all characters of another string.
Here is the code to solve this problem: ```python from collections import Counter def min_window(s, t): if not t or not s: return "" dict_t = Counter(t) required = len(dict_t) l, r = 0, 0 formed = 0 window_counts = {} ans = float("inf"), None, None while r < len(s): cha...
[ "assert min_window(\"geeksforgeeks\", \"ork\") == \"ksfor\"", "assert min_window(\"abcdxyz\", \"xyz\") == \"xyz\"", "assert min_window(\"this is a test string\", \"tist\") == \"t stri\"" ]
To find the smallest window in a string containing all the characters of another string, we can use the two-pointer technique along with a frequency count of characters from the target string. Below is a Python function that implements this approach: ```python from collections import Counter, defaultdict def smallest...
2,705
[ { "from": "human", "value": "Write a python function to find the smallest window in a string containing all characters of another string." }, { "from": "gpt", "value": "To find the smallest window in a string containing all the characters of another string, we can use the two-pointer technique a...
Write a python function to calculate the total number of ways to make a change for a given amount using a set of denominations of coins. The function should return the number of distinct combinations of coins that sum up to the given amount.
Here is the code to solve this problem: ```python def coin_change(amount, coins): dp = [0] * (amount + 1) dp[0] = 1 for coin in coins: for x in range(coin, amount + 1): dp[x] += dp[x - coin] return dp[amount] ```
[ "assert coin_change(10, [2, 5, 3, 6]) == 5", "assert coin_change(0, [1, 2, 5]) == 1", "assert coin_change(3, [2]) == 0" ]
Certainly! We can solve this problem using a dynamic programming approach. The idea is to use an array to keep track of the number of ways to make change for each amount up to the target amount. We'll iterate through each coin denomination and update the number of ways to make change for each possible amount. Here's t...
2,706
[ { "from": "human", "value": "Write a python function to calculate the total number of ways to make a change for a given amount using a set of denominations of coins. The function should return the number of distinct combinations of coins that sum up to the given amount." }, { "from": "gpt", "val...
Write a function to check if a number is a happy number. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle wh...
Here is the code to solve this problem: ```python def get_digits(num): digits = [] while num > 0: digits.append(num % 10) num = num // 10 return digits[::-1] def is_happy_number(n): seen = set() while n not in seen: seen.add(n) digits = get_digits(n) n = sum...
[ "assert is_happy_number(19) == True", "assert is_happy_number(2) == False", "assert is_happy_number(7) == True", "assert is_happy_number(4) == False" ]
Certainly! A happy number is determined by iterating through a process where you replace the number with the sum of the squares of its digits until you either reach 1 (indicating it's happy) or fall into a cycle that does not include 1. Here's a Python function to check if a number is a happy number: ```python def is...
2,707
[ { "from": "human", "value": "Write a function to check if a number is a happy number. A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will s...
Write a python function to find the number of trailing zeros in the factorial of a given number.
Here is the code to solve this problem: ```python def count_trailing_zeros(n): count = 0 while n >= 5: n //= 5 count += n return count ```
[ "assert count_trailing_zeros(3) == 0", "assert count_trailing_zeros(5) == 1", "assert count_trailing_zeros(10) == 2" ]
You can find the number of trailing zeros in the factorial of a number by counting how many times 10 is a factor in the numbers multiplied together in the factorial. Since a factor of 10 is made up of a factor of 2 and a factor of 5, and there are generally more factors of 2 than 5, you only need to count the factors o...
2,708
[ { "from": "human", "value": "Write a python function to find the number of trailing zeros in the factorial of a given number." }, { "from": "gpt", "value": "You can find the number of trailing zeros in the factorial of a number by counting how many times 10 is a factor in the numbers multiplied ...
Write a function to find the maximum number of unique candy types that can be distributed equally to two sisters.
Here is the code to solve this problem: ```python def distribute_candies(candies): candies_map = dict() n_candies = len(candies) for candi in candies: if candi not in candies_map: candies_map[candi] = 1 else: candies_map[candi] += 1 candies_list = sorted(candies_...
[ "assert distribute_candies([1,2,2,3,4,5])==3", "assert distribute_candies([1,1,2,3])==2", "assert distribute_candies([1,1,2,2,3,3])==3" ]
To solve the problem of finding the maximum number of unique candy types that can be distributed equally to two sisters, we can take the following approach: 1. Count the total number of candies, considering the different types. 2. Determine the maximum number of unique candy types that can be given to each sister, whi...
2,709
[ { "from": "human", "value": "Write a function to find the maximum number of unique candy types that can be distributed equally to two sisters." }, { "from": "gpt", "value": "To solve the problem of finding the maximum number of unique candy types that can be distributed equally to two sisters, w...
Write a python function to sort a list of tuples based on the second element of the tuples.
Here is the code to solve this problem: ```python def sort_tuples(tuples, order): tuples_sorted = sorted(tuples, key=lambda x: x[1]) if order == "desc": tuples_sorted.reverse() return tuples_sorted ```
[ "assert sort_tuples([(1, 2), (3, 1), (5, 0)], \"desc\") == [(1, 2), (3, 1), (5, 0)]", "assert sort_tuples([(1, 2), (3, 1), (5, 0)], \"asc\") == [(5, 0), (3, 1), (1, 2)]", "assert sort_tuples([(1, 2), (3, 2), (5, 2)], \"asc\") == [(1, 2), (3, 2), (5, 2)]" ]
You can sort a list of tuples based on the second element of each tuple using the `sorted()` function or the `.sort()` method with a custom key. Here’s a function that demonstrates both approaches: ```python def sort_tuples_by_second_element(tuples_list): # Using the sorted() function sorted_list = sorted(tupl...
2,710
[ { "from": "human", "value": "Write a python function to sort a list of tuples based on the second element of the tuples." }, { "from": "gpt", "value": "You can sort a list of tuples based on the second element of each tuple using the `sorted()` function or the `.sort()` method with a custom key....
Write a function to find the first non-repeating character in a given string.
Here is the code to solve this problem: ```python from collections import defaultdict def find_first_non_repeating(s): charcount = defaultdict(int) for c in s: charcount[c] += 1 for c in s: if charcount[c] == 1: return c return None ```
[ "assert find_first_non_repeating('algorithm') == 'a'", "assert find_first_non_repeating('programming') == 'p'", "assert find_first_non_repeating('mississippi') == 'm'" ]
Certainly! Here’s a simple Python function that finds the first non-repeating character in a given string: ```python def first_non_repeating_character(s): # Create a dictionary to count occurrences of each character char_count = {} # Count each character in the string for char in s: if cha...
2,711
[ { "from": "human", "value": "Write a function to find the first non-repeating character in a given string." }, { "from": "gpt", "value": "Certainly! Here’s a simple Python function that finds the first non-repeating character in a given string:\n\n```python\ndef first_non_repeating_character(s):...
Write a function to find the k smallest elements in a given list of integers.
Here is the code to solve this problem: ```python def k_smallest(numbers, k): numbers.sort() return numbers[:k] ```
[ "assert k_smallest([10, 6, 12, 3, 18, 14], 2) == [3, 6]", "assert k_smallest([4, 1, 7, 3, 8, 5], 3) == [1, 3, 4]", "assert k_smallest([8, 4, 14, 3, 2, 1], 4) == [1, 2, 3, 4]" ]
Certainly! You can find the k smallest elements in a given list of integers by utilizing Python's built-in capabilities. One common approach is to use the `heapq` module, which provides a way to efficiently retrieve the k smallest elements. Here’s how you can implement that in a function: ```python import heapq def k...
2,712
[ { "from": "human", "value": "Write a function to find the k smallest elements in a given list of integers." }, { "from": "gpt", "value": "Certainly! You can find the k smallest elements in a given list of integers by utilizing Python's built-in capabilities. One common approach is to use the `he...
Write a python function to find the number of ways to reach the last cell of a matrix of size 'n' x 'm' from the first cell, moving only right or down.
Here is the code to solve this problem: ```python def countPaths(n, m): # Initialize the first row and column of the DP table dp = [[0 for _ in range(m)] for _ in range(n)] for i in range(n): dp[i][0] = 1 for j in range(m): dp[0][j] = 1 for i in range(1, n): for j in ...
[ "assert countPaths(2, 2) == 2", "assert countPaths(2, 3) == 3", "assert countPaths(3, 3) == 6" ]
To solve the problem of finding the number of ways to reach the bottom-right cell of an `n x m` matrix from the top-left cell while only moving right or down, we can use combinatorial mathematics or dynamic programming. ### Combinatorial Approach The key realization is that to reach the last cell from the first cell ...
2,713
[ { "from": "human", "value": "Write a python function to find the number of ways to reach the last cell of a matrix of size 'n' x 'm' from the first cell, moving only right or down." }, { "from": "gpt", "value": "To solve the problem of finding the number of ways to reach the bottom-right cell of...
Write a python function to find the largest subarray with an equal number of 0's and 1's in a given binary array.
Here is the code to solve this problem: ```python def largest_subarray_equal_zeros_ones(arr): count = 0 max_length = 0 sum_map = {0: -1} for i in range(len(arr)): if arr[i] == 0: count -= 1 else: count += 1 if count in sum_map: max_length = ma...
[ "assert largest_subarray_equal_zeros_ones([0, 0, 1, 0, 1, 0, 0, 1]) == 6", "assert largest_subarray_equal_zeros_ones([1, 1, 1, 1]) == 0", "assert largest_subarray_equal_zeros_ones([0, 1, 0, 1, 0, 1, 1]) == 6" ]
To find the largest subarray with an equal number of 0's and 1's in a given binary array, we can use a hash map (dictionary in Python) to keep track of the cumulative sums. The idea is to replace 0's with -1. This way, if we find the same cumulative sum at two different indices, it indicates that the subarray between t...
2,714
[ { "from": "human", "value": "Write a python function to find the largest subarray with an equal number of 0's and 1's in a given binary array." }, { "from": "gpt", "value": "To find the largest subarray with an equal number of 0's and 1's in a given binary array, we can use a hash map (dictionar...
Write a python function to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings.
Here is the code to solve this problem: ```python def count_strings(lst): count = 0 for s in lst: if len(s) > 1 and s[0] == s[-1]: count += 1 return count ```
[ "assert count_strings([\"abc\", \"xyz\", \"aba\", \"1221\"]) == 2", "assert count_strings([\"aa\", \"bb\", \"cc\", \"dd\"]) == 4", "assert count_strings([\"a\", \"b\", \"c\"]) == 0" ]
Certainly! You can create a Python function that iterates through a list of strings and counts how many of those strings have a length of 2 or more and where the first and last characters are the same. Here's one way to implement such a function: ```python def count_matching_strings(strings): count = 0 for s i...
2,715
[ { "from": "human", "value": "Write a python function to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings." }, { "from": "gpt", "value": "Certainly! You can create a Python function that iterates through a list...
Write a function to find the kth largest element in a given unsorted list of integers. Note that it is the kth largest, not the kth distinct largest. For example, in list [3,2,1,5,6,4] and k = 2, the 2nd largest element is 5, not 4.
Here is the code to solve this problem: ```python def kth_largest(nums, k): nums.sort(reverse=True) return nums[k-1] ```
[ "assert kth_largest([3,2,1,5,6,4], 2) == 5", "assert kth_largest([3,2,3,1,2,4,5,5,6], 4) == 4", "assert kth_largest([1,2,3,4,5,6,7,8,9], 1) == 9" ]
You can find the k-th largest element in an unsorted list of integers using various methods. One efficient way to achieve this is by using a heap data structure. Here's a Python function that uses the `heapq` module to find the k-th largest element: ```python import heapq def find_kth_largest(nums, k): # Create a...
2,716
[ { "from": "human", "value": "Write a function to find the kth largest element in a given unsorted list of integers. Note that it is the kth largest, not the kth distinct largest. For example, in list [3,2,1,5,6,4] and k = 2, the 2nd largest element is 5, not 4." }, { "from": "gpt", "value": "You...
Write a python function to return the maximum integer in a list. If the list is empty or contains non-integer values, the function should return None.
Here is the code to solve this problem: ```python def find_max_integer(lst): if not lst or not all(isinstance(x, int) for x in lst): return None return max(lst) ```
[ "assert find_max_integer([]) == None", "assert find_max_integer([1, 2, 'a', 3]) == None", "assert find_max_integer([1, 3, 2, 5, 4]) == 5" ]
Certainly! Below is a Python function that checks for an empty list or any non-integer values before attempting to find and return the maximum integer. If the list is valid (non-empty and contains only integers), it returns the maximum integer; otherwise, it returns `None`. ```python def max_integer(input_list): #...
2,717
[ { "from": "human", "value": "Write a python function to return the maximum integer in a list. If the list is empty or contains non-integer values, the function should return None." }, { "from": "gpt", "value": "Certainly! Below is a Python function that checks for an empty list or any non-intege...
Write a function that takes two lists as input and returns the list of elements that are common in both input lists. The function should preserve the order of elements as they appear in the first list.
Here is the code to solve this problem: ```python def common_elements(list1, list2): return [x for x in list1 if x in list2] ```
[ "assert common_elements([1, 2, 3, 4, 5], [4, 5, 6, 7, 8]) == [4, 5]", "assert common_elements([10, 20, 30, 40], [50, 60, 70]) == []", "assert common_elements(['apple', 'banana', 'cherry'], ['cherry', 'banana', 'date']) == ['banana', 'cherry']" ]
You can achieve this by defining a function that uses list comprehension to iterate over the first list and checks for membership in the second list. Here’s how you can implement that in Python: ```python def common_elements(list1, list2): # Create a set from list2 for O(1) lookups set2 = set(list2) # Use ...
2,718
[ { "from": "human", "value": "Write a function that takes two lists as input and returns the list of elements that are common in both input lists. The function should preserve the order of elements as they appear in the first list." }, { "from": "gpt", "value": "You can achieve this by defining a...
Write a python function to calculate the factorial of a number using recursion.
Here is the code to solve this problem: ```python def factorial_recursive(n): if n == 0: return 1 else: return n * factorial_recursive(n-1) ```
[ "assert factorial_recursive(5) == 120", "assert factorial_recursive(0) == 1", "assert factorial_recursive(1) == 1" ]
Certainly! A recursive function to calculate the factorial of a number can be defined as follows: ```python def factorial(n): # Base case: factorial of 0 and 1 is 1 if n == 0 or n == 1: return 1 # Recursive case: n! = n * (n-1)! else: return n * factorial(n - 1) # Example usage: result...
2,719
[ { "from": "human", "value": "Write a python function to calculate the factorial of a number using recursion." }, { "from": "gpt", "value": "Certainly! A recursive function to calculate the factorial of a number can be defined as follows:\n\n```python\ndef factorial(n):\n # Base case: factoria...
Write a python function to find the nth Hexagonal number. A Hexagonal number is a figurate number that represents a hexagon with a dot at the center and all other dots surrounding the center dot in a hexagonal lattice. The nth Hexagonal number is given by the formula: H(n) = 2n^2 - n
Here is the code to solve this problem: ```python def hexagonal_number(n): return n * (2 * n - 1) ```
[ "assert hexagonal_number(1) == 1", "assert hexagonal_number(2) == 6", "assert hexagonal_number(3) == 15", "assert hexagonal_number(5) == 45", "assert hexagonal_number(4) == 28" ]
You can create a Python function to calculate the nth Hexagonal number using the provided formula. Here’s a simple implementation: ```python def hexagonal_number(n): """Return the nth Hexagonal number.""" if n < 1: raise ValueError("n must be a positive integer") return 2 * n ** 2 - n # Example us...
2,720
[ { "from": "human", "value": "Write a python function to find the nth Hexagonal number. A Hexagonal number is a figurate number that represents a hexagon with a dot at the center and all other dots surrounding the center dot in a hexagonal lattice.\n\nThe nth Hexagonal number is given by the formula: H(n) = ...
Write a python function to determine if a given list of numbers is sorted in ascending order.
Here is the code to solve this problem: ```python def is_sorted(nums): for i in range(1, len(nums)): if nums[i] < nums[i-1]: return False return True ```
[ "assert is_sorted([1, 1, 2, 3, 5]) == True", "assert is_sorted([1, 2, 3, 4, 5]) == True", "assert is_sorted([5, 4, 3, 2, 1]) == False", "assert is_sorted([1, 3, 5, 7, 9]) == True", "assert is_sorted([10, 8, 6, 4, 2]) == False" ]
Certainly! Below is a Python function that checks if a given list of numbers is sorted in ascending order: ```python def is_sorted_ascending(numbers): """ Check if the given list of numbers is sorted in ascending order. Args: numbers (list): A list of numbers. Returns: bool: True if the list ...
2,721
[ { "from": "human", "value": "Write a python function to determine if a given list of numbers is sorted in ascending order." }, { "from": "gpt", "value": "Certainly! Below is a Python function that checks if a given list of numbers is sorted in ascending order:\n\n```python\ndef is_sorted_ascendi...
Write a python function to return the largest number that can be formed from the given list of digits.
Here is the code to solve this problem: ```python def compare(n1, n2): return int(str(n1) + str(n2)) > int(str(n2) + str(n1)) def max_number(nums): for i in range(len(nums)): for j in range(len(nums) - 1, i, -1): if not compare(nums[j - 1], nums[j]): nums[j - 1], nums[j] = ...
[ "assert max_number([1, 2, 3]) == 321", "assert max_number([9, 3, 4, 0, 1]) == 94310", "assert max_number([3, 30, 34, 5, 9]) == 9534330" ]
You can achieve this by converting each digit to a string, sorting these strings in a way that will yield the largest possible number when concatenated, and then joining them back together. Here’s a Python function that implements this logic: ```python def largest_number(digits): # Convert all digits to strings ...
2,722
[ { "from": "human", "value": "Write a python function to return the largest number that can be formed from the given list of digits." }, { "from": "gpt", "value": "You can achieve this by converting each digit to a string, sorting these strings in a way that will yield the largest possible number...
Write a python function to find the length of the longest balanced parentheses substring for the given string s.
Here is the code to solve this problem: ```python def longest_balanced_parentheses(s): stack = [] max_length = 0 start = -1 for i in range(len(s)): if s[i] == '(': stack.append(i) else: if not stack: start = i else: st...
[ "assert longest_balanced_parentheses(\")()())\") == 4", "assert longest_balanced_parentheses(\"(()\") == 2", "assert longest_balanced_parentheses(\"\") == 0" ]
To find the length of the longest balanced parentheses substring in a given string `s`, we can use a stack-based approach. This method allows us to keep track of the indices of unmatched parentheses and find the length of valid substrings efficiently. Here's a Python function to accomplish this: ```python def longest...
2,723
[ { "from": "human", "value": "Write a python function to find the length of the longest balanced parentheses substring for the given string s." }, { "from": "gpt", "value": "To find the length of the longest balanced parentheses substring in a given string `s`, we can use a stack-based approach. ...
Write a python function to find the number of connected components in an undirected graph.
Here is the code to solve this problem: ```python from collections import deque def count_connected_components(n, edges): def bfs(node): queue = deque([node]) visited.add(node) while queue: current = queue.popleft() for neighbor in adj_list[current]: ...
[ "assert count_connected_components(5, [[1, 2], [5, 3], [3, 4]]) == 2", "assert count_connected_components(4, [[1, 2], [2, 3], [3, 4]]) == 1", "assert count_connected_components(3, []) == 3" ]
To find the number of connected components in an undirected graph, you can use Depth First Search (DFS) or Breadth First Search (BFS) to explore the graph. Below is a Python function that demonstrates how to achieve this using DFS. The function takes an adjacency list representation of the graph as input and returns th...
2,724
[ { "from": "human", "value": "Write a python function to find the number of connected components in an undirected graph." }, { "from": "gpt", "value": "To find the number of connected components in an undirected graph, you can use Depth First Search (DFS) or Breadth First Search (BFS) to explore ...
Write a python function to find the most common element in a list.
Here is the code to solve this problem: ```python from collections import Counter def find_most_common_element(lst): counter = Counter(lst) max_count = max(list(counter.values())) return [item for item, count in counter.items() if count == max_count][0] ```
[ "assert find_most_common_element([1,2,2,3,3,3]) == 3", "assert find_most_common_element(['a','b','a','c','a']) == 'a'", "assert find_most_common_element([5,5,5,5,6,6,7,8,9,9,9,9,9]) == 9" ]
To find the most common element in a list in Python, you can use the `collections.Counter` class, which is ideal for counting hashable objects. Here's a function that does exactly that: ```python from collections import Counter def most_common_element(lst): if not lst: return None # Return None if the li...
2,725
[ { "from": "human", "value": "Write a python function to find the most common element in a list." }, { "from": "gpt", "value": "To find the most common element in a list in Python, you can use the `collections.Counter` class, which is ideal for counting hashable objects. Here's a function that do...
Write a python function that converts a list of numbers into a list of their corresponding ASCII characters.
Here is the code to solve this problem: ```python def convertAscii(numberList): asciiList = [] for number in numberList: asciiList.append(chr(number)) return asciiList ```
[ "assert convertAscii([100, 101, 102]) == ['d', 'e', 'f']", "assert convertAscii([97, 98, 99]) == ['a', 'b', 'c']", "assert convertAscii([103, 104, 105]) == ['g', 'h', 'i']" ]
You can create a Python function to convert a list of numbers into their corresponding ASCII characters using the `chr()` function in Python. Here’s how you can do it: ```python def numbers_to_ascii(numbers): """ Convert a list of numbers into their corresponding ASCII characters. Parameters: numbers ...
2,726
[ { "from": "human", "value": "Write a python function that converts a list of numbers into a list of their corresponding ASCII characters." }, { "from": "gpt", "value": "You can create a Python function to convert a list of numbers into their corresponding ASCII characters using the `chr()` funct...
Write a python function to find the kth largest element in a given list. The function should return the kth largest element.
Here is the code to solve this problem: ```python def kth_largest(nums, k): nums.sort(reverse=True) return nums[k-1] ```
[ "assert kth_largest([3,2,1,5,6,4], 2) == 5", "assert kth_largest([3,2,3,1,2,4,5,5,6], 4) == 4", "assert kth_largest([1,2,3,4,5,6,7,8,9], 1) == 9" ]
Certainly! To find the kth largest element in a list, we can make use of Python's built-in functionality such as sorting or using a heap. Below is a simple implementation using sorting, which is straightforward and easy to understand: ```python def kth_largest(nums, k): if k <= 0 or k > len(nums): raise Va...
2,727
[ { "from": "human", "value": "Write a python function to find the kth largest element in a given list. The function should return the kth largest element." }, { "from": "gpt", "value": "Certainly! To find the kth largest element in a list, we can make use of Python's built-in functionality such a...
Write a function to find the factorial of a given number.
Here is the code to solve this problem: ```python def find_factorial(n): if n == 0: return 1 else: return n * find_factorial(n-1) ```
[ "assert find_factorial(4) == 24", "assert find_factorial(6) == 720", "assert find_factorial(5) == 120" ]
Certainly! Below is a Python function that calculates the factorial of a given number using recursion. Additionally, I've included an iterative version as well. ### Recursive Version ```python def factorial_recursive(n): if n < 0: raise ValueError("Factorial is not defined for negative numbers") elif ...
2,728
[ { "from": "human", "value": "Write a function to find the factorial of a given number." }, { "from": "gpt", "value": "Certainly! Below is a Python function that calculates the factorial of a given number using recursion. Additionally, I've included an iterative version as well.\n\n### Recursive ...
Write a function to find the sum of all the multiples of 3 or 5 below a given number.
Here is the code to solve this problem: ```python def sum_of_multiples(n): sum = 0 for i in range(1, n): if i % 3 == 0 or i % 5 == 0: sum += i return sum ```
[ "assert sum_of_multiples(10)==23", "assert sum_of_multiples(20)==78", "assert sum_of_multiples(15)==45" ]
Certainly! Below is a Python function that calculates the sum of all multiples of 3 or 5 below a given number: ```python def sum_of_multiples(n): total_sum = 0 for i in range(n): if i % 3 == 0 or i % 5 == 0: total_sum += i return total_sum # Example usage: number = 10 result = sum_of_m...
2,729
[ { "from": "human", "value": "Write a function to find the sum of all the multiples of 3 or 5 below a given number." }, { "from": "gpt", "value": "Certainly! Below is a Python function that calculates the sum of all multiples of 3 or 5 below a given number:\n\n```python\ndef sum_of_multiples(n):\...
Given a list of integers, write a function to find the maximum product of two adjacent elements in the list.
Here is the code to solve this problem: ```python def max_adjacent_product(nums): max_product = nums[0] * nums[1] for i in range(1, len(nums) - 1): product = nums[i] * nums[i + 1] if product > max_product: max_product = product return max_product ```
[ "assert max_adjacent_product([3, 6, -2, -5, 7, 3]) == 21", "assert max_adjacent_product([9, 5, 10, 2, 24, -1, -48]) == 50", "assert max_adjacent_product([1, 2]) == 2" ]
You can achieve this by iterating through the list and calculating the products of each pair of adjacent elements. Here’s a simple Python function that implements this: ```python def max_adjacent_product(nums): if len(nums) < 2: raise ValueError("List must contain at least two integers.") max_prod...
2,730
[ { "from": "human", "value": "Given a list of integers, write a function to find the maximum product of two adjacent elements in the list." }, { "from": "gpt", "value": "You can achieve this by iterating through the list and calculating the products of each pair of adjacent elements. Here’s a sim...
Write a function to find all numbers in a list that are divisible by a given divisor and are greater than a given threshold. The function should return a list of these numbers.
Here is the code to solve this problem: ```python def find_divisible(numbers, divisor, threshold): result = [] for number in numbers: if number > threshold and number % divisor == 0: result.append(number) return result ```
[ "assert find_divisible([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2, 4) == [6, 8, 10]", "assert find_divisible([100, 200, 300, 400], 100, 150) == [200, 300, 400]", "assert find_divisible([10, 20, 30, 40, 50], 5, 15) == [20, 30, 40, 50]" ]
You can achieve this by defining a function in Python that iterates through the list of numbers, checks if each number is divisible by the specified divisor and greater than the specified threshold, and collects these numbers into a list. Here’s an example implementation: ```python def find_divisible_and_greater(numbe...
2,731
[ { "from": "human", "value": "Write a function to find all numbers in a list that are divisible by a given divisor and are greater than a given threshold. The function should return a list of these numbers." }, { "from": "gpt", "value": "You can achieve this by defining a function in Python that ...
Write a python function to find the length of the longest consecutive elements sequence in an unsorted array.
Here is the code to solve this problem: ```python def longestConsecutive(nums): nums_set = set(nums) longest_streak = 0 for num in nums_set: if num - 1 not in nums_set: current_num = num current_streak = 1 while current_num + 1 in nums_set: curr...
[ "assert longestConsecutive([0,3,7,2,5,8,4,6,0,1]) == 9", "assert longestConsecutive([9,1,-3,2,4,8,3,-1,6,-2,-4,7]) == 4", "assert longestConsecutive([100, 4, 200, 1, 3, 2]) == 4" ]
Certainly! You can solve the problem of finding the length of the longest consecutive elements sequence in an unsorted array using a set for efficient lookups. Here's a Python function that implements this approach: ```python def longest_consecutive(nums): if not nums: return 0 num_set = set(nums)...
2,732
[ { "from": "human", "value": "Write a python function to find the length of the longest consecutive elements sequence in an unsorted array." }, { "from": "gpt", "value": "Certainly! You can solve the problem of finding the length of the longest consecutive elements sequence in an unsorted array u...
Write a function to find the sum of the digits of a number until the sum becomes a single digit.
Here is the code to solve this problem: ```python def single_digit_sum(num): while num >= 10: num = sum(int(digit) for digit in str(num)) return num ```
[ "assert single_digit_sum(987654321) == 9", "assert single_digit_sum(12345) == 6", "assert single_digit_sum(0) == 0" ]
You can achieve this by implementing a function that continuously sums the digits of a number until the result is a single digit. Below is a Python function that does this: ```python def sum_of_digits_until_single_digit(n): # Ensure n is non-negative n = abs(n) while n >= 10: n = sum(int(digit...
2,733
[ { "from": "human", "value": "Write a function to find the sum of the digits of a number until the sum becomes a single digit." }, { "from": "gpt", "value": "You can achieve this by implementing a function that continuously sums the digits of a number until the result is a single digit. Below is ...
Write a function that takes two strings and determines if the second string is a rotation of the first string.
Here is the code to solve this problem: ```python def is_rotation(s1, s2): if len(s1) != len(s2): return False s1s1 = s1 + s1 return s2 in s1s1 ```
[ "assert is_rotation(\"hello\",\"lohel\") == True", "assert is_rotation(\"waterbottle\",\"erbottlewat\") == True", "assert is_rotation(\"world\",\"dlrow\") == False" ]
To determine if the second string is a rotation of the first string, you can use the following approach: 1. First, check if both strings have the same length. If they don't, the second string cannot be a rotation of the first. 2. Then, concatenate the first string with itself. This will provide a new string that conta...
2,734
[ { "from": "human", "value": "Write a function that takes two strings and determines if the second string is a rotation of the first string." }, { "from": "gpt", "value": "To determine if the second string is a rotation of the first string, you can use the following approach:\n\n1. First, check i...
Write a function to check if a string can be permuted to form a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. For a string to be permutable into a palindrome, it must have at most one character with an odd count.
Here is the code to solve this problem: ```python from collections import defaultdict def can_permute_palindrome(s: str) -> bool: if not s: return False strCntMap = defaultdict(int) for ch in s: strCntMap[ch] += 1 oddCnt = 0 for key, value in strCntMap.items(): if value ...
[ "assert can_permute_palindrome(\"aab\") == True", "assert can_permute_palindrome(\"aabbccde\") == False", "assert can_permute_palindrome(\"test\") == False", "assert can_permute_palindrome(\"carerac\") == True", "assert can_permute_palindrome(\"aabbccd\") == True", "assert can_permute_palindrome(\"aabbcc\...
To determine if a string can be permuted to form a palindrome, we can follow these steps: 1. Count the frequency of each character in the string. 2. Count how many characters have an odd frequency. 3. A string can be permuted to form a palindrome if there is at most one character with an odd frequency count. Here's a...
2,735
[ { "from": "human", "value": "Write a function to check if a string can be permuted to form a palindrome.\n\nA palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. For a string to be permutable into a palindrome, it must have at most one character wi...
Write a function to determine if a string is a valid pin for an ATM. A valid pin is a string that: - Consists only of digits. - Has a length between 4 and 6 characters. - Does not start with a zero.
Here is the code to solve this problem: ```python def is_valid_pin(pin): if not pin.isdigit(): return False if len(pin) < 4 or len(pin) > 6: return False if pin[0] == '0': return False return True ```
[ "assert is_valid_pin(\"123456\") == True", "assert is_valid_pin(\"0123\") == False", "assert is_valid_pin(\"1234\") == True", "assert is_valid_pin(\"a234\") == False", "assert is_valid_pin(\"1234567\") == False" ]
You can create a function in Python to determine if a string is a valid PIN based on the provided criteria. Below is an example implementation of such a function: ```python def is_valid_pin(pin): # Check the length of the pin if len(pin) < 4 or len(pin) > 6: return False # Check if the pin con...
2,736
[ { "from": "human", "value": "Write a function to determine if a string is a valid pin for an ATM.\n\nA valid pin is a string that:\n- Consists only of digits.\n- Has a length between 4 and 6 characters.\n- Does not start with a zero." }, { "from": "gpt", "value": "You can create a function in Py...
Write a function to check if a given string is a valid URL.
Here is the code to solve this problem: ```python import re def is_valid_URL(url): regex = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... r'localhost|' #localhost... r'\d{1,3}\....
[ "assert is_valid_URL(\"not a url\")==False", "assert is_valid_URL(\"https://www.google.com\")==True", "assert is_valid_URL(\"ftp://example.com/file.txt\")==True", "assert is_valid_URL(\"http://\")==False" ]
To check if a given string is a valid URL in Python, you can use the `re` module for regular expressions or the built-in `urllib` library. Below, I'll provide implementations using both methods. The regular expression method is more flexible, while the `urlparse` method is more robust. ### Method 1: Using Regular Expr...
2,737
[ { "from": "human", "value": "Write a function to check if a given string is a valid URL." }, { "from": "gpt", "value": "To check if a given string is a valid URL in Python, you can use the `re` module for regular expressions or the built-in `urllib` library. Below, I'll provide implementations u...
Write a python function to find the most common character in a given string and return its frequency.
Here is the code to solve this problem: ```python def most_common_char(s): freq = {} for c in s: if c in freq: freq[c] += 1 else: freq[c] = 1 return max(freq.values()) ```
[ "assert most_common_char(\"programming\") == 2", "assert most_common_char(\"aaaaaaa\") == 7", "assert most_common_char(\"hello world\") == 3" ]
Certainly! Here’s a Python function that takes a string as input, finds the most common character in that string, and returns both the character and its frequency: ```python def most_common_character(s): # Create a dictionary to count the frequency of each character frequency = {} # Count the frequenc...
2,738
[ { "from": "human", "value": "Write a python function to find the most common character in a given string and return its frequency." }, { "from": "gpt", "value": "Certainly! Here’s a Python function that takes a string as input, finds the most common character in that string, and returns both the...
Write a function to find the minimum number of operations needed to convert a string to its palindrome version where the operation can either be an insertion, deletion, or substitution of a character.
Here is the code to solve this problem: ```python def min_operations_to_palindrome(s: str) -> int: n = len(s) dp = [[0] * (n + 1) for _ in range(n + 1)] for i in range(n): for j in range(n - 1, -1, -1): if s[i] == s[j]: dp[i + 1][j] = dp[i][j + 1] + 1 else: ...
[ "assert min_operations_to_palindrome(\"abc\") == 2", "assert min_operations_to_palindrome(\"abccba\") == 0", "assert min_operations_to_palindrome(\"abcdedcba\") == 0" ]
To solve this problem, we can utilize dynamic programming to calculate the minimum number of operations required to convert a given string into its palindrome version. We will define a function `min_operations_to_palindrome` that implements this logic. The main idea is to compare characters from the beginning and the ...
2,739
[ { "from": "human", "value": "Write a function to find the minimum number of operations needed to convert a string to its palindrome version where the operation can either be an insertion, deletion, or substitution of a character." }, { "from": "gpt", "value": "To solve this problem, we can utili...
Write a python function to convert a given string to uppercase without using the built-in `upper()` function.
Here is the code to solve this problem: ```python def to_uppercase(s): uppercase_str = "" for char in s: if 'a' <= char <= 'z': # Convert lowercase to uppercase by subtracting the difference in ASCII values uppercase_str += chr(ord(char) - (ord('a') - ord('A'))) else: ...
[ "assert to_uppercase(\"Python Programming\") == \"PYTHON PROGRAMMING\"", "assert to_uppercase(\"hello\") == \"HELLO\"", "assert to_uppercase(\"world\") == \"WORLD\"" ]
You can convert a string to uppercase without using the built-in `upper()` function by iterating through each character in the string and converting it to uppercase based on its ASCII value. Here's how you can do it: ```python def to_uppercase(input_string): # Initialize an empty string to store the result res...
2,740
[ { "from": "human", "value": "Write a python function to convert a given string to uppercase without using the built-in `upper()` function." }, { "from": "gpt", "value": "You can convert a string to uppercase without using the built-in `upper()` function by iterating through each character in the...
Write a python function to find the longest subsequence of consecutive characters in a given string.
Here is the code to solve this problem: ```python def longest_consecutive_subsequence(s): max_length = 1 current_length = 1 for i in range(1, len(s)): if s[i] == s[i-1]: current_length += 1 max_length = max(max_length, current_length) else: current_length...
[ "assert longest_consecutive_subsequence(\"aaabbbccc\") == 3", "assert longest_consecutive_subsequence(\"aabbbcc\") == 3", "assert longest_consecutive_subsequence(\"abcdefg\") == 1" ]
Certainly! You can accomplish this by iterating through the string and keeping track of the longest subsequence of consecutive characters. Here's a Python function that does exactly that: ```python def longest_consecutive_subsequence(s): if not s: return "" max_length = 1 current_length = 1 lo...
2,741
[ { "from": "human", "value": "Write a python function to find the longest subsequence of consecutive characters in a given string." }, { "from": "gpt", "value": "Certainly! You can accomplish this by iterating through the string and keeping track of the longest subsequence of consecutive characte...
Write a function to compute the factorial of a given number and return the number of trailing zeroes in the factorial.
Here is the code to solve this problem: ```python def trailing_zeroes_factorial(n): result = 0 while n > 0: n = n // 5 result += n return result ```
[ "assert trailing_zeroes_factorial(5)==1", "assert trailing_zeroes_factorial(10)==2", "assert trailing_zeroes_factorial(25)==6" ]
Certainly! To compute the number of trailing zeroes in the factorial of a given number, we can use the following approach: The number of trailing zeroes in `n!` (the factorial of `n`) is determined by how many times `10` is a factor in the numbers that make up the factorial. Since `10` is made up of the factors `2` an...
2,742
[ { "from": "human", "value": "Write a function to compute the factorial of a given number and return the number of trailing zeroes in the factorial." }, { "from": "gpt", "value": "Certainly! To compute the number of trailing zeroes in the factorial of a given number, we can use the following appr...
Write a python function to find the maximum number of nested list.
Here is the code to solve this problem: ```python def max_nested_list(lst): max_depth = [1] for i in lst: if isinstance(i, list): max_depth.append(1 + max_nested_list(i)) return max(max_depth) ```
[ "assert max_nested_list([1,[2,[3,[4]]]]) == 4", "assert max_nested_list([[1,2],[3,4,[5,6]],[7]]) == 3", "assert max_nested_list([1,2,3]) == 1" ]
To find the maximum depth of nested lists in Python, you can implement a recursive function. This function will go through each element of the list and, if it encounters another list, it will call itself recursively to check the depth of that nested list. Here's how you can implement this: ```python def max_nested_dep...
2,743
[ { "from": "human", "value": "Write a python function to find the maximum number of nested list." }, { "from": "gpt", "value": "To find the maximum depth of nested lists in Python, you can implement a recursive function. This function will go through each element of the list and, if it encounters...
Write a python function to find the maximum depth of a binary tree.
Here is the code to solve this problem: ```python class TreeNode: """Definition for a binary tree node""" def __init__(self, value): self.value = value self.left = None self.right = None def max_depth(root): if root is None: return 0 else: left_depth = max_dept...
[ "assert max_depth(root2) == 4", "assert max_depth(None) == 0", "assert max_depth(root1) == 2" ]
Certainly! To find the maximum depth of a binary tree, we can define a recursive function that traverses the tree. The maximum depth is the maximum number of nodes along the longest path from the root node down to the farthest leaf node. Here's a Python implementation of a `TreeNode` class and a function to calculate ...
2,744
[ { "from": "human", "value": "Write a python function to find the maximum depth of a binary tree." }, { "from": "gpt", "value": "Certainly! To find the maximum depth of a binary tree, we can define a recursive function that traverses the tree. The maximum depth is the maximum number of nodes alon...
Write a function to find the number of occurrences of an element in a sorted array using binary search.
Here is the code to solve this problem: ```python def count_occurrences(A, x): def find_leftmost(): left, right = 0, len(A) - 1 while left < right: mid = left + (right - left) // 2 if A[mid] < x: left = mid + 1 else: right = mid ...
[ "assert count_occurrences([1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3) == 3", "assert count_occurrences([1, 1, 2, 2, 2, 3, 4, 4, 4, 4], 2) == 3", "assert count_occurrences([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5) == 1" ]
Sure! To find the number of occurrences of an element in a sorted array, we can use a binary search algorithm to locate the first and last occurrences of the element. Here's how you can do this in Python: ```python def count_occurrences(arr, target): def find_first(arr, target): left, right = 0, len(arr) -...
2,745
[ { "from": "human", "value": "Write a function to find the number of occurrences of an element in a sorted array using binary search." }, { "from": "gpt", "value": "Sure! To find the number of occurrences of an element in a sorted array, we can use a binary search algorithm to locate the first an...
Write a python function to find the number of divisors of a given number.
Here is the code to solve this problem: ```python def num_Divisors(n): front = [] back = [] root = int(n**(1/2)) for i in range(1, root+1): if (n%i == 0) and (i*i != n): front.append(i) if root*root == n: back.append(root) for f in list(reversed(front)): back...
[ "assert num_Divisors(10) == 4", "assert num_Divisors(28) == 6", "assert num_Divisors(11) == 2" ]
You can find the number of divisors of a given number by counting how many integers divide the number evenly. The most efficient way to do this is to iterate only up to the square root of the number, checking for divisibility. For each divisor found, you can also count its corresponding divisor (i.e., if `d` is a divis...
2,746
[ { "from": "human", "value": "Write a python function to find the number of divisors of a given number." }, { "from": "gpt", "value": "You can find the number of divisors of a given number by counting how many integers divide the number evenly. The most efficient way to do this is to iterate only...
Write a python function that checks if a given array represents a valid permutation. A permutation is a sequence containing each element from 1 to N once, and only once.
Here is the code to solve this problem: ```python def check_valid_permutation(A): A.sort() for i in range(len(A)): if A[i] != i+1: return False return True ```
[ "assert check_valid_permutation([1,2,4]) == False", "assert check_valid_permutation([1,2,3]) == True", "assert check_valid_permutation([1,3,3]) == False", "assert check_valid_permutation([3,1,2]) == True" ]
To check if a given array represents a valid permutation of the integers from 1 to N, we can utilize a straightforward approach that involves: 1. Checking the length of the array to ensure it matches the expected size (N). 2. Creating a set containing the integers from 1 to N. 3. Comparing this set to the set of eleme...
2,747
[ { "from": "human", "value": "Write a python function that checks if a given array represents a valid permutation. A permutation is a sequence containing each element from 1 to N once, and only once." }, { "from": "gpt", "value": "To check if a given array represents a valid permutation of the in...
Write a function that determines whether it is possible to complete all courses given the prerequisites. Each course may have prerequisites, which are courses that must be completed before the course can be taken. The function should return True if it is possible to complete all courses, and False otherwise.
Here is the code to solve this problem: ```python from collections import defaultdict, deque def canFinish(numCourses, prerequisites): if len(prerequisites)==0: return True Indegree = [0] * 2000 graph = defaultdict(list) nodes = set() for b,a in prerequisites: nodes.add(a) ...
[ "assert canFinish(3, [[1,0],[0,2],[1,2]])==True", "assert canFinish(2, [[1,0],[0,1]])==False", "assert canFinish(2, [[1,0]])==True" ]
To determine if it is possible to complete all courses given their prerequisites, we can model this problem using a directed graph representation. Each course can be considered as a node and each prerequisite relationship as a directed edge. The key idea is that if there is a cycle in this graph, it implies that not al...
2,748
[ { "from": "human", "value": "Write a function that determines whether it is possible to complete all courses given the prerequisites. Each course may have prerequisites, which are courses that must be completed before the course can be taken. The function should return True if it is possible to complete all...
Write a python function that finds the first occurrence of a target value in a sorted array using binary search.
Here is the code to solve this problem: ```python def binary_search_first(arr, target): def bsearch(arr, target): n = len(arr) low, high = 0, n - 1 res = -1 while low <= high: mid = (low + high) // 2 if arr[mid] == target: ...
[ "assert binary_search_first([1, 2, 4, 4, 5, 6, 6], 4) == 2", "assert binary_search_first([1, 1, 1, 1, 1], 1) == 0", "assert binary_search_first([1, 2, 3, 4, 5], 6) == -1" ]
Certainly! Below is a Python function that implements binary search to find the first occurrence of a target value in a sorted array. The function returns the index of the first occurrence if found, or -1 if the target is not in the array. ```python def find_first_occurrence(arr, target): left, right = 0, len(arr)...
2,749
[ { "from": "human", "value": "Write a python function that finds the first occurrence of a target value in a sorted array using binary search." }, { "from": "gpt", "value": "Certainly! Below is a Python function that implements binary search to find the first occurrence of a target value in a sor...
Write a function that takes a list of integers and returns a new list with only the prime numbers from the original list.
Here is the code to solve this problem: ```python def prime_filter(numbers): def is_prime(n): if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True return [num for num in numbers if is_prime(num)] ```
[ "assert prime_filter([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [2, 3, 5, 7]", "assert prime_filter([0, 1, 4, 6, 8, 9, 10, 12, 14, 15]) == []", "assert prime_filter([11, 13, 17, 19, 23, 29, 31, 37, 41, 43]) == [11, 13, 17, 19, 23, 29, 31, 37, 41, 43]" ]
Certainly! Below is a Python function that takes a list of integers and returns a new list containing only the prime numbers from the original list. ```python def is_prime(n): """Check if a number is prime.""" if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: ...
2,750
[ { "from": "human", "value": "Write a function that takes a list of integers and returns a new list with only the prime numbers from the original list." }, { "from": "gpt", "value": "Certainly! Below is a Python function that takes a list of integers and returns a new list containing only the pri...
Write a function to check if a number is a power of two.
Here is the code to solve this problem: ```python def is_power_of_two(n): if n <= 0: return False while n != 1: if n % 2 != 0: return False n = n // 2 return True ```
[ "assert is_power_of_two(1024)==True", "assert is_power_of_two(1023)==False", "assert is_power_of_two(256)==True" ]
You can determine whether a given number is a power of two by checking if it is greater than zero and if it has only one bit set in its binary representation. A number that is a power of two will have the property that `n & (n - 1)` equals zero, and `n` itself must be greater than zero. Here's a simple Python function...
2,751
[ { "from": "human", "value": "Write a function to check if a number is a power of two." }, { "from": "gpt", "value": "You can determine whether a given number is a power of two by checking if it is greater than zero and if it has only one bit set in its binary representation. A number that is a p...
Write a python function to find the minimum number of swaps required to sort an array in ascending order.
Here is the code to solve this problem: ```python def minSwaps(arr): n = len(arr) arrpos = [*enumerate(arr)] arrpos.sort(key=lambda it: it[1]) vis = {k: False for k in range(n)} ans = 0 for i in range(n): if vis[i] or arrpos[i][0] == i: continue cycle_size = 0 ...
[ "assert minSwaps([4, 3, 2, 1]) == 2", "assert minSwaps([1, 3, 5, 2, 4, 6, 7]) == 3", "assert minSwaps([1, 5, 4, 3, 2]) == 2" ]
To find the minimum number of swaps required to sort an array, we can use the concept of cycles in permutation. The idea is to first determine the positions of elements in the sorted version of the array and then calculate the necessary swaps based on the cycles formed by these indices. Here's a Python function that i...
2,752
[ { "from": "human", "value": "Write a python function to find the minimum number of swaps required to sort an array in ascending order." }, { "from": "gpt", "value": "To find the minimum number of swaps required to sort an array, we can use the concept of cycles in permutation. The idea is to fir...
Write a python function that takes a list of strings and returns a dictionary where keys are the strings from the list and values are the lengths of those strings.
Here is the code to solve this problem: ```python def string_length_dict(lst): return {word: len(word) for word in lst} ```
[ "assert string_length_dict([\"python\", \"is\", \"awesome\"]) == {\"python\": 6, \"is\": 2, \"awesome\": 7}", "assert string_length_dict([\"hello\", \"world\"]) == {\"hello\": 5, \"world\": 5}", "assert string_length_dict([\"one\", \"two\", \"three\", \"four\", \"five\"]) == {\"one\": 3, \"two\": 3, \"three\": ...
Certainly! You can create a function that takes a list of strings and returns a dictionary with the strings as keys and their corresponding lengths as values. Here is a sample implementation: ```python def strings_to_lengths(strings): length_dict = {string: len(string) for string in strings} return length_dict...
2,753
[ { "from": "human", "value": "Write a python function that takes a list of strings and returns a dictionary where keys are the strings from the list and values are the lengths of those strings." }, { "from": "gpt", "value": "Certainly! You can create a function that takes a list of strings and re...
Write a python function that checks 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 from collections import deque def word_break(s, wordDict): queue = deque([s]) word_set = set(wordDict) seen = set() while queue: word = queue.popleft() if word in word_set or len(word) == 0: return True ...
[ "assert word_break(\"catsandog\", [\"cats\", \"dog\", \"sand\", \"and\", \"cat\"]) == False", "assert word_break(\"applepenapple\", [\"apple\", \"pen\"]) == True", "assert word_break(\"leetcode\", [\"leet\", \"code\"]) == True" ]
You can solve this problem using dynamic programming. The idea is to use a boolean array to track which substrings of the input can be segmented into words from the dictionary. Here’s a Python function that accomplishes this: ```python def can_segment_string(s, word_dict): # Convert the list of words to a set for...
2,754
[ { "from": "human", "value": "Write a python function that checks if a given string can be segmented into a space-separated sequence of one or more dictionary words." }, { "from": "gpt", "value": "You can solve this problem using dynamic programming. The idea is to use a boolean array to track wh...
Write a python function to find the length of the longest subarray with a sum of zero.
Here is the code to solve this problem: ```python def longest_subarray_with_zero_sum(arr): max_len = 0 sum_val = 0 sum_map = {} for i in range(len(arr)): sum_val += arr[i] if arr[i] == 0 and max_len == 0: max_len = 1 if sum_val == 0: ...
[ "assert longest_subarray_with_zero_sum([3, -3, 3, -3]) == 4", "assert longest_subarray_with_zero_sum([1, 2, 3]) == 0", "assert longest_subarray_with_zero_sum([1, 2, -3, 3]) == 3" ]
You can use a hash map (or dictionary) to efficiently find the longest subarray with a sum of zero. The idea is to maintain a running sum of the elements as you iterate through the array. If the same sum occurs again, it means the elements between those two indices sum to zero. Here's a Python function to achieve this...
2,755
[ { "from": "human", "value": "Write a python function to find the length of the longest subarray with a sum of zero." }, { "from": "gpt", "value": "You can use a hash map (or dictionary) to efficiently find the longest subarray with a sum of zero. The idea is to maintain a running sum of the elem...
Write a function that takes a list of integers and returns the largest product that can be made by multiplying any three integers.
Here is the code to solve this problem: ```python def largest_product(arr): arr.sort() return max(arr[0] * arr[1] * arr[-1], arr[-1] * arr[-2] * arr[-3]) ```
[ "assert largest_product([1, 2, 3, 4]) == 24", "assert largest_product([-4, -3, -2, -1, 60]) == 720", "assert largest_product([-1, -2, -3, -4]) == -6" ]
Certainly! Here is a Python function that takes a list of integers and calculates the largest product that can be achieved by multiplying any three integers from the list: ```python def largest_product_of_three(nums): if len(nums) < 3: raise ValueError("The list must contain at least three integers.") ...
2,756
[ { "from": "human", "value": "Write a function that takes a list of integers and returns the largest product that can be made by multiplying any three integers." }, { "from": "gpt", "value": "Certainly! Here is a Python function that takes a list of integers and calculates the largest product tha...
Write a python function that takes a string and returns a dictionary containing the frequency of each letter in the string.
Here is the code to solve this problem: ```python def letter_frequency(string): frequency = {} for letter in string: if letter in frequency: frequency[letter] += 1 else: frequency[letter] = 1 return frequency ```
[ "assert letter_frequency('aaaaa') == {'a': 5}", "assert letter_frequency('hello') == {'h': 1, 'e': 1, 'l': 2, 'o': 1}", "assert letter_frequency('python') == {'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1}" ]
Certainly! You can achieve this by creating a function that iterates over the characters in the string, checking if each character is a letter, and then counting the occurrences of each letter using a dictionary. Here's a simple implementation: ```python def letter_frequency(s): # Initialize an empty dictionary to...
2,757
[ { "from": "human", "value": "Write a python function that takes a string and returns a dictionary containing the frequency of each letter in the string." }, { "from": "gpt", "value": "Certainly! You can achieve this by creating a function that iterates over the characters in the string, checking...
Write a python function to find the number of balanced parentheses in a string. Balanced parentheses are defined as either an empty string or a string that consists of two parts: a left parenthesis, a balanced string, a right parenthesis, and then another balanced string. For example, the following are balanced paren...
Here is the code to solve this problem: ```python def balanced_parentheses(s): stack = [] balanced = 0 for char in s: if char == '(': stack.append(char) elif char == ')' and stack: stack.pop() if not stack: balanced += 1 return balan...
[ "assert balanced_parentheses(\"((()))\") == 1", "assert balanced_parentheses(\"(()(()))\") == 1", "assert balanced_parentheses(\"()\") == 1", "assert balanced_parentheses(\"(()())(())\") == 2", "assert balanced_parentheses(\"()()\") == 2" ]
To find the number of balanced parentheses in a string, we can implement a function that utilizes a stack-like approach to keep track of the parentheses. The key is to iterate through the string and maintain a count of open and closed parentheses. We will also ensure that for every closing parenthesis, there is a corre...
2,758
[ { "from": "human", "value": "Write a python function to find the number of balanced parentheses in a string.\n\nBalanced parentheses are defined as either an empty string or a string that consists of two parts: a left parenthesis, a balanced string, a right parenthesis, and then another balanced string.\n\n...
Create a python function that takes a list of integers and returns a new list where every odd number in the original list is replaced by the square of that number.
Here is the code to solve this problem: ```python def square_odds(lst): return [num**2 if num % 2 != 0 else num for num in lst] ```
[ "assert square_odds([5, 6, 7, 8]) == [25, 6, 49, 8]", "assert square_odds([2, 4, 6, 8]) == [2, 4, 6, 8]", "assert square_odds([1, 2, 3, 4]) == [1, 2, 9, 4]" ]
You can achieve this by defining a function that iterates through the input list, checks if each number is odd, and then either replaces it with its square or keeps it as is. Here's a sample implementation: ```python def replace_odds_with_squares(int_list): return [x**2 if x % 2 != 0 else x for x in int_list] # E...
2,759
[ { "from": "human", "value": "Create a python function that takes a list of integers and returns a new list where every odd number in the original list is replaced by the square of that number." }, { "from": "gpt", "value": "You can achieve this by defining a function that iterates through the in...
Write a python function to check if a given number is an ugly number. An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. The sequence of ugly numbers starts with 1, and each subsequent number is the smallest number greater than the previous ugly number that can still be expressed as a ...
Here is the code to solve this problem: ```python def is_ugly_number(num: int) -> bool: if num <= 0: return False for i in [2, 3, 5]: while num % i == 0: num = num // i return num == 1 ```
[ "assert is_ugly_number(30) == True", "assert is_ugly_number(6) == True", "assert is_ugly_number(14) == False" ]
Certainly! An ugly number is defined as a positive integer whose prime factors are limited to 2, 3, and 5. The number 1 is also considered an ugly number. To check if a given number is an ugly number, you can follow these steps: 1. If the number is less than or equal to 0, it is not an ugly number. 2. Continuously d...
2,760
[ { "from": "human", "value": "Write a python function to check if a given number is an ugly number. An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5. The sequence of ugly numbers starts with 1, and each subsequent number is the smallest number greater than the previous ugly...
Write a function to find the largest sum of non-adjacent elements in a given array.
Here is the code to solve this problem: ```python def max_non_adjacent_sum(arr): incl = 0 excl = 0 for i in arr: new_excl = excl if excl>incl else incl incl = excl + i excl = new_excl return excl if excl>incl else incl ```
[ "assert max_non_adjacent_sum([5, 1, 1, 5]) == 10", "assert max_non_adjacent_sum([2, 4, 6, 2, 5]) == 13", "assert max_non_adjacent_sum([3, 2, 7, 10]) == 13" ]
You can solve the problem of finding the largest sum of non-adjacent elements in an array by using dynamic programming. The idea is to maintain two variables that keep track of the maximum sum including the current element and the maximum sum excluding the current element as you iterate through the array. Here is a Py...
2,761
[ { "from": "human", "value": "Write a function to find the largest sum of non-adjacent elements in a given array." }, { "from": "gpt", "value": "You can solve the problem of finding the largest sum of non-adjacent elements in an array by using dynamic programming. The idea is to maintain two vari...
Write a function to check whether a given graph can be divided into two groups such that each edge connects vertices from different groups (bipartite graph). A graph is represented as a list of edges.
Here is the code to solve this problem: ```python from collections import defaultdict, deque def is_bipartite(edges): graph = defaultdict(list) for edge in edges: graph[edge[0]].append(edge[1]) graph[edge[1]].append(edge[0]) color = [0] * len(graph) for i in range(len(graph)): ...
[ "assert is_bipartite([(0, 1), (1, 2), (2, 3), (3, 4)]) == True", "assert is_bipartite([(0, 1), (1, 3), (0, 2), (2, 3)]) == True", "assert is_bipartite([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]) == False", "assert is_bipartite([(0, 1), (1, 2), (2, 0)]) == False" ]
To determine if a given graph is bipartite (i.e., whether it can be divided into two groups such that each edge connects vertices from different groups), we can use a graph traversal algorithm like Depth-First Search (DFS) or Breadth-First Search (BFS). Here, I'll provide a solution using BFS. We'll represent the grap...
2,762
[ { "from": "human", "value": "Write a function to check whether a given graph can be divided into two groups such that each edge connects vertices from different groups (bipartite graph). A graph is represented as a list of edges." }, { "from": "gpt", "value": "To determine if a given graph is bi...
Write a python function to find the length of the largest subarray with a sum of zero.
Here is the code to solve this problem: ```python def max_length_subarray(arr): max_length = 0 sum_dict = {0: -1} current_sum = 0 for i in range(len(arr)): current_sum += arr[i] if current_sum not in sum_dict: sum_dict[current_sum] = i else: max_length = ...
[ "assert max_length_subarray([1, 2, 3, -6]) == 4", "assert max_length_subarray([1, 2, -3, 3]) == 3", "assert max_length_subarray([1, 2, 3, -6, 5]) == 4" ]
You can find the length of the largest subarray with a sum of zero using a dictionary to track the cumulative sums and their indices. When you encounter the same cumulative sum again, it means the subarray between the two indices has a sum of zero. Here's a Python function to achieve this: ```python def max_length_zer...
2,763
[ { "from": "human", "value": "Write a python function to find the length of the largest subarray with a sum of zero." }, { "from": "gpt", "value": "You can find the length of the largest subarray with a sum of zero using a dictionary to track the cumulative sums and their indices. When you encoun...
Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.
Here is the code to solve this problem: ```python from collections import Counter def duplicate_count(text): text = text.lower() counter = Counter(text) return sum(1 for c in counter if counter[c] > 1) ```
[ "assert duplicate_count(\"aabbcde\") == 2 # a, b", "assert duplicate_count(\"abcde\") == 0 # a, b, c, d, e are all not repeated", "assert duplicate_count(\"indivisibility\") == 1 # i", "assert duplicate_count(\"Indivisibilities\") == 2 # i, s", "assert duplicate_count(\"ABBA\") == 2 # A, B", "assert dupli...
Certainly! Below is a Python function that accomplishes this task. The function takes an input string, processes it to count the occurrences of each character (considering case insensitivity), and then returns the count of those characters that occur more than once. ```python def count_duplicates(s): # Convert the...
2,764
[ { "from": "human", "value": "Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits." }, {...
Write a function that takes a list of strings as input and returns a list of words that can be formed by concatenating the words in the original list. The concatenated words must be at least twice as long as the original words. For example, if the input list is ["cat", "cats", "catsdogcats", "dog", "dogcatsdog", "hipp...
Here is the code to solve this problem: ```python def concatenate_words(words): word_set = set(words) result = [] def can_form(word): for i in range(1, len(word)): prefix, suffix = word[:i], word[i:] if prefix in word_set and (suffix in word_set or can_form(suffix)): ...
[ "assert concatenate_words([\"cat\", \"cats\", \"catsdogcats\", \"dog\", \"dogcatsdog\", \"hippopotamuses\", \"rat\", \"ratcatdogcat\"]) == ['catsdogcats', 'dogcatsdog', 'ratcatdogcat']", "assert concatenate_words([\"a\", \"aa\", \"aaa\", \"aaaa\"]) == ['aa', 'aaa', 'aaaa']", "assert concatenate_words([\"apple\"...
To solve the problem of finding words that can be formed by concatenating other words in a list, we can approach it by using a set for fast lookups. We'll iterate through each word in the list and try to split it into two or more parts that also exist in the list. Additionally, we'll ensure that the concatenated words ...
2,765
[ { "from": "human", "value": "Write a function that takes a list of strings as input and returns a list of words that can be formed by concatenating the words in the original list. The concatenated words must be at least twice as long as the original words.\n\nFor example, if the input list is [\"cat\", \"ca...
Write a function to generate all possible combinations of words from a list of string arrays.
Here is the code to solve this problem: ```python def generate_combinations(list_of_arrays): if not list_of_arrays: return [] # Function to multiply arrays def multiply(arrays, prefix=""): if not arrays: return [prefix] result = [] current_array = a...
[ "assert generate_combinations([[\"1\", \"2\"], [\"3\"], [\"4\", \"5\"], [\"6\"]]) == ['1346', '1356', '2346', '2356']", "assert generate_combinations([[\"x\", \"y\"], [\"z\"], [\"m\", \"n\"]]) == ['xzm', 'xzn', 'yzm', 'yzn']", "assert generate_combinations([[\"a\", \"b\"], [\"c\", \"d\"]]) == ['ac', 'ad', 'bc',...
You can generate all possible combinations of words from a list of string arrays using Python's `itertools.product`. This function can create the Cartesian product of the provided input lists, which results in all combinations that can be formed by taking one element from each array. Here’s a function that implements ...
2,766
[ { "from": "human", "value": "Write a function to generate all possible combinations of words from a list of string arrays." }, { "from": "gpt", "value": "You can generate all possible combinations of words from a list of string arrays using Python's `itertools.product`. This function can create ...
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
Here is the code to solve this problem: ```python def hamming_weight(n): count = 0 while n: count += n & 1 n >>= 1 return count ```
[ "assert hamming_weight(128)==1", "assert hamming_weight(11)==3", "assert hamming_weight(4294967293)==31" ]
Certainly! You can write a function in Python to count the number of '1' bits in the binary representation of an unsigned integer. Here's a simple way to do that: ```python def hamming_weight(n: int) -> int: count = 0 while n: count += n & 1 # Add 1 to count if the least significant bit is 1 n...
2,767
[ { "from": "human", "value": "Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight)." }, { "from": "gpt", "value": "Certainly! You can write a function in Python to count the number of '1' bits in the binary representation of ...
Create a function that will take a list of numbers as input and return a new list with all the numbers multiplied by two.
Here is the code to solve this problem: ```python def multiply_by_two(input_list): return [element * 2 for element in input_list] ```
[ "assert multiply_by_two([1,2,3,4,5]) == [2,4,6,8,10]", "assert multiply_by_two([10,20,30]) == [20,40,60]", "assert multiply_by_two([5,10,15,20,25,30]) == [10,20,30,40,50,60]" ]
Sure! Here’s a simple function in Python that takes a list of numbers as input and returns a new list with all the numbers multiplied by two: ```python def multiply_by_two(numbers): return [num * 2 for num in numbers] ``` ### Example usage: ```python input_list = [1, 2, 3, 4, 5] result = multiply_by_two(input_li...
2,768
[ { "from": "human", "value": "Create a function that will take a list of numbers as input and return a new list with all the numbers multiplied by two." }, { "from": "gpt", "value": "Sure! Here’s a simple function in Python that takes a list of numbers as input and returns a new list with all the...
Create a function to merge two sorted arrays into one sorted array.
Here is the code to solve this problem: ```python def merge_two_sorted_arrays(arr1, arr2): result = [] i, j = 0, 0 while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: result.append(arr1[i]) i += 1 else: result.append(arr2[j]) j += 1 ...
[ "assert merge_two_sorted_arrays([2, 4, 6, 8], [1, 3, 5, 7]) == [1, 2, 3, 4, 5, 6, 7, 8]", "assert merge_two_sorted_arrays([11, 13, 15, 17], [9, 10, 12, 14]) == [9, 10, 11, 12, 13, 14, 15, 17]", "assert merge_two_sorted_arrays([1, 3, 5, 7], [2, 4, 6, 8]) == [1, 2, 3, 4, 5, 6, 7, 8]" ]
You can merge two sorted arrays into a single sorted array by using a two-pointer technique. Below is a Python function that accomplishes this: ```python def merge_sorted_arrays(arr1, arr2): # Create a result array to hold the merged elements merged_array = [] i, j = 0, 0 # Loop until we reach the...
2,769
[ { "from": "human", "value": "Create a function to merge two sorted arrays into one sorted array." }, { "from": "gpt", "value": "You can merge two sorted arrays into a single sorted array by using a two-pointer technique. Below is a Python function that accomplishes this:\n\n```python\ndef merge_...
Write a function that takes a list of integers and returns a new list with only the prime numbers from the original list. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Here is the code to solve this problem: ```python def is_prime(n): if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def filter_prime_numbers(numbers): return [n for n in numbers if is_prime(n)] ```
[ "assert filter_prime_numbers([2, 3, 4, 5, 6, 7, 8, 9, 10]) == [2, 3, 5, 7]", "assert filter_prime_numbers([11, 13, 17, 19, 23, 29]) == [11, 13, 17, 19, 23, 29]", "assert filter_prime_numbers([1, 4, 6, 8, 10, 12, 14, 15]) == []" ]
To create a function that filters out prime numbers from a list of integers, we can follow these steps: 1. Define a helper function that checks if a number is prime. 2. Use a loop or a list comprehension to filter the original list using the helper function. Here is a Python implementation of this approach: ```pytho...
2,770
[ { "from": "human", "value": "Write a function that takes a list of integers and returns a new list with only the prime numbers from the original list.\n\nA prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself." }, { "from": "gpt", "value": "To cre...
Write a function that takes a list of integers and returns a list of their squares.
Here is the code to solve this problem: ```python def square_list(nums): return [num ** 2 for num in nums] ```
[ "assert square_list([0, 10, 20, 30, 40]) == [0, 100, 400, 900, 1600]", "assert square_list([-1, -2, -3, -4, -5]) == [1, 4, 9, 16, 25]", "assert square_list([1, 2, 3, 4, 5]) == [1, 4, 9, 16, 25]" ]
Certainly! You can create a function in Python that takes a list of integers and returns a new list containing their squares. Here is a simple implementation of that function: ```python def square_list(int_list): return [x ** 2 for x in int_list] # Example usage: input_list = [1, 2, 3, 4, 5] squared_list = square...
2,771
[ { "from": "human", "value": "Write a function that takes a list of integers and returns a list of their squares." }, { "from": "gpt", "value": "Certainly! You can create a function in Python that takes a list of integers and returns a new list containing their squares. Here is a simple implement...
Write a function in Python that takes a positive integer as input and returns the sum of the digits of that number. However, there is a twist: if any of the digits is a 9, the function should return the sum of the digits excluding the 9s.
Here is the code to solve this problem: ```python def sum_except_nine(n): total = 0 while n > 0: digit = n % 10 if digit != 9: total += digit n = n // 10 return total ```
[ "assert sum_except_nine(9999) == 0", "assert sum_except_nine(12345) == 15", "assert sum_except_nine(123) == 6" ]
You can create a Python function to achieve this by first converting the integer to a string to easily iterate over each digit. Then, you will check if there are any '9's in the number, summing the digits accordingly. Here's how you can implement this: ```python def sum_of_digits(num): if num < 1: raise Va...
2,772
[ { "from": "human", "value": "Write a function in Python that takes a positive integer as input and returns the sum of the digits of that number. However, there is a twist: if any of the digits is a 9, the function should return the sum of the digits excluding the 9s." }, { "from": "gpt", "value"...
Write a function to find the number of times a given pattern appears in a string. The pattern can overlap.
Here is the code to solve this problem: ```python def count_pattern(text, pattern): count = 0 index = 0 while index < len(text): found = text.find(pattern, index) if found != -1: count += 1 index = found + 1 else: break return count ```
[ "assert count_pattern(\"abcabcabc\", \"abc\") == 3", "assert count_pattern(\"hellohello\", \"ll\") == 2", "assert count_pattern(\"ababababa\", \"aba\") == 4", "assert count_pattern(\"mississippi\", \"issi\") == 2" ]
You can write a function in Python that counts the number of times a given pattern appears in a string, allowing for overlapping occurrences. Below is one way to implement this: ```python def count_overlapping_pattern(text, pattern): count = 0 start = 0 while True: start = text.find(pattern, start...
2,773
[ { "from": "human", "value": "Write a function to find the number of times a given pattern appears in a string. The pattern can overlap." }, { "from": "gpt", "value": "You can write a function in Python that counts the number of times a given pattern appears in a string, allowing for overlapping ...
Write a python function to find the next greater element for every element of the array in the given array.
Here is the code to solve this problem: ```python def next_greater(arr): next = -1 result = [-1]*len(arr) s = [] for i in range(len(arr)): while(len(s) != 0 and arr[s[-1]] < arr[i]): next = arr[i] result[s[-1]] = next s.pop() s.append(i) return re...
[ "assert next_greater([4, 5, 2, 25]) == [5, 25, 25, -1]", "assert next_greater([13, 7, 6, 12]) == [-1, 12, 12, -1]", "assert next_greater([1, 2, 3, 4, 5]) == [2, 3, 4, 5, -1]" ]
To find the next greater element for each element in an array, we can efficiently use a stack data structure. The idea is to iterate through the array and keep track of the indices of elements for which we haven't found the next greater element yet. As we encounter each element, we'll check if it is greater than the el...
2,774
[ { "from": "human", "value": "Write a python function to find the next greater element for every element of the array in the given array." }, { "from": "gpt", "value": "To find the next greater element for each element in an array, we can efficiently use a stack data structure. The idea is to ite...
Write a python function to generate all possible permutations of a given list of elements.
Here is the code to solve this problem: ```python import itertools def permute(elements): return [list(p) for p in itertools.permutations(elements)] ```
[ "assert permute([1]) == [[1]]", "assert permute(['a','b','c']) == [['a', 'b', 'c'], ['a', 'c', 'b'], ['b', 'a', 'c'], ['b', 'c', 'a'], ['c', 'a', 'b'], ['c', 'b', 'a']]", "assert permute([1,2,3]) == [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]" ]
You can generate all possible permutations of a list in Python using a recursive approach or by utilizing the `itertools` module, which provides a built-in function for permutations. Below, I've implemented both methods for you. ### Using Recursion Here’s a recursive approach to generate permutations: ```python def p...
2,775
[ { "from": "human", "value": "Write a python function to generate all possible permutations of a given list of elements." }, { "from": "gpt", "value": "You can generate all possible permutations of a list in Python using a recursive approach or by utilizing the `itertools` module, which provides ...
Write a python function to find the frequency of each character in a given string.
Here is the code to solve this problem: ```python def character_frequency(string): frequency = {} for char in string: if char in frequency: frequency[char] += 1 else: frequency[char] = 1 return frequency ```
[ "assert character_frequency(\"mississippi\") == {'m': 1, 'i': 4, 's': 4, 'p': 2}", "assert character_frequency(\"hello world\") == {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}", "assert character_frequency(\"apple\") == {'a': 1, 'p': 2, 'l': 1, 'e': 1}" ]
You can find the frequency of each character in a string using a simple Python function. One effective way to do this is by using a dictionary to keep track of the character counts. Here’s a sample function that accomplishes this: ```python def character_frequency(s): frequency = {} for char in s: ...
2,776
[ { "from": "human", "value": "Write a python function to find the frequency of each character in a given string." }, { "from": "gpt", "value": "You can find the frequency of each character in a string using a simple Python function. One effective way to do this is by using a dictionary to keep tr...
Write a function to find the number of unique paths from the top-left corner to the bottom-right corner of a m x n grid. You can only move either down or right at any point in time.
Here is the code to solve this problem: ```python def uniquePaths(m, n): dp = [[1]*n for _ in range(m)] for i in range(1, m): for j in range(1, n): dp[i][j] = dp[i-1][j] + dp[i][j-1] return dp[-1][-1] ```
[ "assert uniquePaths(3, 2) == 3", "assert uniquePaths(3, 3) == 6", "assert uniquePaths(3, 7) == 28" ]
You can solve the problem of finding the number of unique paths in an `m x n` grid using either recursion with memoization or dynamic programming. Below is an implementation using dynamic programming in Python. ### Dynamic Programming Approach We can create a 2D array `dp` where `dp[i][j]` represents the number of un...
2,777
[ { "from": "human", "value": "Write a function to find the number of unique paths from the top-left corner to the bottom-right corner of a m x n grid. You can only move either down or right at any point in time." }, { "from": "gpt", "value": "You can solve the problem of finding the number of uni...
Write a python function to find the number of ways to decode a message with a given encoding pattern. Given a non-empty string containing only digits, determine the total number of ways to decode it using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 To make the solution robust, you should assume that the in...
Here is the code to solve this problem: ```python def decode_variations(s): if not s or s[0] == '0': return 0 first, second = 1, 1 for i in range(1, len(s)): current = 0 if s[i] > '0': current = second if s[i-1] == '1' or (s[i-1] == '2' and s[i] < '7'): ...
[ "assert decode_variations(\"06\") == 0", "assert decode_variations(\"226\") == 3", "assert decode_variations(\"12\") == 2" ]
To solve the problem of counting the number of ways to decode a string of digits into letters according to the specified mapping (where '1' maps to 'A', '2' to 'B', ..., '26' to 'Z'), we can utilize dynamic programming. Here’s how the function works: 1. We first check if the input string is empty or starts with a '0'....
2,778
[ { "from": "human", "value": "Write a python function to find the number of ways to decode a message with a given encoding pattern.\n\nGiven a non-empty string containing only digits, determine the total number of ways to decode it using the following mapping:\n'A' -> 1\n'B' -> 2\n...\n'Z' -> 26\n\nTo make t...
Write a function to find the top k frequent elements from a list of numbers.
Here is the code to solve this problem: ```python from collections import Counter def top_k_frequent(nums, k): count = Counter(nums) return [item for item, _ in count.most_common(k)] ```
[ "assert top_k_frequent([1,1,1,2,2,3], 2) == [1, 2]", "assert top_k_frequent([1], 1) == [1]", "assert top_k_frequent([4,1,-2,1,1,3,1,-2,4,2], 2) == [1, 4]" ]
Certainly! You can find the top `k` frequent elements from a list of numbers using Python. Below is a function that accomplishes this using the `collections.Counter` class for frequency counting and the `heapq` module to efficiently retrieve the top `k` frequent elements. Here's the implementation: ```python from col...
2,779
[ { "from": "human", "value": "Write a function to find the top k frequent elements from a list of numbers." }, { "from": "gpt", "value": "Certainly! You can find the top `k` frequent elements from a list of numbers using Python. Below is a function that accomplishes this using the `collections.Co...
Write a Python function that takes a list of integers as an argument and returns the largest prime number in the list. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. If there is no prime number in the list, the function should return None.
Here is the code to solve this problem: ```python def find_largest_prime(numbers): def is_prime(n): if n <= 1: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True primes = [num for num in numbers if is_prime...
[ "assert find_largest_prime([2, 3, 5, 7, 11, 13]) == 13", "assert find_largest_prime([4, 6, 8, 10, 12]) == None", "assert find_largest_prime([0, 1, -1, -2, -3]) == None", "assert find_largest_prime([17, 19, 23, 29, 31, 37, 41]) == 41" ]
Certainly! Here's a Python function that takes a list of integers and returns the largest prime number in that list. If there are no prime numbers, the function returns `None`. ```python def is_prime(n): """Check if a number is prime.""" if n <= 1: return False for i in range(2, int(n**0.5) + 1): ...
2,780
[ { "from": "human", "value": "Write a Python function that takes a list of integers as an argument and returns the largest prime number in the list. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. If there is no prime number in the list, the function s...
Write a function to check if a given number is a power of 2.
Here is the code to solve this problem: ```python def is_power_of_two(n): if n <= 0: return False while n % 2 == 0: n = n // 2 return n == 1 ```
[ "assert is_power_of_two(8) == True", "assert is_power_of_two(18) == False", "assert is_power_of_two(16) == True" ]
You can check if a given number is a power of 2 by using a simple mathematical property: A number is a power of 2 if it is greater than 0 and if it has only one bit set in its binary representation. This can be easily checked using the expression `n & (n - 1) == 0`. Here's how you can implement this in Python: ```pyth...
2,781
[ { "from": "human", "value": "Write a function to check if a given number is a power of 2." }, { "from": "gpt", "value": "You can check if a given number is a power of 2 by using a simple mathematical property: A number is a power of 2 if it is greater than 0 and if it has only one bit set in its...
Write a python function to determine if a given string is a palindrome or not. A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward or forward.
Here is the code to solve this problem: ```python def is_Palindrome(s): return s == s[::-1] ```
[ "assert is_Palindrome(\"madam\") == True", "assert is_Palindrome(\"12321\") == True", "assert is_Palindrome(\"racecar\") == True", "assert is_Palindrome(\"hello\") == False" ]
Certainly! Here is a Python function that checks if a given string is a palindrome: ```python def is_palindrome(s): # Remove non-alphanumeric characters and convert to lower case cleaned_s = ''.join(char.lower() for char in s if char.isalnum()) # Check if the cleaned string is equal to its reverse retu...
2,782
[ { "from": "human", "value": "Write a python function to determine if a given string is a palindrome or not. A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward or forward." }, { "from": "gpt", "value": "Certainly! Here is a Python function that ch...
Write a python function to calculate the area of a circle given its radius.
Here is the code to solve this problem: ```python import math def circle_area(radius): return math.pi * radius**2 ```
[ "assert circle_area(1)==(3.141592653589793)", "assert circle_area(5)==(78.53981633974483)", "assert circle_area(10)==(314.1592653589793)" ]
Certainly! The area of a circle can be calculated using the formula: \[ \text{Area} = \pi \times r^2 \] where \( r \) is the radius of the circle and \( \pi \) is approximately 3.14159. Here is a Python function that calculates the area of a circle given its radius: ```python import math def calculate_circle_area(...
2,783
[ { "from": "human", "value": "Write a python function to calculate the area of a circle given its radius." }, { "from": "gpt", "value": "Certainly! The area of a circle can be calculated using the formula:\n\n\\[ \\text{Area} = \\pi \\times r^2 \\]\n\nwhere \\( r \\) is the radius of the circle a...
Write a function to find the total number of vowels in a given string.
Here is the code to solve this problem: ```python def count_vowels(s): vowels = "aeiou" count = 0 for char in s.lower(): if char in vowels: count += 1 return count ```
[ "assert count_vowels(\"python programming\") == 4", "assert count_vowels(\"hello world\") == 3", "assert count_vowels(\"aeiou\") == 5" ]
Certainly! Below is a Python function that takes a string as input and returns the total number of vowels in that string. Vowels are considered to be 'a', 'e', 'i', 'o', and 'u' (both uppercase and lowercase). ```python def count_vowels(s): # Define a set of vowels vowels = 'aeiouAEIOU' # Initialize a coun...
2,784
[ { "from": "human", "value": "Write a function to find the total number of vowels in a given string." }, { "from": "gpt", "value": "Certainly! Below is a Python function that takes a string as input and returns the total number of vowels in that string. Vowels are considered to be 'a', 'e', 'i', ...
Write a python function to find the maximum of three given numbers.
Here is the code to solve this problem: ```python def max_of_three(x, y, z): return max(x, y, z) ```
[ "assert max_of_three(1, 1, 1) == 1", "assert max_of_three(3, 5, 7) == 7", "assert max_of_three(10, 4, 8) == 10" ]
You can create a Python function to find the maximum of three given numbers by using the built-in `max` function, or you can implement the logic manually. Here’s an example of both methods: ### Method 1: Using the `max` function ```python def find_max_of_three(num1, num2, num3): return max(num1, num2, num3) ``` ...
2,785
[ { "from": "human", "value": "Write a python function to find the maximum of three given numbers." }, { "from": "gpt", "value": "You can create a Python function to find the maximum of three given numbers by using the built-in `max` function, or you can implement the logic manually. Here’s an exa...
Write a python function to find the shortest alternating paths in a directed graph from node 0 to all other nodes. The graph is represented by two lists of directed edges, one for red edges and one for blue edges. The function should return a list of integers where the i-th integer represents the length of the shortest...
Here is the code to solve this problem: ```python from collections import defaultdict def shortest_alternating_paths(n, red_edges, blue_edges): """ :type n: int :type red_edges: List[List[int]] :type blue_edges: List[List[int]] :rtype: List[int] """ if n <= 0: return [] red_map = defau...
[ "assert shortest_alternating_paths(3, [[0,1]], [[2,1]]) == [0,1,-1]", "assert shortest_alternating_paths(3, [[0,1]], [[1,2]]) == [0,1,2]", "assert shortest_alternating_paths(2, [[0,1]], [[1,0]]) == [0,1]", "assert shortest_alternating_paths(3, [[0,1],[0,2]], [[1,0]]) == [0,1,1]", "assert shortest_alternatin...
To find the shortest alternating paths in a directed graph using red and blue edges, we can employ a Breadth-First Search (BFS) algorithm that keeps track of the last edge color used. This will help us ensure that we are alternating colors properly as we traverse the graph. Here’s a Python function that implements thi...
2,786
[ { "from": "human", "value": "Write a python function to find the shortest alternating paths in a directed graph from node 0 to all other nodes. The graph is represented by two lists of directed edges, one for red edges and one for blue edges. The function should return a list of integers where the i-th inte...
Write a python function to find the duplicate elements in a list and return them in a sorted list.
Here is the code to solve this problem: ```python def find_duplicates(lst): duplicates = [] unique = set() for i in lst: if i in unique: duplicates.append(i) else: unique.add(i) return sorted(list(set(duplicates))) ```
[ "assert find_duplicates([10,20,30,20,10,40]) == [10, 20]", "assert find_duplicates([1,2,3,2,1,5,6,5,5,5]) == [1, 2, 5]", "assert find_duplicates([1,2,3,4,5]) == []" ]
Certainly! You can create a function that iterates through the list, counts the occurrences of each element, and returns the duplicates in a sorted manner. Here's one way to implement this: ```python def find_duplicates(input_list): # Create a dictionary to count occurrences count_dict = {} # Count oc...
2,787
[ { "from": "human", "value": "Write a python function to find the duplicate elements in a list and return them in a sorted list." }, { "from": "gpt", "value": "Certainly! You can create a function that iterates through the list, counts the occurrences of each element, and returns the duplicates i...
Write a function to determine if a given string is a valid number. A valid number can be an integer, a decimal, or a number with an exponent. It can also have leading and trailing whitespaces, and an optional sign (+ or -) at the beginning. A decimal number must have at least one digit before and after the decimal poin...
Here is the code to solve this problem: ```python def is_valid_number(s): s = s.strip() # dfa status err = -1 #error srt = 0 #start sgd = 1 #integer part sign did = 2 #integer part number ddp = 3 #xx. (there some number before '.') dnp = 4 #. dii = 5 # decimal part number ...
[ "assert is_valid_number(\" 123.45 \") == True", "assert is_valid_number(\"123\") == True", "assert is_valid_number(\"-123\") == True", "assert is_valid_number(\".45\") == True", "assert is_valid_number(\"123.45.67\") == False", "assert is_valid_number(\"abc\") == False", "assert is_valid_number(\"123e\"...
To determine if a given string is a valid number according to the specified criteria, we can use a regular expression. Here's a Python function that implements this logic: ```python import re def is_valid_number(s: str) -> bool: # Strip leading and trailing whitespace s = s.strip() # Regular expressi...
2,788
[ { "from": "human", "value": "Write a function to determine if a given string is a valid number. A valid number can be an integer, a decimal, or a number with an exponent. It can also have leading and trailing whitespaces, and an optional sign (+ or -) at the beginning. A decimal number must have at least on...
Write a function to count the occurrences of each character in a given string.
Here is the code to solve this problem: ```python def count_characters(string): char_count = {} for char in string: if char in char_count: char_count[char] += 1 else: char_count[char] = 1 return char_count ```
[ "assert count_characters(\"mississippi\") == {'m': 1, 'i': 4, 's': 4, 'p': 2}", "assert count_characters(\"python\") == {'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1}", "assert count_characters(\"hello world\") == {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}" ]
Certainly! Below is a simple Python function that takes a string as input and returns a dictionary with the counts of each character in that string. ```python def count_characters(s): char_count = {} # Initialize an empty dictionary to store character counts for char in s: # Iterate over each character in th...
2,789
[ { "from": "human", "value": "Write a function to count the occurrences of each character in a given string." }, { "from": "gpt", "value": "Certainly! Below is a simple Python function that takes a string as input and returns a dictionary with the counts of each character in that string.\n\n```py...
Write a python function that converts a given list of integers into a dictionary where the keys are the integers and the values are the frequencies of these integers in the list.
Here is the code to solve this problem: ```python def count_frequencies(nums): freq_dict = {} for num in nums: if num in freq_dict: freq_dict[num] += 1 else: freq_dict[num] = 1 return freq_dict ```
[ "assert count_frequencies([1,2,2,3,3,3])=={1: 1, 2: 2, 3: 3}", "assert count_frequencies([9,8,7,6,5,4])=={9: 1, 8: 1, 7: 1, 6: 1, 5: 1, 4: 1}", "assert count_frequencies([4,5,5,5,5,6])=={4: 1, 5: 4, 6: 1}" ]
You can create a function in Python to accomplish this task using the `collections.Counter` class, which makes it easy to count the frequency of elements in a list. Here's a simple function that does this: ```python from collections import Counter def list_to_frequency_dict(int_list): """Converts a list of intege...
2,790
[ { "from": "human", "value": "Write a python function that converts a given list of integers into a dictionary where the keys are the integers and the values are the frequencies of these integers in the list." }, { "from": "gpt", "value": "You can create a function in Python to accomplish this ta...
Write a function to find the greatest common divisor (GCD) of two numbers using Euclid's algorithm.
Here is the code to solve this problem: ```python def find_gcd(x, y): while(y): x, y = y, x % y return x ```
[ "assert find_gcd(48, 18)==6", "assert find_gcd(7, 5)==1", "assert find_gcd(100, 25)==25" ]
Certainly! Here’s a Python function that implements Euclid's algorithm to find the greatest common divisor (GCD) of two numbers: ```python def gcd(a, b): """Calculate the GCD of two numbers using Euclid's algorithm.""" while b != 0: a, b = b, a % b return abs(a) # Example usage: num1 = 48 num2 = 1...
2,791
[ { "from": "human", "value": "Write a function to find the greatest common divisor (GCD) of two numbers using Euclid's algorithm." }, { "from": "gpt", "value": "Certainly! Here’s a Python function that implements Euclid's algorithm to find the greatest common divisor (GCD) of two numbers:\n\n```p...
Write a function to generate all unique combinations of pairs from a given list of numbers.
Here is the code to solve this problem: ```python def unique_pairs(numbers): pairs = [] for i in range(len(numbers)): for j in range(i+1, len(numbers)): pairs.append((numbers[i], numbers[j])) return pairs ```
[ "assert unique_pairs([1, 2, 3]) == [(1, 2), (1, 3), (2, 3)]", "assert unique_pairs([4, 5, 6, 7]) == [(4, 5), (4, 6), (4, 7), (5, 6), (5, 7), (6, 7)]", "assert unique_pairs([10, 20, 30, 40, 50]) == [(10, 20), (10, 30), (10, 40), (10, 50), (20, 30), (20, 40), (20, 50), (30, 40), (30, 50), (40, 50)]" ]
To generate all unique combinations of pairs from a given list of numbers, we can use Python's `itertools.combinations` function, which allows us to create combinations of a specified length from the input iterable. Since we're interested in pairs, we will generate combinations of length 2. Here's a simple function to...
2,792
[ { "from": "human", "value": "Write a function to generate all unique combinations of pairs from a given list of numbers." }, { "from": "gpt", "value": "To generate all unique combinations of pairs from a given list of numbers, we can use Python's `itertools.combinations` function, which allows u...
Write a 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 find_longest_increasing_subsequence(nums): if not nums: return 0 dp = [1] * len(nums) for i in range(1, len(nums)): for j in range(i): if nums[i] > nums[j]: dp[i] = max(dp[i], dp[j] + 1) return max(dp) `...
[ "assert find_longest_increasing_subsequence([7, 7, 7, 7, 7, 7, 7]) == 1", "assert find_longest_increasing_subsequence([0, 1, 0, 3, 2, 3]) == 4", "assert find_longest_increasing_subsequence([10, 9, 2, 5, 3, 7, 101, 18]) == 4" ]
Certainly! To find the length of the longest increasing subsequence (LIS) in a given list of numbers, you can use a dynamic programming approach. Here's a Python function that implements this method: ```python def length_of_LIS(nums): if not nums: return 0 # Create an array to store the length of the ...
2,793
[ { "from": "human", "value": "Write a function to find the length of the longest increasing subsequence in a given list of numbers." }, { "from": "gpt", "value": "Certainly! To find the length of the longest increasing subsequence (LIS) in a given list of numbers, you can use a dynamic programmin...
Write a function that takes a list of integers and a list of booleans. If the boolean is True, the corresponding integer is squared and added to a new list. If the boolean is False, the integer is cubed and added to the new list. Return the new list.
Here is the code to solve this problem: ```python def square_or_cube(arr, flag): new_arr = [] for i in range(len(flag)): if flag[i] == True: new_arr.append(arr[i]**2) else: new_arr.append(arr[i]**3) return new_arr ```
[ "assert square_or_cube([11, 12, 13, 14, 15], [True, True, False, False, True]) == [121, 144, 2197, 2744, 225]", "assert square_or_cube([6, 7, 8, 9, 10], [False, True, False, True, False]) == [216, 49, 512, 81, 1000]", "assert square_or_cube([1, 2, 3, 4, 5], [True, False, True, False, True]) == [1, 8, 9, 64, 25]...
Sure! Below is a Python function that implements your requirements. It takes a list of integers and a list of booleans, and based on the boolean values, it either squares or cubes the integers before adding them to a new list. ```python def process_integers(int_list, bool_list): result = [] for i, num in enume...
2,794
[ { "from": "human", "value": "Write a function that takes a list of integers and a list of booleans. If the boolean is True, the corresponding integer is squared and added to a new list. If the boolean is False, the integer is cubed and added to the new list. Return the new list." }, { "from": "gpt",...
Write a python function to check if a given string is a valid IPv4 address.
Here is the code to solve this problem: ```python def isValidIPv4(ip): nums = ip.split('.') if len(nums) != 4: return False for x in nums: if not x.isdigit(): return False i = int(x) if i < 0 or i > 255: return False if len(x) > 1 and x[0] == ...
[ "assert isValidIPv4(\"256.256.256.256\") == False", "assert isValidIPv4(\"192.168.1.1\") == True", "assert isValidIPv4(\"192.168.1.1.1\") == False", "assert isValidIPv4(\"192.168.1\") == False", "assert isValidIPv4(\"192.168.1.256\") == False", "assert isValidIPv4(\"192.168.1.01\") == False", "assert is...
You can use the following Python function to check if a given string is a valid IPv4 address. This function will ensure that the address consists of four decimal numbers separated by dots, and each number must be in the range of 0 to 255. Here's the implementation: ```python def is_valid_ipv4(ip): # Split the IP ...
2,795
[ { "from": "human", "value": "Write a python function to check if a given string is a valid IPv4 address." }, { "from": "gpt", "value": "You can use the following Python function to check if a given string is a valid IPv4 address. This function will ensure that the address consists of four decima...
Write a function that finds the number of times a substring appears in a string, including overlaps.
Here is the code to solve this problem: ```python def substring_count(main_string, substring): count = 0 index = 0 while index < len(main_string): index = main_string.find(substring, index) if index == -1: break count += 1 index += 1 return count ```
[ "assert substring_count(\"mississippi\", \"issi\") == 2", "assert substring_count(\"hello\", \"l\") == 2", "assert substring_count(\"aaaa\", \"aa\") == 3" ]
You can create a function in Python to count the number of times a substring appears in a string, including overlapping occurrences. Here's one way to do it using a loop: ```python def count_overlapping_substrings(string, substring): count = 0 start = 0 while True: # Find the index of the subs...
2,796
[ { "from": "human", "value": "Write a function that finds the number of times a substring appears in a string, including overlaps." }, { "from": "gpt", "value": "You can create a function in Python to count the number of times a substring appears in a string, including overlapping occurrences. He...
Write a function that takes a list of integers and returns a new list where each element is multiplied by its index in the original list.
Here is the code to solve this problem: ```python def multiply_by_index(lst): return [i * lst[i] for i in range(len(lst))] ```
[ "assert multiply_by_index([1, 2, 3, 4, 5]) == [0, 2, 6, 12, 20]", "assert multiply_by_index([10, 20, 30, 40, 50]) == [0, 20, 60, 120, 200]", "assert multiply_by_index([5, 4, 3, 2, 1]) == [0, 4, 6, 6, 4]" ]
You can achieve this by defining a function that takes a list of integers as an input and then uses a list comprehension to create a new list where each element is multiplied by its index. Here’s how you can do it in Python: ```python def multiply_by_index(int_list): return [value * index for index, value in enume...
2,797
[ { "from": "human", "value": "Write a function that takes a list of integers and returns a new list where each element is multiplied by its index in the original list." }, { "from": "gpt", "value": "You can achieve this by defining a function that takes a list of integers as an input and then use...
Write a python function to generate all possible permutations of a given list of integers.
Here is the code to solve this problem: ```python def generate_permutations(arr): if len(arr) == 0: return [] if len(arr) == 1: return [arr] permutations = [] for i in range(len(arr)): m = arr[i] remaining_elements = arr[:i] + arr[i+1:] for p in generate_permutat...
[ "assert generate_permutations([1]) == [[1]]", "assert generate_permutations([1,2]) == [[1, 2], [2, 1]]", "assert generate_permutations([1,2,3]) == [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]" ]
You can generate all possible permutations of a list of integers in Python using the `itertools` module, which provides a handy function called `permutations`. However, if you'd like to write your own function to generate permutations recursively, here's how you can do it: ### Using `itertools.permutations` Here's a ...
2,798
[ { "from": "human", "value": "Write a python function to generate all possible permutations of a given list of integers." }, { "from": "gpt", "value": "You can generate all possible permutations of a list of integers in Python using the `itertools` module, which provides a handy function called `...
Write a function that takes a string as input and returns the string with all non-alphabetic characters removed and the remaining characters in reverse order.
Here is the code to solve this problem: ```python def reverse_and_remove_non_alpha(s: str) -> str: alpha_str = "" for char in s: if char.isalpha(): alpha_str += char return alpha_str[::-1] ```
[ "assert reverse_and_remove_non_alpha(\"123ABCabc!\") == \"cbaCBA\"", "assert reverse_and_remove_non_alpha(\"1234567890\") == \"\"", "assert reverse_and_remove_non_alpha(\"Hello, World!\") == \"dlroWolleH\"", "assert reverse_and_remove_non_alpha(\"Python 3.8\") == \"nohtyP\"" ]
You can achieve this by defining a function that processes the input string, filters out non-alphabetic characters, and then reverses the remaining characters. Here's one way to implement this in Python: ```python def reverse_alphabetic_string(s): # Filter out non-alphabetic characters filtered_characters = [c...
2,799
[ { "from": "human", "value": "Write a function that takes a string as input and returns the string with all non-alphabetic characters removed and the remaining characters in reverse order." }, { "from": "gpt", "value": "You can achieve this by defining a function that processes the input string, ...