instruction_seed stringlengths 42 1.67k | response_seed stringlengths 83 5.94k | testcase sequencelengths 3 39 | response stringlengths 46 5.35k | __original_row_idx int64 0 50k | conversations listlengths 2 2 |
|---|---|---|---|---|---|
Write a function that takes a list of integers as input and returns a list of tuples. Each tuple should contain the count of consecutive occurrences of an integer and the integer itself. | Here is the code to solve this problem:
```python
def count_consecutive(numbers):
result = []
current_num = numbers[0]
count = 1
for num in numbers[1:]:
if num == current_num:
count += 1
else:
result.append((count, current_num))
current_num = num
... | [
"assert count_consecutive([4, 5, 5, 6, 6, 6, 7]) == [(1, 4), (2, 5), (3, 6), (1, 7)]",
"assert count_consecutive([1, 1, 2, 2, 2, 3]) == [(2, 1), (3, 2), (1, 3)]",
"assert count_consecutive([0, 0, 0, 1, 1, 2, 3, 3]) == [(3, 0), (2, 1), (1, 2), (2, 3)]"
] | Certainly! You can create a function in Python that takes a list of integers and returns a list of tuples where each tuple consists of the count of consecutive occurrences of an integer and the integer itself. Here's how you can implement this:
```python
def count_consecutive_occurrences(input_list):
if not input_... | 10,000 | [
{
"from": "human",
"value": "Write a function that takes a list of integers as input and returns a list of tuples. Each tuple should contain the count of consecutive occurrences of an integer and the integer itself."
},
{
"from": "gpt",
"value": "Certainly! You can create a function in Python th... |
Write a function to generate a list of prime numbers up to a given number using the Sieve of Eratosthenes algorithm. | Here is the code to solve this problem:
```python
def generate_primes(n):
if n < 2:
return []
primes = []
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False
for current in range(2, int(n**0.5) + 1):
if sieve[current]:
primes.append(current)
for mu... | [
"assert generate_primes(10) == [2, 3, 5, 7]",
"assert generate_primes(20) == [2, 3, 5, 7, 11, 13, 17, 19]",
"assert generate_primes(30) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]"
] | Certainly! The Sieve of Eratosthenes is an efficient algorithm for finding all prime numbers up to a specified integer. Below is a Python function that implements the Sieve of Eratosthenes to generate a list of prime numbers up to a given number.
```python
def sieve_of_eratosthenes(n):
"""Generate a list of prime ... | 10,001 | [
{
"from": "human",
"value": "Write a function to generate a list of prime numbers up to a given number using the Sieve of Eratosthenes algorithm."
},
{
"from": "gpt",
"value": "Certainly! The Sieve of Eratosthenes is an efficient algorithm for finding all prime numbers up to a specified integer.... |
Write a function that takes a list of strings and returns a dictionary where each key is a unique string from the list and the value is the number of times that string appears in the list. | Here is the code to solve this problem:
```python
def string_frequency(strings):
frequency = {}
for string in strings:
if string in frequency:
frequency[string] += 1
else:
frequency[string] = 1
return frequency
``` | [
"assert string_frequency([\"hello\", \"world\", \"hello\", \"python\"]) == {\"hello\": 2, \"world\": 1, \"python\": 1}",
"assert string_frequency([\"apple\", \"banana\", \"apple\", \"orange\", \"banana\", \"apple\"]) == {\"apple\": 3, \"banana\": 2, \"orange\": 1}",
"assert string_frequency([\"test\", \"test\",... | You can achieve this by defining a function that iterates through the list of strings and counts the occurrences of each string, storing the results in a dictionary. Here's a sample implementation of such a function in Python:
```python
def count_strings(string_list):
string_count = {}
for string in string_lis... | 10,002 | [
{
"from": "human",
"value": "Write a function that takes a list of strings and returns a dictionary where each key is a unique string from the list and the value is the number of times that string appears in the list."
},
{
"from": "gpt",
"value": "You can achieve this by defining a function tha... |
Write a python function to find the maximum length of a subarray with a sum of zero. | Here is the code to solve this problem:
```python
def maxLen(arr):
# create a dictionary to store the sum and its index
sum_index = {0: -1}
max_length = 0
current_sum = 0
# iterate over the array
for i, num in enumerate(arr):
current_sum += num
# if the sum has been seen befor... | [
"assert maxLen([1, 0, 3]) == 1",
"assert maxLen([1, 2, 3]) == 0",
"assert maxLen([15, -2, 2, -8, 1, 7, 10, 23]) == 5"
] | To find the maximum length of a subarray with a sum of zero, we can use a hash map (dictionary in Python) to keep track of the cumulative sums and their corresponding indices. The idea is that if we encounter the same cumulative sum again, the subarray between the two indices where the cumulative sum was found has a su... | 10,003 | [
{
"from": "human",
"value": "Write a python function to find the maximum length of a subarray with a sum of zero."
},
{
"from": "gpt",
"value": "To find the maximum length of a subarray with a sum of zero, we can use a hash map (dictionary in Python) to keep track of the cumulative sums and thei... |
Write a function to find the maximum value in a list of tuples based on the second element of each tuple. | Here is the code to solve this problem:
```python
def find_max_value(test_list):
res = max(test_list, key=lambda x: x[1])[1]
return (res)
``` | [
"assert find_max_value([(1, 3), (2, 2), (3, 1)]) == 3",
"assert find_max_value([(4, 10), (5, 5), (6, 15)]) == 15",
"assert find_max_value([(7, 20), (8, 18), (9, 25)]) == 25"
] | You can find the maximum value in a list of tuples based on the second element of each tuple using Python. Here’s a function that accomplishes this:
```python
def max_value_by_second_element(tuples_list):
# Check if the list is empty
if not tuples_list:
return None # or raise an exception, depending o... | 10,004 | [
{
"from": "human",
"value": "Write a function to find the maximum value in a list of tuples based on the second element of each tuple."
},
{
"from": "gpt",
"value": "You can find the maximum value in a list of tuples based on the second element of each tuple using Python. Here’s a function that ... |
Write a function to calculate the number of valid parentheses combinations given a number of pairs of parentheses. | Here is the code to solve this problem:
```python
def valid_parentheses_combinations(n):
if n <= 0:
return 1
dp = [0] * (n + 1)
dp[0] = 1
for i in range(1, n + 1):
for j in range(i):
dp[i] += dp[j] * dp[i - j - 1]
return dp[n]
``` | [
"assert valid_parentheses_combinations(5) == 42",
"assert valid_parentheses_combinations(4) == 14",
"assert valid_parentheses_combinations(3) == 5"
] | To calculate the number of valid combinations of parentheses for a given number of pairs \( n \), you can use the concept of **Catalan numbers**. The \( n \)-th Catalan number can be calculated using the formula:
\[
C_n = \frac{1}{n+1} \binom{2n}{n} = \frac{(2n)!}{(n+1)!n!}
\]
This can be implemented directly in Pyth... | 10,005 | [
{
"from": "human",
"value": "Write a function to calculate the number of valid parentheses combinations given a number of pairs of parentheses."
},
{
"from": "gpt",
"value": "To calculate the number of valid combinations of parentheses for a given number of pairs \\( n \\), you can use the conce... |
Write a function to find the median of two sorted arrays. | Here is the code to solve this problem:
```python
def median_two_sorted_arrays(arr1, arr2):
m, n = len(arr1), len(arr2)
if m > n:
arr1, arr2, m, n = arr2, arr1, n, m
imin, imax, half_len = 0, m, (m + n + 1) // 2
while imin <= imax:
i = (imin + imax) // 2
j = half_len - i
... | [
"assert median_two_sorted_arrays([1, 2], [3, 4])==2.5",
"assert median_two_sorted_arrays([1, 3], [2])==2.0",
"assert median_two_sorted_arrays([1, 3], [2, 7, 9])==3.0"
] | To find the median of two sorted arrays, you can use a binary search algorithm that works efficiently in \( O(\log(\min(n, m))) \) time, where \( n \) and \( m \) are the sizes of the two arrays. Here’s a Python function that accomplishes this:
```python
def findMedianSortedArrays(nums1, nums2):
# Ensure nums1 is ... | 10,006 | [
{
"from": "human",
"value": "Write a function to find the median of two sorted arrays."
},
{
"from": "gpt",
"value": "To find the median of two sorted arrays, you can use a binary search algorithm that works efficiently in \\( O(\\log(\\min(n, m))) \\) time, where \\( n \\) and \\( m \\) are the... |
Write a function called `merge_lists` that takes two lists as input and returns a new list that contains the elements of both input lists in alternating order. If one list is longer than the other, append the remaining elements of the longer list to the end of the merged list. | Here is the code to solve this problem:
```python
def merge_lists(list1, list2):
merged_list = []
i, j = 0, 0
while i < len(list1) and j < len(list2):
merged_list.append(list1[i])
merged_list.append(list2[j])
i += 1
j += 1
if i < len(list1):
merged_list.extend(li... | [
"assert merge_lists([1, 3, 5], [2, 4, 6, 8, 10]) == [1, 2, 3, 4, 5, 6, 8, 10]",
"assert merge_lists([1, 2, 3], [4, 5]) == [1, 4, 2, 5, 3]",
"assert merge_lists([], [1, 2, 3]) == [1, 2, 3]"
] | Here's a Python function called `merge_lists` that merges two lists in alternating order, appending any remaining elements from the longer list if needed.
```python
def merge_lists(list1, list2):
merged_list = []
# Get the minimum length of the two lists
min_length = min(len(list1), len(list2))
... | 10,007 | [
{
"from": "human",
"value": "Write a function called `merge_lists` that takes two lists as input and returns a new list that contains the elements of both input lists in alternating order. If one list is longer than the other, append the remaining elements of the longer list to the end of the merged list."
... |
Write a python function to generate a dictionary where the keys are numbers from 1 to n (inclusive) and the values are square of keys. | Here is the code to solve this problem:
```python
def square_dict(n):
return {i: i * i for i in range(1, n+1)}
``` | [
"assert square_dict(4) == {1: 1, 2: 4, 3: 9, 4: 16}",
"assert square_dict(2) == {1: 1, 2: 4}",
"assert square_dict(6) == {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}"
] | Certainly! Below is a Python function that generates a dictionary where the keys are numbers from 1 to `n` (inclusive) and the values are the squares of the keys.
```python
def generate_square_dict(n):
return {i: i**2 for i in range(1, n + 1)}
# Example usage:
result = generate_square_dict(5)
print(result)
```
#... | 10,008 | [
{
"from": "human",
"value": "Write a python function to generate a dictionary where the keys are numbers from 1 to n (inclusive) and the values are square of keys."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that generates a dictionary where the keys are numbers from 1 t... |
Write a function to find the maximum score that can be obtained by jumping through the elements of the given list. The score for each jump is the value of the element jumped to. You can jump up to k steps ahead from the current position. The goal is to reach the last index of the list. | Here is the code to solve this problem:
```python
from collections import deque
def max_score(nums, k):
deq = deque([0])
n = len(nums)
for i in range(1, n):
while deq and deq[0] < i - k: deq.popleft()
nums[i] += nums[deq[0]]
while deq and nums[i] >= nums[deq[-1]]: deq.pop()
... | [
"assert max_score([10, -5, -2, 4, 0, 3], 3) == 17",
"assert max_score([1, -1, -2, 4, -7, 3], 2) == 7",
"assert max_score([1, -5, -20, 4, -1, 3, -6, -3], 2) == 0"
] | To solve the problem of finding the maximum score obtained by jumping through the elements of a given list, we can use a dynamic programming approach. The idea is to track the maximum score that can be achieved at each index, starting from the first index and considering jumps that can be made up to `k` steps ahead.
H... | 10,009 | [
{
"from": "human",
"value": "Write a function to find the maximum score that can be obtained by jumping through the elements of the given list. The score for each jump is the value of the element jumped to. You can jump up to k steps ahead from the current position. The goal is to reach the last index of th... |
Write a python function to find the top K frequent elements in a given list. | Here is the code to solve this problem:
```python
from collections import Counter
def topKFrequent(nums, k):
count = Counter(nums)
return [i for i,_ in count.most_common(k)]
``` | [
"assert topKFrequent([1], 1) == [1]",
"assert topKFrequent([1,1,1,2,2,3], 2) == [1,2]",
"assert topKFrequent([4,1,2,2,3,3,3,4,4,4], 3) == [4, 3, 2]"
] | You can find the top K frequent elements in a list using the `collections.Counter` to count the occurrences of each element, and then use the `most_common` method to retrieve the K most common elements. Here's a Python function that implements this:
```python
from collections import Counter
def top_k_frequent(nums, k... | 10,010 | [
{
"from": "human",
"value": "Write a python function to find the top K frequent elements in a given list."
},
{
"from": "gpt",
"value": "You can find the top K frequent elements in a list using the `collections.Counter` to count the occurrences of each element, and then use the `most_common` met... |
Write a function that takes a list of words and a prefix string as input and returns a list of words that start with the given prefix. | Here is the code to solve this problem:
```python
def get_words_with_prefix(word_list, prefix):
return [word for word in word_list if word.startswith(prefix)]
``` | [
"assert get_words_with_prefix([], \"pre\") == []",
"assert get_words_with_prefix([\"apple\", \"banana\", \"grape\", \"pineapple\"], \"a\") == [\"apple\"]",
"assert get_words_with_prefix([\"preach\", \"prefix\", \"protest\", \"presentation\"], \"pre\") == [\"preach\", \"prefix\", \"presentation\"]"
] | You can create a function in Python that filters a list of words based on whether they start with a specified prefix. Here’s an example of how you can implement this:
```python
def words_starting_with_prefix(words, prefix):
"""
Returns a list of words that start with the given prefix.
:param words: List o... | 10,011 | [
{
"from": "human",
"value": "Write a function that takes a list of words and a prefix string as input and returns a list of words that start with the given prefix."
},
{
"from": "gpt",
"value": "You can create a function in Python that filters a list of words based on whether they start with a s... |
Write a python function to find the maximum profit from buying and selling a stock on different days. You can only make one transaction (buy one and sell one share of the stock). | Here is the code to solve this problem:
```python
def max_Profit(prices):
if not prices:
return 0
min_price = float('inf')
max_profit = 0
for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
return max_profit
``` | [
"assert max_Profit([7,1,5,3,6,4]) == 5",
"assert max_Profit([1,2,3,4,5]) == 4",
"assert max_Profit([7,6,4,3,1]) == 0"
] | Certainly! To find the maximum profit from buying and selling stock on different days with only one transaction allowed, you can implement a function that keeps track of the minimum price seen so far as you iterate through the list of stock prices. The maximum profit can then be calculated by subtracting the minimum pr... | 10,012 | [
{
"from": "human",
"value": "Write a python function to find the maximum profit from buying and selling a stock on different days. You can only make one transaction (buy one and sell one share of the stock)."
},
{
"from": "gpt",
"value": "Certainly! To find the maximum profit from buying and sel... |
Write a python function to find the number of ways to reach the last cell of a grid from the first cell using only allowed moves (right and down). | Here is the code to solve this problem:
```python
def numberOfWays(m, n):
if m == 1 or n == 1:
return 1
else:
return numberOfWays(m-1, n) + numberOfWays(m, n-1)
``` | [
"assert numberOfWays(3, 3) == 6",
"assert numberOfWays(2, 2) == 2",
"assert numberOfWays(4, 4) == 20"
] | You can solve the problem of finding the number of ways to reach the last cell of a grid (starting from the first cell) using dynamic programming. The allowed moves are only to the right and down. Here’s a Python function to do that:
```python
def count_paths(m, n):
# Create a 2D array to store the number of ways ... | 10,013 | [
{
"from": "human",
"value": "Write a python function to find the number of ways to reach the last cell of a grid from the first cell using only allowed moves (right and down)."
},
{
"from": "gpt",
"value": "You can solve the problem of finding the number of ways to reach the last cell of a grid ... |
Write a function to check if a graph is a star graph. A star graph is a tree with n nodes (where n >= 3) that consists of one central node with degree n - 1, and n - 1 leaves (nodes of degree 1). | Here is the code to solve this problem:
```python
def is_star_graph(edges):
n = len(edges)+1
indegree = [0]*(n+1)
for u,v in edges:
indegree[u]+=1
indegree[v]+=1
center = -1
for i in range(1, n+1):
if indegree[i] > 1:
if center != -1:
return Fals... | [
"assert is_star_graph([[1,2], [2,3], [3,4]]) == False",
"assert is_star_graph([[1,2], [2,3], [2,4]]) == True",
"assert is_star_graph([[1,2], [1,3], [1,4], [1,5]]) == True"
] | To determine if a graph is a star graph, we need to check the following properties:
1. The graph should have at least 3 nodes (n >= 3).
2. There should be exactly one node (the central node) with a degree of n - 1 (i.e., connected to all other nodes).
3. All other nodes (n - 1 leaves) should have a degree of 1.
Here'... | 10,014 | [
{
"from": "human",
"value": "Write a function to check if a graph is a star graph. A star graph is a tree with n nodes (where n >= 3) that consists of one central node with degree n - 1, and n - 1 leaves (nodes of degree 1)."
},
{
"from": "gpt",
"value": "To determine if a graph is a star graph,... |
Write a python function to find the number of trailing zeroes in a factorial of a number. | Here is the code to solve this problem:
```python
def count_trailing_zeroes(n):
count = 0
i=5
while n/i>=1:
count += int(n/i)
i *= 5
return int(count)
``` | [
"assert count_trailing_zeroes(10) == 2",
"assert count_trailing_zeroes(25) == 6",
"assert count_trailing_zeroes(5) == 1"
] | To find the number of trailing zeroes in the factorial of a number \( n \), you need to consider how many times 10 is a factor in the numbers multiplied together to form \( n! \). Since 10 is made of the factors 2 and 5, and there are generally more factors of 2 than 5 in this sequence, the number of trailing zeroes is... | 10,015 | [
{
"from": "human",
"value": "Write a python function to find the number of trailing zeroes in a factorial of a number."
},
{
"from": "gpt",
"value": "To find the number of trailing zeroes in the factorial of a number \\( n \\), you need to consider how many times 10 is a factor in the numbers mu... |
Write a function to find the minimum number of jumps required for a knight to reach from one position to another on a chessboard. | Here is the code to solve this problem:
```python
from collections import deque
def knight_moves(x1, y1, x2, y2):
# Define the possible moves of a knight
moves = [(2, 1), (1, 2), (-1, -2), (-2, -1), (-2, 1), (-1, 2), (1, -2), (2, -1)]
# Create a visited matrix to keep track of visited positions
v... | [
"assert knight_moves(1, 1, 1, 1) == 0",
"assert knight_moves(1, 1, 8, 8) == 6",
"assert knight_moves(8, 8, 1, 1) == 6"
] | To solve the problem of finding the minimum number of jumps required for a knight to reach from one position to another on a chessboard, we can use a Breadth-First Search (BFS) algorithm. The knight in chess moves in an L-shape: it can move to any of the eight possible positions from its current position.
Here's how y... | 10,016 | [
{
"from": "human",
"value": "Write a function to find the minimum number of jumps required for a knight to reach from one position to another on a chessboard."
},
{
"from": "gpt",
"value": "To solve the problem of finding the minimum number of jumps required for a knight to reach from one positi... |
Write a function to generate the nth ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. | Here is the code to solve this problem:
```python
import heapq
def nth_ugly_number(n):
ugly_numbers = [1]
factors = [2, 3, 5]
indexes = [0, 0, 0]
for _ in range(1, n):
new_ugly_numbers = [factors[j] * ugly_numbers[indexes[j]] for j in range(3)]
new_ugly_number = min(new_ugly_numbers)
ugly_numbers.a... | [
"assert nth_ugly_number(10) == 12",
"assert nth_ugly_number(1) == 1",
"assert nth_ugly_number(15) == 24"
] | To generate the nth ugly number, we can use a dynamic programming approach with multiple pointers. The idea is to keep track of the next multiple of each of the prime factors (2, 3, 5) and to iteratively determine the next ugly number based on these multiples.
Here's how the function can be implemented in Python:
```... | 10,017 | [
{
"from": "human",
"value": "Write a function to generate the nth ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5."
},
{
"from": "gpt",
"value": "To generate the nth ugly number, we can use a dynamic programming approach with multiple pointers. The idea is... |
Write a python function to find the minimum difference between any item from the first list and any item from the second list. | Here is the code to solve this problem:
```python
def min_difference(list1, list2):
list1.sort()
list2.sort()
i, j = 0, 0
min_diff = abs(list1[i] - list2[j])
while i < len(list1) and j < len(list2):
min_diff = min(min_diff, abs(list1[i] - list2[j]))
if list1[i] < list2[j]:
... | [
"assert min_difference([1, 2, 3], [4, 5, 6]) == 1",
"assert min_difference([100, 200, 300], [101, 201, 301]) == 1",
"assert min_difference([10, 20, 30], [15, 25, 35]) == 5"
] | Certainly! Below is a Python function that takes two lists as input and finds the minimum difference between any item from the first list and any item from the second list.
```python
def min_difference(list1, list2):
if not list1 or not list2:
raise ValueError("Both lists must contain at least one element.... | 10,018 | [
{
"from": "human",
"value": "Write a python function to find the minimum difference between any item from the first list and any item from the second list."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that takes two lists as input and finds the minimum difference between ... |
Write a function to find the number of days between two dates. | Here is the code to solve this problem:
```python
from datetime import datetime
def date_diff(date1, date2):
date_format = "%Y-%m-%d"
a = datetime.strptime(date1, date_format)
b = datetime.strptime(date2, date_format)
delta = b - a
return abs(delta.days)
``` | [
"assert date_diff(\"2019-12-31\", \"2020-01-01\")==1",
"assert date_diff(\"2020-01-15\", \"2020-02-14\")==30",
"assert date_diff(\"2021-02-28\", \"2021-03-01\")==1"
] | You can create a function in Python that calculates the number of days between two dates using the `datetime` module. Here’s a simple implementation:
```python
from datetime import datetime
def days_between_dates(date1, date2):
# Convert string dates to datetime objects
d1 = datetime.strptime(date1, '%Y-%m-%d... | 10,019 | [
{
"from": "human",
"value": "Write a function to find the number of days between two dates."
},
{
"from": "gpt",
"value": "You can create a function in Python that calculates the number of days between two dates using the `datetime` module. Here’s a simple implementation:\n\n```python\nfrom date... |
Write a python function to find the total number of palindromic substrings in a given string.
A palindromic string is a string that reads the same backward as forward. | Here is the code to solve this problem:
```python
def count_palindromes(s):
def expand_around_center(left, right):
count = 0
while left >= 0 and right < len(s) and s[left] == s[right]:
count += 1
left -= 1
right += 1
return count
total_count = 0
... | [
"assert count_palindromes(\"racecar\") == 10",
"assert count_palindromes(\"abc\") == 3",
"assert count_palindromes(\"aaa\") == 6"
] | You can find the total number of palindromic substrings in a string using a couple of approaches. Here, I will provide a function using the "expand around center" technique, which is efficient and straightforward. This method checks for palindromes by expanding around each character (and each pair of characters) in the... | 10,020 | [
{
"from": "human",
"value": "Write a python function to find the total number of palindromic substrings in a given string.\n\nA palindromic string is a string that reads the same backward as forward."
},
{
"from": "gpt",
"value": "You can find the total number of palindromic substrings in a stri... |
Write a python function that takes a string and returns a new string with the first letter capitalized. | Here is the code to solve this problem:
```python
def capitalize_first_letter(str):
return str[0].upper() + str[1:]
``` | [
"assert capitalize_first_letter('python') == 'Python'",
"assert capitalize_first_letter('world') == 'World'",
"assert capitalize_first_letter('hello') == 'Hello'"
] | You can easily create a Python function to capitalize the first letter of a string using the `capitalize()` method or by combining string slicing with the `upper()` method. Below are two examples demonstrating each approach.
### Method 1: Using `capitalize()`
```python
def capitalize_first_letter(input_string):
r... | 10,021 | [
{
"from": "human",
"value": "Write a python function that takes a string and returns a new string with the first letter capitalized."
},
{
"from": "gpt",
"value": "You can easily create a Python function to capitalize the first letter of a string using the `capitalize()` method or by combining s... |
Write a function that takes a list of integers and returns a new list with each element's square. | Here is the code to solve this problem:
```python
def square_elements(numbers):
return [num ** 2 for num in numbers]
``` | [
"assert square_elements([1, 2, 3, 4, 5]) == [1, 4, 9, 16, 25]",
"assert square_elements([2, 4, 6, 8, 10]) == [4, 16, 36, 64, 100]",
"assert square_elements([0, -1, -2, -3, -4]) == [0, 1, 4, 9, 16]"
] | You can create a function in Python that takes a list of integers and returns a new list containing the squares of each element. Here's a simple implementation using a list comprehension:
```python
def square_elements(input_list):
return [x ** 2 for x in input_list]
# Example usage:
numbers = [1, 2, 3, 4, 5]
squa... | 10,022 | [
{
"from": "human",
"value": "Write a function that takes a list of integers and returns a new list with each element's square."
},
{
"from": "gpt",
"value": "You can create a function in Python that takes a list of integers and returns a new list containing the squares of each element. Here's a ... |
Write a python function to find the maximum number of consecutive 1's in the array if you can change at most one 0. | Here is the code to solve this problem:
```python
def find_max_consecutive_ones(nums):
left, right, zero_count, max_len = 0, 0, 0, 0
while right < len(nums):
if nums[right] == 0:
zero_count += 1
while zero_count > 1:
if nums[left] == 0:
zero_count -= 1
... | [
"assert find_max_consecutive_ones([1,0,1,1,0]) == 4",
"assert find_max_consecutive_ones([1,0,1,1,0,1]) == 4",
"assert find_max_consecutive_ones([0,0,1,1]) == 3"
] | You can solve this problem using a sliding window approach. The idea is to maintain a window that represents the current sequence of 1's where you can change at most one 0 to a 1. Here’s a Python function to implement this:
```python
def longest_ones_with_one_flip(nums):
left = 0 # Left end of the window
max_... | 10,023 | [
{
"from": "human",
"value": "Write a python function to find the maximum number of consecutive 1's in the array if you can change at most one 0."
},
{
"from": "gpt",
"value": "You can solve this problem using a sliding window approach. The idea is to maintain a window that represents the current... |
Write a Python function that takes a list of integers and returns a new list with elements that are the square of the original elements in reverse order. | Here is the code to solve this problem:
```python
def reverse_square(nums):
return [i*i for i in reversed(nums)]
``` | [
"assert reverse_square([10, 9, 8, 7, 6]) == [36, 49, 64, 81, 100]",
"assert reverse_square([1, 2, 3, 4, 5]) == [25, 16, 9, 4, 1]",
"assert reverse_square([-2, -3, -4]) == [16, 9, 4]"
] | You can create a Python function that takes a list of integers, squares each element, and then returns a new list with the squared values in reverse order. Here is how you can do it:
```python
def square_and_reverse(input_list):
# Square each element and create a new list
squared_list = [x**2 for x in input_li... | 10,024 | [
{
"from": "human",
"value": "Write a Python function that takes a list of integers and returns a new list with elements that are the square of the original elements in reverse order."
},
{
"from": "gpt",
"value": "You can create a Python function that takes a list of integers, squares each eleme... |
Write a function that takes a list of strings and returns a list of unique strings. The order of the strings in the output list should be the same as the order of their first occurrence in the input list. | Here is the code to solve this problem:
```python
def get_unique_strings(strings):
unique_strings = []
seen = set()
for string in strings:
if string not in seen:
unique_strings.append(string)
seen.add(string)
return unique_strings
``` | [
"assert get_unique_strings([\"hello\", \"world\", \"hello\", \"python\", \"world\", \"java\"]) == [\"hello\", \"world\", \"python\", \"java\"]",
"assert get_unique_strings([\"cat\", \"dog\", \"bird\", \"cat\", \"dog\", \"fish\"]) == [\"cat\", \"dog\", \"bird\", \"fish\"]",
"assert get_unique_strings([\"apple\",... | Certainly! You can achieve this using Python by defining a function that iterates over the list of strings while keeping track of the unique strings encountered. Here’s one way to implement such a function:
```python
def unique_strings(input_list):
unique_list = []
seen = set()
for string in input_lis... | 10,025 | [
{
"from": "human",
"value": "Write a function that takes a list of strings and returns a list of unique strings. The order of the strings in the output list should be the same as the order of their first occurrence in the input list."
},
{
"from": "gpt",
"value": "Certainly! You can achieve this... |
Write a function to find the number of times a sorted array is rotated. The array was originally sorted in increasing order, but then rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). | Here is the code to solve this problem:
```python
def find_rotation_count(arr):
low, high = 0, len(arr) - 1
if len(arr) == 0:
return 0
while low <= high:
if arr[low] <= arr[high]:
return low
mid = (low + high) // 2
next = (mid + 1) % len(arr)
prev = (mi... | [
"assert find_rotation_count([1, 2, 3, 4, 5]) == 0",
"assert find_rotation_count([7, 9, 11, 12, 5]) == 4",
"assert find_rotation_count([15, 18, 2, 3, 6, 12]) == 2"
] | To find the number of times a sorted array has been rotated, you can use a modified binary search approach. The idea is to find the point where the array is "broken" — that is, the point where the order of the elements changes from increasing to a smaller number due to the rotation.
Here's how you can implement this i... | 10,026 | [
{
"from": "human",
"value": "Write a function to find the number of times a sorted array is rotated. The array was originally sorted in increasing order, but then rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2])."
},
{
"from": "gpt",
"value": ... |
Write a function to convert a list into a dictionary where keys are the elements of the list and values are the frequency of the elements. | Here is the code to solve this problem:
```python
def list_to_dict(lst):
"""
Converts a list of elements into a dictionary where keys are the elements of the list and values are the frequency of the elements.
"""
freq_dict = {}
for item in lst:
if item in freq_dict:
freq_dict[it... | [
"assert list_to_dict(['red', 'blue', 'red', 'green', 'blue', 'blue']) == {'red': 2, 'blue': 3, 'green': 1}",
"assert list_to_dict(['apple', 'banana', 'apple', 'orange', 'banana', 'banana']) == {'apple': 2, 'banana': 3, 'orange': 1}",
"assert list_to_dict(['a', 'b', 'c', 'a', 'b', 'b', 'b']) == {'a': 2, 'b': 4, ... | Certainly! You can create a function in Python that takes a list as input and outputs a dictionary where each key is an element from the list and the corresponding value is the frequency of that element. Here’s how you can do it:
```python
def list_to_frequency_dict(lst):
frequency_dict = {}
for element in lst... | 10,027 | [
{
"from": "human",
"value": "Write a function to convert a list into a dictionary where keys are the elements of the list and values are the frequency of the elements."
},
{
"from": "gpt",
"value": "Certainly! You can create a function in Python that takes a list as input and outputs a dictionar... |
Write a python function to check if two given strings are anagrams of each other. | Here is the code to solve this problem:
```python
def is_Anagram(str1,str2):
if sorted(str1) == sorted(str2):
return True
else:
return False
``` | [
"assert is_Anagram(\"listen\",\"silent\") == True",
"assert is_Anagram(\"cinema\",\"iceman\") == True",
"assert is_Anagram(\"hello\",\"world\") == False"
] | Certainly! An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all original letters exactly once. To check if two strings are anagrams of each other, you can follow these steps:
1. Remove any whitespace and convert both strings to the same case (e.g., lower c... | 10,028 | [
{
"from": "human",
"value": "Write a python function to check if two given strings are anagrams of each other."
},
{
"from": "gpt",
"value": "Certainly! An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all original letters exactly on... |
Write a function to calculate the roots of a quadratic equation. The function should return both roots as a tuple (root1, root2). If there are no real roots, return None. | Here is the code to solve this problem:
```python
import cmath
def quadratic_roots(a, b, c):
d = (b**2) - (4*a*c)
if d < 0: return None
else:
root1 = (-b + cmath.sqrt(d)) / (2 * a)
root2 = (-b - cmath.sqrt(d)) / (2 * a)
return (root1.real, root2.real)
``` | [
"assert quadratic_roots(1, -3, 2) == (2.0, 1.0)",
"assert quadratic_roots(1, 4, 4) == (-2.0, -2.0)",
"assert quadratic_roots(1, 0, -4) == (2.0, -2.0)",
"assert quadratic_roots(1, 0, 1) == None"
] | Certainly! In Python, you can calculate the roots of a quadratic equation of the form \( ax^2 + bx + c = 0 \) using the quadratic formula:
\[
x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}
\]
The discriminant \( D = b^2 - 4ac \) determines the nature of the roots:
- If \( D > 0 \), there are two distinct real roots.
- If \( ... | 10,029 | [
{
"from": "human",
"value": "Write a function to calculate the roots of a quadratic equation. The function should return both roots as a tuple (root1, root2). If there are no real roots, return None."
},
{
"from": "gpt",
"value": "Certainly! In Python, you can calculate the roots of a quadratic ... |
Write a python function to check if a string is a palindrome and it also contains all the alphabets. The function should return True if the string is a palindrome and contains all the alphabets, otherwise return False. | Here is the code to solve this problem:
```python
def is_palindrome_and_pangram(s):
s = s.lower()
s = ''.join([i for i in s if i.isalpha()])
return s == s[::-1] and len(set(s)) == 26
``` | [
"assert is_palindrome_and_pangram(\"The quick brown fox jumps over the lazy dog\") == False",
"assert is_palindrome_and_pangram(\"A man, a plan, a canal, Panama\") == False",
"assert is_palindrome_and_pangram(\"zyxwvutsrqponmlkjihgfedcba\") == False",
"assert is_palindrome_and_pangram(\"abcdefghijklmnopqrstuv... | Certainly! Below is a Python function that checks if a given string is a palindrome and also contains all the letters of the English alphabet (from 'a' to 'z'):
```python
def is_palindrome_and_contains_all_alphabets(s):
# Normalize the string by converting it to lowercase and filtering only alphabetic characters
... | 10,030 | [
{
"from": "human",
"value": "Write a python function to check if a string is a palindrome and it also contains all the alphabets. The function should return True if the string is a palindrome and contains all the alphabets, otherwise return False."
},
{
"from": "gpt",
"value": "Certainly! Below ... |
Write a python function to find the number of digits in a given number. | Here is the code to solve this problem:
```python
def count_digits(n):
if n == 0:
return 1
count = 0
while n != 0:
n = n // 10
count += 1
return count
``` | [
"assert count_digits(0) == 1",
"assert count_digits(123) == 3",
"assert count_digits(10000) == 5"
] | You can write a Python function to find the number of digits in a given number by converting the number to a string and then counting its length. Here's a simple implementation of such a function:
```python
def count_digits(number):
# Convert the number to its absolute value and then to a string
str_number = s... | 10,031 | [
{
"from": "human",
"value": "Write a python function to find the number of digits in a given number."
},
{
"from": "gpt",
"value": "You can write a Python function to find the number of digits in a given number by converting the number to a string and then counting its length. Here's a simple im... |
Write a function that takes a list of numbers and returns a list of the unique numbers in the original list in the order they first appeared. | Here is the code to solve this problem:
```python
from typing import List
def unique_numbers(nums: List[int]) -> List[int]:
seen = set()
result = []
for num in nums:
if num not in seen:
result.append(num)
seen.add(num)
return result
``` | [
"assert unique_numbers([1, 1, 1, 1, 1])==[1]",
"assert unique_numbers([1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 8, 9])==[1, 2, 3, 4, 5, 6, 7, 8, 9]",
"assert unique_numbers([1, 2, 2, 3])==[1, 2, 3]"
] | You can accomplish this in Python using a function that leverages a set to track the unique numbers while maintaining a list for the output. Here’s a sample function that does exactly that:
```python
def unique_numbers(numbers):
seen = set()
unique_list = []
for number in numbers:
if number no... | 10,032 | [
{
"from": "human",
"value": "Write a function that takes a list of numbers and returns a list of the unique numbers in the original list in the order they first appeared."
},
{
"from": "gpt",
"value": "You can accomplish this in Python using a function that leverages a set to track the unique nu... |
Write a function to convert a given matrix into its transpose. | Here is the code to solve this problem:
```python
def matrix_transpose(matrix):
return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
``` | [
"assert matrix_transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[1, 4, 7], [2, 5, 8], [3, 6, 9]]",
"assert matrix_transpose([[10, 20], [30, 40], [50, 60]]) == [[10, 30, 50], [20, 40, 60]]",
"assert matrix_transpose([[1, 2], [3, 4], [5, 6], [7, 8]]) == [[1, 3, 5, 7], [2, 4, 6, 8]]"
] | Sure! In mathematics, the transpose of a matrix is produced by swapping the rows and columns. Here’s a simple Python function that takes a matrix (represented as a list of lists) as input and returns its transpose.
```python
def transpose(matrix):
# Check if the matrix is empty
if not matrix:
return []... | 10,033 | [
{
"from": "human",
"value": "Write a function to convert a given matrix into its transpose."
},
{
"from": "gpt",
"value": "Sure! In mathematics, the transpose of a matrix is produced by swapping the rows and columns. Here’s a simple Python function that takes a matrix (represented as a list of l... |
Write a function that takes two integers as its parameters and returns the integer part of their division. Then, write another function that uses this division function to compute the average of a list of integers. | Here is the code to solve this problem:
```python
def integer_division(dividend, divisor):
return dividend // divisor
def calculate_average(numbers):
return integer_division(sum(numbers), len(numbers))
``` | [
"assert integer_division(15, 5) == 3",
"assert integer_division(9, 2) == 4",
"assert integer_division(10, 3) == 3",
"assert calculate_average([5, 15, 25, 35, 45]) == 25",
"assert calculate_average([10, 20, 30, 40, 50]) == 30",
"assert calculate_average([1, 2, 3, 4, 5]) == 3",
""
] | Sure! Below are the implementations of the required functions in Python.
1. The first function, `integer_division`, takes two integers as parameters and returns the integer part of their division.
2. The second function, `average_of_list`, takes a list of integers, uses the `integer_division` function to compute the a... | 10,034 | [
{
"from": "human",
"value": "Write a function that takes two integers as its parameters and returns the integer part of their division. Then, write another function that uses this division function to compute the average of a list of integers."
},
{
"from": "gpt",
"value": "Sure! Below are the i... |
Write a function to find the total number of occurrences of a substring in a given string. | Here is the code to solve this problem:
```python
def find_substring_occurrences(string, substring):
count = 0
index = 0
while index < len(string):
index = string.find(substring, index)
if index == -1:
break
count += 1
index += len(substring)
return count
``` | [
"assert find_substring_occurrences(\"ababababab\", \"abab\") == 2",
"assert find_substring_occurrences(\"Hello World\", \"o\") == 2",
"assert find_substring_occurrences(\"Hello Hello Hello\", \"Hello\") == 3"
] | You can find the total number of occurrences of a substring in a given string using Python. Below is a simple function that accomplishes this:
```python
def count_occurrences(main_string, substring):
count = 0
start = 0
while True:
start = main_string.find(substring, start)
if start == -1:... | 10,035 | [
{
"from": "human",
"value": "Write a function to find the total number of occurrences of a substring in a given string."
},
{
"from": "gpt",
"value": "You can find the total number of occurrences of a substring in a given string using Python. Below is a simple function that accomplishes this:\n\... |
Write a python function that implements binary search on a 2D matrix. The function should return True if the target is found in the matrix and False otherwise. The matrix has the following properties:
- Each row is sorted in non-decreasing order.
- The first integer of each row is greater than the last integer of the p... | Here is the code to solve this problem:
```python
def search_matrix(matrix, target):
m, n = len(matrix), len(matrix[0])
left, right = 0, m * n - 1
while left <= right:
mid = left + (right - left) // 2
mid_val = matrix[mid // n][mid % n]
if mid_val == target:
return Tru... | [
"assert search_matrix([[1]], 1) == True",
"assert search_matrix([[1,3,5,7],[10,11,16,20],[23,30,34,60]], 3) == True",
"assert search_matrix([[1,3,5,7],[10,11,16,20],[23,30,34,60]], 13) == False",
"assert search_matrix([[1,2],[3,4]], 4) == True"
] | To implement a binary search on a 2D matrix with the properties you've described, we can treat the 2D matrix as a flat sorted array. This means that we can use a single binary search to find the target value. Here’s how you can achieve that:
1. Calculate the total number of elements in the matrix, which is `m * n` (wh... | 10,036 | [
{
"from": "human",
"value": "Write a python function that implements binary search on a 2D matrix. The function should return True if the target is found in the matrix and False otherwise. The matrix has the following properties:\n- Each row is sorted in non-decreasing order.\n- The first integer of each ro... |
Write a python function that takes a matrix of integers as input and returns a list of integers that are the diagonal elements of the matrix. | Here is the code to solve this problem:
```python
def diagonal_elements(matrix):
result = []
for i in range(len(matrix)):
result.append(matrix[i][i])
return result
``` | [
"assert diagonal_elements([[1, 2, 3], [4, 5, 6], [7, 8, 9]])==[1, 5, 9]",
"assert diagonal_elements([[1, 2], [3, 4]])==[1, 4]",
"assert diagonal_elements([[1]])==[1]"
] | Certainly! Here is a Python function that takes a matrix (list of lists) of integers as input and returns a list of the diagonal elements of the matrix:
```python
def get_diagonal_elements(matrix):
# Initialize an empty list to store diagonal elements
diagonal_elements = []
# Iterate through the matri... | 10,037 | [
{
"from": "human",
"value": "Write a python function that takes a matrix of integers as input and returns a list of integers that are the diagonal elements of the matrix."
},
{
"from": "gpt",
"value": "Certainly! Here is a Python function that takes a matrix (list of lists) of integers as input ... |
Write a function to calculate the sum of the first and third largest numbers in a list.
Given a list of integers, return the sum of the first and third largest numbers in the list. If the list contains less than three elements, return the sum of the elements present. | Here is the code to solve this problem:
```python
def sum_first_third_largest(nums):
if len(nums) < 3:
return sum(nums)
else:
nums.sort()
return nums[-1] + nums[-3]
``` | [
"assert sum_first_third_largest([1, 2, 3, 4, 5]) == 8",
"assert sum_first_third_largest([5, 1, 2, 4, 3]) == 8",
"assert sum_first_third_largest([1, 2]) == 3",
"assert sum_first_third_largest([10]) == 10"
] | Here's a Python function that calculates the sum of the first and third largest numbers in a list, and handles the case where the list has fewer than three elements by returning the sum of the available elements:
```python
def sum_first_and_third_largest(numbers):
# Check if the list has less than three elements
... | 10,038 | [
{
"from": "human",
"value": "Write a function to calculate the sum of the first and third largest numbers in a list.\n\nGiven a list of integers, return the sum of the first and third largest numbers in the list. If the list contains less than three elements, return the sum of the elements present."
},
... |
Write a function to find the intersection of two lists, returning the common elements without duplicates. The function should sort the result in ascending order. | Here is the code to solve this problem:
```python
def sorted_intersection(list1, list2):
"""
Return the sorted intersection of two lists without duplicates.
"""
# Set intersection to find common elements and remove duplicates
result = list(set(list1) & set(list2))
# Sort the result
result.s... | [
"assert sorted_intersection([1, 4, 3, 34, 653, 2, 5], [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]",
"assert sorted_intersection([10, 20, 30], [15, 25, 35]) == []",
"assert sorted_intersection([5, 3, 2, 8], [3, 2]) == [2, 3]"
] | You can create a function in Python to find the intersection of two lists, removing duplicates and sorting the result. Here’s a simple implementation:
```python
def intersect_lists(list1, list2):
# Convert both lists to sets to get unique elements
set1 = set(list1)
set2 = set(list2)
# Find the int... | 10,039 | [
{
"from": "human",
"value": "Write a function to find the intersection of two lists, returning the common elements without duplicates. The function should sort the result in ascending order."
},
{
"from": "gpt",
"value": "You can create a function in Python to find the intersection of two lists,... |
Write a function to calculate the maximum profit from stock trading given a list of daily prices. You can make as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). However, you must sell the stock before you buy again. | Here is the code to solve this problem:
```python
def calculate_max_profit(prices):
max_profit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
max_profit += prices[i] - prices[i - 1]
return max_profit
``` | [
"assert calculate_max_profit([1, 2, 3, 4, 5]) == 4",
"assert calculate_max_profit([7, 1, 5, 3, 6, 4]) == 7",
"assert calculate_max_profit([7, 6, 4, 3, 1]) == 0"
] | To calculate the maximum profit from stock trading given a list of daily prices, we can use a simple algorithm. The key idea is that whenever the price rises from one day to the next, we should consider it as an opportunity to buy on the earlier day and sell on the later day. We just keep adding the profit from those t... | 10,040 | [
{
"from": "human",
"value": "Write a function to calculate the maximum profit from stock trading given a list of daily prices. You can make as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). However, you must sell the stock before you buy again."
},
{
"f... |
Write a python function to convert a list to a string using a specific separator. | Here is the code to solve this problem:
```python
def list_to_string(list1, separator):
return separator.join(list1)
``` | [
"assert list_to_string(['a', 'b', 'c', 'd'], ',') == 'a,b,c,d'",
"assert list_to_string(['Python', 'Programming'], ' ') == 'Python Programming'",
"assert list_to_string(['Hello', 'world'], '-') == 'Hello-world'"
] | Certainly! You can create a Python function that takes a list and a separator string as arguments and returns the elements of the list as a single string, with each element separated by the specified separator. Here’s an example of how you might implement this:
```python
def list_to_string(lst, separator):
"""Conv... | 10,041 | [
{
"from": "human",
"value": "Write a python function to convert a list to a string using a specific separator."
},
{
"from": "gpt",
"value": "Certainly! You can create a Python function that takes a list and a separator string as arguments and returns the elements of the list as a single string,... |
Write a function to find the number of unique triplets in a list of numbers where all three numbers are different from each other. | Here is the code to solve this problem:
```python
def unequalTriplets(nums):
count = {}
for _ in nums:
if _ not in count:
count[_] = 1
else:
count[_] += 1
res = 0
n = len(nums)
t = 0
for _, v in count.items():
res += t * v * (n - t - v)
t ... | [
"assert unequalTriplets([1, 2, 3, 4, 5])==10",
"assert unequalTriplets([4, 4, 2, 4, 3])==3",
"assert unequalTriplets([1, 1, 1, 1, 1])==0"
] | To find the number of unique triplets in a list of numbers where all three numbers are different, we can implement a function in Python. The approach used here involves using a set to ensure that we only consider unique combinations of triplets.
Below is a sample implementation:
```python
from itertools import combin... | 10,042 | [
{
"from": "human",
"value": "Write a function to find the number of unique triplets in a list of numbers where all three numbers are different from each other."
},
{
"from": "gpt",
"value": "To find the number of unique triplets in a list of numbers where all three numbers are different, we can ... |
Write a python function to find the second largest number in a list of integers. | Here is the code to solve this problem:
```python
def second_largest_number(numbers):
if len(numbers) < 2:
return None
unique_numbers = list(set(numbers))
if len(unique_numbers) < 2:
return None
unique_numbers.sort()
return unique_numbers[-2]
``` | [
"assert second_largest_number([1, 2, 3, 4, 5]) == 4",
"assert second_largest_number([5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 9",
"assert second_largest_number([10]) == None",
"assert second_largest_number([2, 2, 2, 2]) == None",
"assert second_largest_number([10, 9]) == 9"
] | You can find the second largest number in a list of integers by first creating a set to remove duplicates, then sorting the set and retrieving the second largest element. Here's a simple function to do that:
```python
def second_largest(numbers):
# Remove duplicates by converting the list to a set
unique_numbe... | 10,043 | [
{
"from": "human",
"value": "Write a python function to find the second largest number in a list of integers."
},
{
"from": "gpt",
"value": "You can find the second largest number in a list of integers by first creating a set to remove duplicates, then sorting the set and retrieving the second l... |
Write a function that takes a list of integers as input and returns a list of tuples, where each tuple contains the original number and a string indicating whether the number is 'Even' or 'Odd'. | Here is the code to solve this problem:
```python
def even_odd(numbers):
result = []
for number in numbers:
if number % 2 == 0:
result.append((number, 'Even'))
else:
result.append((number, 'Odd'))
return result
``` | [
"assert even_odd([1, 2, 3, 4, 5]) == [(1, 'Odd'), (2, 'Even'), (3, 'Odd'), (4, 'Even'), (5, 'Odd')]",
"assert even_odd([10, 21, 32, 43, 54]) == [(10, 'Even'), (21, 'Odd'), (32, 'Even'), (43, 'Odd'), (54, 'Even')]",
"assert even_odd([0, -1, -2, -3, -4]) == [(0, 'Even'), (-1, 'Odd'), (-2, 'Even'), (-3, 'Odd'), (-... | You can achieve this by defining a function in Python that iterates through the list of integers, checks whether each number is even or odd, and constructs the output as a list of tuples. Here's one way to implement this:
```python
def classify_numbers(numbers):
result = []
for number in numbers:
if nu... | 10,044 | [
{
"from": "human",
"value": "Write a function that takes a list of integers as input and returns a list of tuples, where each tuple contains the original number and a string indicating whether the number is 'Even' or 'Odd'."
},
{
"from": "gpt",
"value": "You can achieve this by defining a functi... |
Write a function to convert a given number into a string that represents the number in words. The function should handle numbers from 0 to 999. | Here is the code to solve this problem:
```python
def number_to_words(num):
ones = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
teens = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
tens = ["", "", "Twenty", "T... | [
"assert number_to_words(123) == \"One Hundred Twenty Three\"",
"assert number_to_words(12) == \"Twelve\"",
"assert number_to_words(0) == \"Zero\"",
"assert number_to_words(100) == \"One Hundred\""
] | Certainly! Below is a Python function that converts a given number (between 0 and 999) into its corresponding string representation in words.
```python
def number_to_words(n):
if not (0 <= n <= 999):
raise ValueError("Number must be between 0 and 999")
# Define the words for numbers
below_20 =... | 10,045 | [
{
"from": "human",
"value": "Write a function to convert a given number into a string that represents the number in words. The function should handle numbers from 0 to 999."
},
{
"from": "gpt",
"value": "Certainly! Below is a Python function that converts a given number (between 0 and 999) into ... |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 18