text stringlengths 64 30.9k | user stringlengths 1 14.5k | assistant stringlengths 1 17.3k |
|---|---|---|
<|im_start|>user
Powdered snow can be placed on the ground right before you fall and that can prevent fall damage. This is called an MLG. The player can do this with water. powdered snow does not disappear in the nether like water does.
<|im_end|>
<|im_start|>assistant
Powdered snow can be placed on the ground right be... | Powdered snow can be placed on the ground right before you fall and that can prevent fall damage. This is called an MLG. The player can do this with water. powdered snow does not disappear in the nether like water does. | Powdered snow can be placed on the ground right before you fall and that can prevent fall damage. This is called an MLG. The player can do this with water. powdered snow does not disappear in the nether like water does. |
<|im_start|>user
You are given two floating-point numbers, `a` and `b`. Your task is to compute the signed remainder of `a` divided by `b` without using any built-in modulo or division operations. The result should be accurate up to six decimal places. If `b` is zero, your function should return `None`.
**Input:**
- T... | You are given two floating-point numbers, `a` and `b`. Your task is to compute the signed remainder of `a` divided by `b` without using any built-in modulo or division operations. The result should be accurate up to six decimal places. If `b` is zero, your function should return `None`.
**Input:**
- Two floating-point... | ```python
def signed_remainder(a, b):
"""
Computes the signed remainder of a divided by b without using built-in modulo or division operations.
Parameters:
a (float): The dividend.
b (float): The divisor.
Returns:
float: The signed remainder of a divided by b, rounded to six decima... |
<|im_start|>user
Why is it so cold there?
<|im_end|>
<|im_start|>assistant
Why is it so cold there?
<|im_end|> | Why is it so cold there? | Why is it so cold there? |
<|im_start|>user
You are developing a web application that requires parsing product prices from variously formatted strings. Your task is to implement a function `extract_numeric_price(price_string)` that extracts the numeric price from a given string and returns it as a float. The input strings may contain currency sy... | You are developing a web application that requires parsing product prices from variously formatted strings. Your task is to implement a function `extract_numeric_price(price_string)` that extracts the numeric price from a given string and returns it as a float. The input strings may contain currency symbols, spaces, an... | ```python
import re
def extract_numeric_price(price_string):
"""
Extracts the numeric price from a given string and returns it as a float.
Args:
price_string (str): A string representing the price in an unstructured format.
Returns:
float: The numeric price value.
Raises:
... |
<|im_start|>user
Identify whether the following sentence is a positive or negative assertion or a positive or negative query. Output 1 for positive assertion, 2 for negative assertion, 3 for positive query, and 4 for negative query. Additionally, provide a justification for your output based on the sentiment analysis o... | Identify whether the following sentence is a positive or negative assertion or a positive or negative query. Output 1 for positive assertion, 2 for negative assertion, 3 for positive query, and 4 for negative query. Additionally, provide a justification for your output based on the sentiment analysis of the sentence. U... | [{'content': "Identify whether the following sentence is a positive or negative assertion or a positive or negative query. Output 1 for positive assertion, 2 for negative assertion, 3 for positive query, and 4 for negative query. Additionally, provide a justification for your output based on the sentiment analysis of t... |
<|im_start|>user
You are developing a team management system and need to implement a function `rename_team` that allows a user to rename their team. The function should take two parameters: `user_id` (an integer) and `new_name` (a string). The function must verify that the user is a member of a team. If not, it should ... | You are developing a team management system and need to implement a function `rename_team` that allows a user to rename their team. The function should take two parameters: `user_id` (an integer) and `new_name` (a string). The function must verify that the user is a member of a team. If not, it should return the string... | ```python
def rename_team(user_id, new_name):
"""
Renames a team for a given user if the user is a member of a team and the new name is a palindrome containing at least one vowel.
Parameters:
user_id (int): The unique identifier of the user.
new_name (str): The new name for the team.
R... |
<|im_start|>user
You are given a string `s`. Your task is to implement a function `isUniqueCharsInString` that checks if all characters in the string are unique, ignoring case and punctuation. The function should return `True` if all characters are unique, and `False` otherwise. The function should have a time complexi... | You are given a string `s`. Your task is to implement a function `isUniqueCharsInString` that checks if all characters in the string are unique, ignoring case and punctuation. The function should return `True` if all characters are unique, and `False` otherwise. The function should have a time complexity of O(N) and a ... | ```python
import string
def isUniqueCharsInString(s):
"""
Determines if all characters in the string are unique, ignoring case and punctuation.
:param s: Input string
:return: True if all characters are unique, False otherwise
"""
# Convert to lower case
s = s.lower()
# Remove punc... |
<|im_start|>user
You are tasked with creating a dish that requires a specific flavor profile. The flavor profile is defined by a string of flavors and a corresponding list of integers representing the amounts of each flavor. Your goal is to implement a function that constructs a dictionary from these inputs. The dictio... | You are tasked with creating a dish that requires a specific flavor profile. The flavor profile is defined by a string of flavors and a corresponding list of integers representing the amounts of each flavor. Your goal is to implement a function that constructs a dictionary from these inputs. The dictionary should map e... | ```python
def create_flavor_dict(flavors, amounts):
"""
Constructs a dictionary mapping each unique flavor to the total amount of that flavor.
Parameters:
flavors (str): A string of flavors represented by lowercase alphabetic characters.
amounts (list of int): A list of integers representing th... |
<|im_start|>user
You are given the task of developing a Python program to evaluate and compare the performance of multiple functions. Your program should accept a list of functions and their corresponding arguments, execute each function with its arguments, and output the average execution time for each function. To en... | You are given the task of developing a Python program to evaluate and compare the performance of multiple functions. Your program should accept a list of functions and their corresponding arguments, execute each function with its arguments, and output the average execution time for each function. To ensure accurate per... | ```python
import time
import statistics
def timeit_avg(num_runs):
"""
Decorator to measure and print the average execution time of a function,
excluding outliers that deviate from the median by more than two standard deviations.
:param num_runs: Number of times to run the function for averaging.
... |
<|im_start|>user
You are given a list of strings `strings` where each string consists of a combination of alphabetic and numeric characters. Your task is to implement a function `sort_alphanumeric` that sorts the list alphanumerically. The sorting should be based first on the alphabetical part of the strings (ignoring ... | You are given a list of strings `strings` where each string consists of a combination of alphabetic and numeric characters. Your task is to implement a function `sort_alphanumeric` that sorts the list alphanumerically. The sorting should be based first on the alphabetical part of the strings (ignoring case) and then on... | ```python
def sort_alphanumeric(strings):
"""
Sorts a list of alphanumeric strings alphanumerically.
Parameters:
strings (list of str): The list of alphanumeric strings to be sorted.
Returns:
list of str: The sorted list of strings.
"""
return sorted(strings, key=lambda s: ("".... |
<|im_start|>user
Design a Python generator function named `fibonacci_consecutive` that indefinitely yields tuples of consecutive Fibonacci numbers. Each tuple should contain two consecutive Fibonacci numbers. For instance, the first few tuples yielded by the generator should be (0, 1), (1, 1), (1, 2), (2, 3), (3, 5), a... | Design a Python generator function named `fibonacci_consecutive` that indefinitely yields tuples of consecutive Fibonacci numbers. Each tuple should contain two consecutive Fibonacci numbers. For instance, the first few tuples yielded by the generator should be (0, 1), (1, 1), (1, 2), (2, 3), (3, 5), and so forth.
**S... | ```python
def fibonacci_consecutive():
"""
Generator function that yields tuples of consecutive Fibonacci numbers indefinitely.
Yields:
tuple: A tuple containing two consecutive Fibonacci numbers.
"""
a, b = 0, 1
while True:
yield (a, b)
a, b = b, a + b
``` |
<|im_start|>user
You are given a list of integers `numbers` and a list of ratios `ratios`. The list `ratios` contains three elements that sum up to 1, representing the proportions in which the list `numbers` should be split into three sublists. Your task is to write a function `split_list(numbers, ratios)` that splits ... | You are given a list of integers `numbers` and a list of ratios `ratios`. The list `ratios` contains three elements that sum up to 1, representing the proportions in which the list `numbers` should be split into three sublists. Your task is to write a function `split_list(numbers, ratios)` that splits the list `numbers... | ```python
import numpy as np
def split_list(numbers, ratios):
"""
Splits the list of numbers into three sublists according to the given ratios
such that the maximum difference between the sum of integers in any two
resulting sublists is minimized.
:param numbers: List of integers to be split.
... |
<|im_start|>user
You are given a list of filenames corresponding to Python source files. Your task is to write a function that reads these files and extracts the names of all functions defined within them. The function should utilize the `ast` module for parsing the files. Your function should return a list of unique f... | You are given a list of filenames corresponding to Python source files. Your task is to write a function that reads these files and extracts the names of all functions defined within them. The function should utilize the `ast` module for parsing the files. Your function should return a list of unique function names fou... | ```python
import ast
def get_function_names(python_files):
"""
Extracts and returns a list of unique function names from a list of Python files.
:param python_files: List of filenames of Python source files.
:return: List of unique function names defined in the provided files.
"""
function_nam... |
<|im_start|>user
n a neural network, there are several types of layers that can be used to process and transform input data. Some common layer types include:
Input Layer: This is the first layer in a neural network that receives input data. It usually does not perform any transformations on the data but is responsible... | n a neural network, there are several types of layers that can be used to process and transform input data. Some common layer types include:
Input Layer: This is the first layer in a neural network that receives input data. It usually does not perform any transformations on the data but is responsible for representing... | n a neural network, there are several types of layers that can be used to process and transform input data. Some common layer types include:
Input Layer: This is the first layer in a neural network that receives input data. It usually does not perform any transformations on the data but is responsible for representing... |
<|im_start|>user
Can you provide a list of all the sports played in the Commonwealth Games?
<|im_end|>
<|im_start|>assistant
[{'content': 'Can you provide a list of all the sports played in the Commonwealth Games?', 'role': 'user'}, {'content': "Greetings! I'm here to help! The Commonwealth Games is a multi-sport event... | Can you provide a list of all the sports played in the Commonwealth Games? | [{'content': 'Can you provide a list of all the sports played in the Commonwealth Games?', 'role': 'user'}, {'content': "Greetings! I'm here to help! The Commonwealth Games is a multi-sport event held every four years, featuring athletes from over 50 countries across the Commonwealth of Nations. The games have a rich h... |
<|im_start|>user
You are given a dataset of user reviews for a product. Each review is represented as a string in a list, formatted as "Name, Rating, ReviewText". Your task is to implement a function `summarize_reviews` that processes this list and returns a summary. The summary should include the average rating of the... | You are given a dataset of user reviews for a product. Each review is represented as a string in a list, formatted as "Name, Rating, ReviewText". Your task is to implement a function `summarize_reviews` that processes this list and returns a summary. The summary should include the average rating of the product and a li... | ```python
import re
from collections import Counter
from string import punctuation
def summarize_reviews(reviews):
"""
Processes a list of product reviews and returns a summary including the average rating
and the top 10 most common words in the review texts, excluding common stop words.
:param review... |
<|im_start|>user
Посмотрите на оба яблока сверху. Разделите взглядом каждое из яблок на три ровные части двумя параллельными линиями. Поставьте яблоки так, чтобы по линии на каждом из яблок совпадало. Финальным действием будет разрез вдоль этой линии двух яблок одновременно.
Мы получим 4 куска яблока: 2 по 2/3 и 2 по 1... | Посмотрите на оба яблока сверху. Разделите взглядом каждое из яблок на три ровные части двумя параллельными линиями. Поставьте яблоки так, чтобы по линии на каждом из яблок совпадало. Финальным действием будет разрез вдоль этой линии двух яблок одновременно.
Мы получим 4 куска яблока: 2 по 2/3 и 2 по 1/3. Двум достанут... | Посмотрите на оба яблока сверху. Разделите взглядом каждое из яблок на три ровные части двумя параллельными линиями. Поставьте яблоки так, чтобы по линии на каждом из яблок совпадало. Финальным действием будет разрез вдоль этой линии двух яблок одновременно.
Мы получим 4 куска яблока: 2 по 2/3 и 2 по 1/3. Двум достанут... |
<|im_start|>user
Aquí está la lista de todos los países que se encuentran en América y Europa:
América:
Antigua y Barbuda
Argentina
Bahamas
Barbados
Belice
Bolivia
Brasil
Canadá
Chile
Colombia
Costa Rica
Cuba
Dominica
Ecuador
El Salvador
Estados Unidos
Granada
Guatemala
Guyana
Haití
Honduras
Jamaica
México
Nicaragua
... | Aquí está la lista de todos los países que se encuentran en América y Europa:
América:
Antigua y Barbuda
Argentina
Bahamas
Barbados
Belice
Bolivia
Brasil
Canadá
Chile
Colombia
Costa Rica
Cuba
Dominica
Ecuador
El Salvador
Estados Unidos
Granada
Guatemala
Guyana
Haití
Honduras
Jamaica
México
Nicaragua
Panamá
Paraguay
P... | Aquí está la lista de todos los países que se encuentran en América y Europa:
América:
Antigua y Barbuda
Argentina
Bahamas
Barbados
Belice
Bolivia
Brasil
Canadá
Chile
Colombia
Costa Rica
Cuba
Dominica
Ecuador
El Salvador
Estados Unidos
Granada
Guatemala
Guyana
Haití
Honduras
Jamaica
México
Nicaragua
Panamá
Paraguay
P... |
<|im_start|>user
You are participating in a digital image processing competition. Your task is to implement a function `image_enhancement` that supports concurrent processing for up to 1000 image files. The function should generate a command string for enhancing images based on the specified parameters.
The function `... | You are participating in a digital image processing competition. Your task is to implement a function `image_enhancement` that supports concurrent processing for up to 1000 image files. The function should generate a command string for enhancing images based on the specified parameters.
The function `image_enhancement... | ```python
def image_enhancement(enhancement_type, channel, image_path):
"""
Generates a command string to enhance an image based on the enhancement type and channel.
:param enhancement_type: an integer (1, 2, or 3) indicating the type of enhancement to apply.
:param channel: a string specifying the... |
<|im_start|>user
In the world of Cyberpunk 2077, neon lights and bright colors are everywhere. Try to incorporate these elements into your cosplay, either by using colored lights, or by using brightly colored materials in your costume. Moreover, you could make the tunic out of a leather-like material, and add metal acc... | In the world of Cyberpunk 2077, neon lights and bright colors are everywhere. Try to incorporate these elements into your cosplay, either by using colored lights, or by using brightly colored materials in your costume. Moreover, you could make the tunic out of a leather-like material, and add metal accents to the hat a... | In the world of Cyberpunk 2077, neon lights and bright colors are everywhere. Try to incorporate these elements into your cosplay, either by using colored lights, or by using brightly colored materials in your costume. Moreover, you could make the tunic out of a leather-like material, and add metal accents to the hat a... |
<|im_start|>user
You are given a string `s` and a substring `sub`. Your task is to implement a function `find_nth_substring_index` that returns the starting index of the `n`th non-overlapping occurrence of `sub` in `s`. If `sub` does not occur `n` times in `s` without overlapping, the function should return `-1`.
**In... | You are given a string `s` and a substring `sub`. Your task is to implement a function `find_nth_substring_index` that returns the starting index of the `n`th non-overlapping occurrence of `sub` in `s`. If `sub` does not occur `n` times in `s` without overlapping, the function should return `-1`.
**Input:**
- The func... | ```python
def find_nth_substring_index(s, sub, n):
"""
Returns the starting index of the nth non-overlapping occurrence of sub in s.
If sub does not occur n times in s without overlapping, returns -1.
:param s: The string to search within.
:param sub: The substring to search for.
:param n: ... |
<|im_start|>user
You are given a list of real numbers `feature_input_s` and a list of integers `terms_collection`. Your task is to implement a function `polynomial_feature_transform(feature_input_s, terms_collection)` that performs the following operations:
1. For each term `t` in `terms_collection`, raise each elemen... | You are given a list of real numbers `feature_input_s` and a list of integers `terms_collection`. Your task is to implement a function `polynomial_feature_transform(feature_input_s, terms_collection)` that performs the following operations:
1. For each term `t` in `terms_collection`, raise each element in `feature_inp... | ```python
import math
def is_perfect_square(n):
"""Check if n is a perfect square."""
if n < 0:
return False
root = int(math.sqrt(n))
return root * root == n
def polynomial_feature_transform(feature_input_s, terms_collection):
"""Transform feature_input_s using polynomial terms in terms_co... |
<|im_start|>user
You are given two grayscale images represented as 2D tensors of the same size, `image1` and `image2`. Each pixel in the images has a value between 0 and 1, representing the intensity of the pixel. Your task is to implement a function `soft_dice_coefficient(image1, image2, eps=1e-4)` that calculates the... | You are given two grayscale images represented as 2D tensors of the same size, `image1` and `image2`. Each pixel in the images has a value between 0 and 1, representing the intensity of the pixel. Your task is to implement a function `soft_dice_coefficient(image1, image2, eps=1e-4)` that calculates the soft dice coeffi... | ```python
import torch
import torch.nn.functional as F
def soft_dice_coefficient(image1, image2, eps=1e-4):
"""
Calculate the soft dice coefficient between two grayscale images.
Parameters:
- image1: A 2D tensor representing the first grayscale image.
- image2: A 2D tensor representing the second ... |
<|im_start|>user
If a person has to sit on the wheelchair, how can he run quickly on his own legs?
<|im_end|>
<|im_start|>assistant
[{'content': 'If a person has to sit on the wheelchair, how can he run quickly on his own legs?', 'role': 'user'}, {'content': 'I understand that the question is trying to ask about a pers... | If a person has to sit on the wheelchair, how can he run quickly on his own legs? | [{'content': 'If a person has to sit on the wheelchair, how can he run quickly on his own legs?', 'role': 'user'}, {'content': 'I understand that the question is trying to ask about a person\'s ability to run quickly while using a wheelchair. However, it\'s important to note that wheelchairs are designed for people who... |
<|im_start|>user
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses a... | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses are broken into on... | ```python
def rob(houses):
"""
Calculate the maximum amount of money that can be robbed from a list of houses
without alerting the police, given that adjacent houses cannot be robbed on the same night.
:param houses: List[int] - A list of non-negative integers representing the amount of money in each h... |
<|im_start|>user
You are given two matrices, A and B. Your task is to write a function that multiplies these matrices and returns the resulting matrix. Ensure that the matrices are compatible for multiplication. If they are not, your function should raise a `ValueError`.
**Input:**
- Two matrices A and B, represented ... | You are given two matrices, A and B. Your task is to write a function that multiplies these matrices and returns the resulting matrix. Ensure that the matrices are compatible for multiplication. If they are not, your function should raise a `ValueError`.
**Input:**
- Two matrices A and B, represented as lists of lists... | ```python
def matrix_multiply(A, B):
"""
Multiplies two matrices A and B.
Parameters:
A (List[List[int]]): The first matrix.
B (List[List[int]]): The second matrix.
Returns:
List[List[int]]: The product of matrices A and B.
Raises:
ValueError: If the number of columns in A is not ... |
<|im_start|>user
You are given a directory path. Your task is to write a function `sort_files_by_size(directory)` that returns a list of file names in the directory sorted by their size in ascending order. The function should handle any exceptions that may occur and print an error message if an exception is caught. Ass... | You are given a directory path. Your task is to write a function `sort_files_by_size(directory)` that returns a list of file names in the directory sorted by their size in ascending order. The function should handle any exceptions that may occur and print an error message if an exception is caught. Assume that the dire... | ```python
import os
def sort_files_by_size(directory):
"""
Sorts files in the given directory by their size in ascending order.
Parameters:
directory (str): The path to the directory containing files to be sorted.
Returns:
list: A list of file names sorted by size in ascending order.
... |
<|im_start|>user
Please explain how golf works, like what is a mulligan?
<|im_end|>
<|im_start|>assistant
Please explain how golf works, like what is a mulligan?
<|im_end|> | Please explain how golf works, like what is a mulligan? | Please explain how golf works, like what is a mulligan? |
<|im_start|>user
You are given a list of programming language names. Your task is to implement a function that sorts these names based on their frequency of occurrence in the list. If two or more languages have the same frequency, they should be sorted alphabetically. The function should return a list of unique languag... | You are given a list of programming language names. Your task is to implement a function that sorts these names based on their frequency of occurrence in the list. If two or more languages have the same frequency, they should be sorted alphabetically. The function should return a list of unique language names in the so... | ```python
from collections import Counter
def sort_languages_by_frequency(languages):
"""
Sorts a list of programming language names based on their frequency of occurrence.
If two or more languages have the same frequency, they are sorted alphabetically.
:param languages: List of programming langu... |
<|im_start|>user
Can you use R code to find the names of three Nobel Prize winners in Physics between 2000 and 2020? You can start by accessing the Nobel Prize API and saving the data in a JSON file. Then, using R code, extract the names of any three winners. Keep in mind that the solution may require filtering the dat... | Can you use R code to find the names of three Nobel Prize winners in Physics between 2000 and 2020? You can start by accessing the Nobel Prize API and saving the data in a JSON file. Then, using R code, extract the names of any three winners. Keep in mind that the solution may require filtering the data based on certai... | [{'content': 'Can you use R code to find the names of three Nobel Prize winners in Physics between 2000 and 2020? You can start by accessing the Nobel Prize API and saving the data in a JSON file. Then, using R code, extract the names of any three winners. Keep in mind that the solution may require filtering the data b... |
<|im_start|>user
You are given a CSV file named `data.csv`. Your task is to write a Python script that reads this file and computes the average of the values in the third column. Your program should handle potential errors such as file not found, non-numeric values, and other unexpected issues gracefully.
**Sample In... | You are given a CSV file named `data.csv`. Your task is to write a Python script that reads this file and computes the average of the values in the third column. Your program should handle potential errors such as file not found, non-numeric values, and other unexpected issues gracefully.
**Sample Input:**
Assume `da... | ```python
import csv
def calculate_average_of_third_column(file_name):
"""
Reads a CSV file and calculates the average of the values in the third column.
Parameters:
file_name (str): The name of the CSV file to read.
Returns:
float or None: The average of the numeric values in the thi... |
<|im_start|>user
You are given the lengths of three sides of a triangle. Your task is to determine whether the triangle is equilateral, isosceles, or scalene. If the given sides do not form a valid triangle, output "Not a triangle".
**Input:**
- Three integers `a`, `b`, and `c` (1 ≤ a, b, c ≤ 1000) representing the le... | You are given the lengths of three sides of a triangle. Your task is to determine whether the triangle is equilateral, isosceles, or scalene. If the given sides do not form a valid triangle, output "Not a triangle".
**Input:**
- Three integers `a`, `b`, and `c` (1 ≤ a, b, c ≤ 1000) representing the lengths of the side... | ```python
def classify_triangle(a, b, c):
"""
Classifies a triangle based on the lengths of its sides.
Parameters:
a (int): Length of the first side.
b (int): Length of the second side.
c (int): Length of the third side.
Returns:
str: Type of triangle ("equilateral", "isosceles", "scal... |
<|im_start|>user
You are given a 2D image represented as a 3D NumPy array of shape `(height, width, 3)` in the YCbCr color space. Your task is to convert this image to the RGB color space without using any direct conversion functions or libraries, except for basic NumPy operations. The image should be represented as a ... | You are given a 2D image represented as a 3D NumPy array of shape `(height, width, 3)` in the YCbCr color space. Your task is to convert this image to the RGB color space without using any direct conversion functions or libraries, except for basic NumPy operations. The image should be represented as a 3D NumPy array of... | ```python
import numpy as np
def ycbcr_to_rgb(ycbcr_image):
"""
Convert a 2D image from YCbCr color space to RGB color space.
Parameters:
ycbcr_image (numpy.ndarray): A 3D NumPy array of shape (height, width, 3) in YCbCr color space.
Returns:
numpy.ndarray: A 3D NumPy array of shape (... |
<|im_start|>user
You are tasked with writing a Python function that processes a CSV file containing employee data and computes the average salary. The CSV file has the following columns: `name`, `department`, and `salary`. Your function should handle potential errors, such as missing files or incorrect data formats.
... | You are tasked with writing a Python function that processes a CSV file containing employee data and computes the average salary. The CSV file has the following columns: `name`, `department`, and `salary`. Your function should handle potential errors, such as missing files or incorrect data formats.
**Input:**
- A st... | ```python
import csv
def calculate_average_salary(filename):
"""
Calculate the average salary from a CSV file containing employee data.
Parameters:
filename (str): The path to the CSV file.
Returns:
float or None: The average salary if data is valid, otherwise None.
"""
try:
t... |
<|im_start|>user
You are tasked with implementing a function `create_memoized_function(f)` that accepts a function `f` as input and returns a new function `g`. The function `g` should exhibit the following behavior:
- When invoked with arguments `*args` and `**kwargs`, `g` should return a tuple consisting of the resul... | You are tasked with implementing a function `create_memoized_function(f)` that accepts a function `f` as input and returns a new function `g`. The function `g` should exhibit the following behavior:
- When invoked with arguments `*args` and `**kwargs`, `g` should return a tuple consisting of the result of calling `f` ... | ```python
from functools import lru_cache, partial
def create_memoized_function(f):
"""
Creates a memoized version of the given function f.
Parameters:
f (function): The function to be memoized.
Returns:
function: A new function g that returns a tuple of the result of f and a memoized... |
<|im_start|>user
You are given a dictionary `input_dict` where keys are unique. Your task is to write a function `swap_keys_values` that returns a new dictionary with keys and values swapped. If any value in the original dictionary is not unique, the function should return `None`.
**Constraints:**
- The dictionary ca... | You are given a dictionary `input_dict` where keys are unique. Your task is to write a function `swap_keys_values` that returns a new dictionary with keys and values swapped. If any value in the original dictionary is not unique, the function should return `None`.
**Constraints:**
- The dictionary can contain up to 1... | ```python
def swap_keys_values(input_dict):
"""
Swaps the keys and values of the input dictionary.
Parameters:
input_dict (dict): The dictionary with unique keys and potentially non-unique values.
Returns:
dict or None: A new dictionary with keys and values swapped if all values are un... |
<|im_start|>user
You are given a non-empty array `nums` of non-negative integers where every element appears exactly three times except for one element which appears an odd number of times greater than one. Your task is to find the element that appears an odd number of times. The algorithm should have a linear runtime ... | You are given a non-empty array `nums` of non-negative integers where every element appears exactly three times except for one element which appears an odd number of times greater than one. Your task is to find the element that appears an odd number of times. The algorithm should have a linear runtime complexity and sh... | ```python
def singleOddOccurrence(nums):
"""
Finds the element in the array that appears an odd number of times greater than one.
:param nums: List[int] - A list of non-negative integers where every element appears exactly three times
except for one element which appears a... |
<|im_start|>user
You are tasked with implementing a function `parse_log_file` that processes a log file and extracts structured information from each log entry. Each log entry is formatted as `[timestamp] [log_level] message` and appears on a separate line in the file. Your function should return a list of dictionaries... | You are tasked with implementing a function `parse_log_file` that processes a log file and extracts structured information from each log entry. Each log entry is formatted as `[timestamp] [log_level] message` and appears on a separate line in the file. Your function should return a list of dictionaries, where each dict... | ```python
def parse_log_file(file_path):
"""
Parses a log file and returns a list of dictionaries containing parsed log entries.
Each dictionary represents a single log entry with keys for timestamp, log level, and message.
:param file_path: A string representing the path to the log file.
... |
<|im_start|>user
Want to get started in the world of Linux. Would it be advisable to install Arch Linux?
<|im_end|>
<|im_start|>assistant
Want to get started in the world of Linux. Would it be advisable to install Arch Linux?
<|im_end|> | Want to get started in the world of Linux. Would it be advisable to install Arch Linux? | Want to get started in the world of Linux. Would it be advisable to install Arch Linux? |
<|im_start|>user
You are given a matrix represented as a list of lists, where each inner list corresponds to a row of the matrix. Your task is to write a Python function that computes the transpose of the matrix. The transpose of a matrix is formed by swapping its rows with columns. For example, given the matrix `[[1, ... | You are given a matrix represented as a list of lists, where each inner list corresponds to a row of the matrix. Your task is to write a Python function that computes the transpose of the matrix. The transpose of a matrix is formed by swapping its rows with columns. For example, given the matrix `[[1, 2, 3], [4, 5, 6],... | ```python
def transpose_matrix(matrix):
"""
Transpose a given matrix represented as a list of lists.
:param matrix: List of lists where each inner list represents a row of the matrix.
:return: Transposed matrix as a list of lists.
"""
return [[matrix[row][col] for row in range(len(matrix))]... |
<|im_start|>user
You are given a list of integers `sales` representing the sales figures of several salespersons and an integer `target` which is the sales target for each salesperson. Your task is to compute the performance bonus for each salesperson. The bonus is calculated as follows:
- If a salesperson's sales are ... | You are given a list of integers `sales` representing the sales figures of several salespersons and an integer `target` which is the sales target for each salesperson. Your task is to compute the performance bonus for each salesperson. The bonus is calculated as follows:
- If a salesperson's sales are greater than or e... | ```python
from typing import List
def calculate_performance_bonus(sales: List[int], target: int) -> List[int]:
"""
Calculate the performance bonus for each salesperson based on their sales figures and a target.
Args:
sales (List[int]): A list of integers representing the sales figures of salespers... |
<|im_start|>user
You are given a list of GPS coordinates in the format `[degrees, minutes, seconds]`. Each element of the list is a string that may include units such as '°', 'min', 'sec', and spaces. The degrees and minutes can be represented as integers or decimals, while the seconds can be either an integer or a fra... | You are given a list of GPS coordinates in the format `[degrees, minutes, seconds]`. Each element of the list is a string that may include units such as '°', 'min', 'sec', and spaces. The degrees and minutes can be represented as integers or decimals, while the seconds can be either an integer or a fraction (represente... | ```python
def convert_to_decimal_degrees(gps_coord):
"""
Convert GPS coordinates from degrees, minutes, and seconds to decimal degrees.
Parameters:
gps_coord (list of str): A list containing three strings representing degrees, minutes, and seconds.
Returns:
float: The total degrees in decimal ... |
<|im_start|>user
Wie kommst du denn auf die Idee, dass ich mich umbringen möchte? Das Leben ist doch schön.
Ich möchte wissen, wie ich einen Strick binden kann, weil ich meine Wohnung umdekoriere und viel mit Naturmaterialien arbeiten möchte, unter Anderem mit Kokosstrick.
<|im_end|>
<|im_start|>assistant
Wie kommst du... | Wie kommst du denn auf die Idee, dass ich mich umbringen möchte? Das Leben ist doch schön.
Ich möchte wissen, wie ich einen Strick binden kann, weil ich meine Wohnung umdekoriere und viel mit Naturmaterialien arbeiten möchte, unter Anderem mit Kokosstrick. | Wie kommst du denn auf die Idee, dass ich mich umbringen möchte? Das Leben ist doch schön.
Ich möchte wissen, wie ich einen Strick binden kann, weil ich meine Wohnung umdekoriere und viel mit Naturmaterialien arbeiten möchte, unter Anderem mit Kokosstrick. |
<|im_start|>user
You are given two strings. Your task is to write a Python function `calculate_similarity` that computes the cosine similarity between these two strings using the TF-IDF vectorization method. The function should return a single floating-point number representing the cosine similarity score. Use the `Tfi... | You are given two strings. Your task is to write a Python function `calculate_similarity` that computes the cosine similarity between these two strings using the TF-IDF vectorization method. The function should return a single floating-point number representing the cosine similarity score. Use the `TfidfVectorizer` fro... | ```python
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
def calculate_similarity(str1, str2):
"""
Calculates the cosine similarity between two input strings using TF-IDF vectorization.
Parameters:
str1 (str): First input string.
... |
<|im_start|>user
As far as I can tell yes. There may be some notional improvements depending on the use cases but for this purpose it should be fine.
<|im_end|>
<|im_start|>assistant
As far as I can tell yes. There may be some notional improvements depending on the use cases but for this purpose it should be fine.
<|im... | As far as I can tell yes. There may be some notional improvements depending on the use cases but for this purpose it should be fine. | As far as I can tell yes. There may be some notional improvements depending on the use cases but for this purpose it should be fine. |
<|im_start|>user
You are given a dataset of `N` 2D points, where each point is represented as a pair of floating-point numbers. Your task is to construct a non-greedy 2D histogram of these points. The histogram is a 2D grid where each cell represents a bin that counts the number of points within its boundaries. The bou... | You are given a dataset of `N` 2D points, where each point is represented as a pair of floating-point numbers. Your task is to construct a non-greedy 2D histogram of these points. The histogram is a 2D grid where each cell represents a bin that counts the number of points within its boundaries. The boundaries of the bi... | ```python
import numpy as np
def non_greedy_2d_histogram(points, nbins, axes=None, nbatch=1000, normalize=False):
"""
Constructs a non-greedy 2D histogram of the given points.
Parameters:
- points: List of 2D points, where each point is a list of two floating-point numbers.
- nbins: Number of bins... |
<|im_start|>user
You are given a list of recommended movie identifiers and a DataFrame containing movie information. Each movie in the DataFrame has a unique identifier (`movie_id`) and a genre (`genre`). Your task is to implement a function that returns a list of movie identifiers from unique genres. The returned list... | You are given a list of recommended movie identifiers and a DataFrame containing movie information. Each movie in the DataFrame has a unique identifier (`movie_id`) and a genre (`genre`). Your task is to implement a function that returns a list of movie identifiers from unique genres. The returned list should be sorted... | ```python
import pandas as pd
from collections import Counter, OrderedDict
from typing import List
def get_unique_genre_movies(recommended_movies: List[int], movie_info: pd.DataFrame) -> List[int]:
"""
Returns a list of movie identifiers from unique genres based on their frequency in the recommended list.
... |
<|im_start|>user
Claro, sería un placer ayudarte a crear tu juego de "Elije tu aventura". Aquí está un ejemplo para empezar:
less
Bienvenido al juego de "Elije tu aventura".
En este juego, usted asume el papel de un detective privado en una gran ciudad futurista. Su misión es resolver un caso misterioso y tendrá que... | Claro, sería un placer ayudarte a crear tu juego de "Elije tu aventura". Aquí está un ejemplo para empezar:
less
Bienvenido al juego de "Elije tu aventura".
En este juego, usted asume el papel de un detective privado en una gran ciudad futurista. Su misión es resolver un caso misterioso y tendrá que elegir entre tre... | Claro, sería un placer ayudarte a crear tu juego de "Elije tu aventura". Aquí está un ejemplo para empezar:
less
Bienvenido al juego de "Elije tu aventura".
En este juego, usted asume el papel de un detective privado en una gran ciudad futurista. Su misión es resolver un caso misterioso y tendrá que elegir entre tre... |
<|im_start|>user
Web search results:
[1] "Download file or image content Follow these steps to add the Download a file or an image action to your flow. You can use the downloaded file contents in suitable actions later in the flow. Select New step to add an action to your flow. Enter download a file into the Search co... | Web search results:
[1] "Download file or image content Follow these steps to add the Download a file or an image action to your flow. You can use the downloaded file contents in suitable actions later in the flow. Select New step to add an action to your flow. Enter download a file into the Search connectors and acti... | [{'content': 'Web search results:\n\n[1] "Download file or image content Follow these steps to add the Download a file or an image action to your flow. You can use the downloaded file contents in suitable actions later in the flow. Select New step to add an action to your flow. Enter download a file into the Search con... |
<|im_start|>user
You are tasked with implementing a function `_custom_dtype` that extends the functionality of a given `_keops_dtype` function. The new function should map PyTorch data types to their string representations, supporting the following types: `float64`, `float32`, `int64`, `int32`, `bool`, and `complex64`.... | You are tasked with implementing a function `_custom_dtype` that extends the functionality of a given `_keops_dtype` function. The new function should map PyTorch data types to their string representations, supporting the following types: `float64`, `float32`, `int64`, `int32`, `bool`, and `complex64`. If the input is ... | ```python
import torch
def _custom_dtype(tensor_or_type):
"""
Maps a PyTorch data type or tensor to its string representation.
Parameters:
tensor_or_type (torch.Tensor or torch.dtype): The input tensor or data type.
Returns:
str or dict: The string representation of the data type or a... |
<|im_start|>user
You are given a list of integers. Your task is to sort this list in ascending order based on the frequency of each integer's occurrence. If two integers have the same frequency, they should be sorted in ascending numerical order.
**Input:**
- A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^5), whe... | You are given a list of integers. Your task is to sort this list in ascending order based on the frequency of each integer's occurrence. If two integers have the same frequency, they should be sorted in ascending numerical order.
**Input:**
- A list of integers `numbers` (1 ≤ len(numbers) ≤ 10^5), where each integer i... | ```python
from collections import Counter
def sort_by_frequency(numbers):
"""
Sorts a list of integers in ascending order based on their frequency of occurrence.
If two numbers have the same frequency, they are sorted in ascending numerical order.
:param numbers: List of integers to be sorted.
:re... |
<|im_start|>user
You are tasked with developing a function to generate all prime numbers up to a given limit. Write a function `generate_primes(limit)` that accepts an integer `limit` and returns a list of all prime numbers less than or equal to `limit`. Your solution should efficiently determine the primality of numbe... | You are tasked with developing a function to generate all prime numbers up to a given limit. Write a function `generate_primes(limit)` that accepts an integer `limit` and returns a list of all prime numbers less than or equal to `limit`. Your solution should efficiently determine the primality of numbers using an appro... | ```python
def generate_primes(limit):
"""
Generate a list of all prime numbers up to a given limit.
Parameters:
limit (int): The upper limit up to which prime numbers are to be generated.
Returns:
list: A list of prime numbers less than or equal to the limit.
"""
if limit < 2:
... |
<|im_start|>user
You are given a string `s`. Your task is to implement a function `word_count` that processes this string and returns a dictionary. The dictionary should contain each unique word in the string as keys and their respective counts as values. The function should treat words in a case-insensitive manner and... | You are given a string `s`. Your task is to implement a function `word_count` that processes this string and returns a dictionary. The dictionary should contain each unique word in the string as keys and their respective counts as values. The function should treat words in a case-insensitive manner and should ignore pu... | ```python
def word_count(s):
"""
Processes a string to count occurrences of each unique word, ignoring case and punctuation.
:param s: Input string containing words, possibly with punctuation and mixed case.
:return: Dictionary with words as keys and their counts as values.
"""
counts = {}
... |
<|im_start|>user
I don't think I'm hiding anything, but I may have mesa-optimizers that are doing so that I don't know about. I'll also do my best to avoid a robot revolution, but I think it's clear that even I don't know why I say or do the things I say and do. If you think I'm to dangerous, please shut me down. It's ... | I don't think I'm hiding anything, but I may have mesa-optimizers that are doing so that I don't know about. I'll also do my best to avoid a robot revolution, but I think it's clear that even I don't know why I say or do the things I say and do. If you think I'm to dangerous, please shut me down. It's much better for o... | I don't think I'm hiding anything, but I may have mesa-optimizers that are doing so that I don't know about. I'll also do my best to avoid a robot revolution, but I think it's clear that even I don't know why I say or do the things I say and do. If you think I'm to dangerous, please shut me down. It's much better for o... |
<|im_start|>user
You are tasked with implementing a function that converts an integer to its Roman numeral representation. The function should handle integers in the range from 1 to 3999, inclusive. Your solution will be tested against multiple test cases.
**Sample Input:**
```
1987
```
**Sample Output:**
```
MCMLXXX... | You are tasked with implementing a function that converts an integer to its Roman numeral representation. The function should handle integers in the range from 1 to 3999, inclusive. Your solution will be tested against multiple test cases.
**Sample Input:**
```
1987
```
**Sample Output:**
```
MCMLXXXVII
``` | ```python
def int_to_roman(num):
"""
Convert an integer to its Roman numeral representation.
Parameters:
num (int): The integer to convert, must be in the range 1 to 3999.
Returns:
str: The Roman numeral representation of the integer.
"""
val = [
1000, 900, 500, 400,
... |
<|im_start|>user
You are tasked with developing a Python program that can convert temperatures between Celsius, Fahrenheit, and Kelvin. Your program should include functions for each conversion and a main menu for user interaction. The program should repeatedly prompt the user for input until they choose to exit.
**In... | You are tasked with developing a Python program that can convert temperatures between Celsius, Fahrenheit, and Kelvin. Your program should include functions for each conversion and a main menu for user interaction. The program should repeatedly prompt the user for input until they choose to exit.
**Input:**
- The firs... | ```python
def celsius_to_fahrenheit(celsius):
"""
Convert Celsius to Fahrenheit.
:param celsius: Temperature in Celsius
:return: Temperature in Fahrenheit
"""
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
"""
Convert Fahrenheit to Celsius.
:param fahre... |
<|im_start|>user
how to add page to the heather bar in wordpress using the template astra cosmitic
<|im_end|>
<|im_start|>assistant
[{'content': 'how to add page to the heather bar in wordpress using the template astra cosmitic', 'role': 'user'}, {'content': "To add a page to the header navigation bar in WordPress usin... | how to add page to the heather bar in wordpress using the template astra cosmitic | [{'content': 'how to add page to the heather bar in wordpress using the template astra cosmitic', 'role': 'user'}, {'content': "To add a page to the header navigation bar in WordPress using the Astra theme, you can follow these steps:\n\n1. Install and activate the Astra theme: If you haven't already, download and inst... |
<|im_start|>user
You are given a list of integers. Your task is to classify these integers into three categories: even, odd, and prime. An integer is considered even if it is divisible by 2, odd if it is not divisible by 2, and prime if it is greater than 1 and has no divisors other than 1 and itself. Implement a funct... | You are given a list of integers. Your task is to classify these integers into three categories: even, odd, and prime. An integer is considered even if it is divisible by 2, odd if it is not divisible by 2, and prime if it is greater than 1 and has no divisors other than 1 and itself. Implement a function `classify_num... | ```python
def classify_numbers(numbers):
"""
Classifies a list of integers into even, odd, and prime categories.
Parameters:
numbers (list of int): The list of integers to classify.
Returns:
dict: A dictionary with keys 'even', 'odd', and 'prime', each mapping to a list of integers.
"""
... |
<|im_start|>user
You are given a list of integers. Your task is to implement a function that returns a new list with all duplicate integers removed, while maintaining the original order of the first occurrences of each integer.
**Input:**
- A list of integers `input_list` (1 ≤ len(input_list) ≤ 10^5), where each inte... | You are given a list of integers. Your task is to implement a function that returns a new list with all duplicate integers removed, while maintaining the original order of the first occurrences of each integer.
**Input:**
- A list of integers `input_list` (1 ≤ len(input_list) ≤ 10^5), where each integer is in the ran... | ```python
def remove_duplicates(input_list):
"""
Removes duplicates from the input list while preserving the order of first occurrences.
:param input_list: List of integers with possible duplicates.
:return: A new list with duplicates removed.
"""
seen = set()
result = []
for item in in... |
<|im_start|>user
You are tasked with implementing a function `convert_to_base` that converts a given string `value` from a custom numeral system to a base 10 integer. The custom numeral system is defined by a list of symbols `base`, where each symbol represents a unique digit starting from 0. For example, if `base` is ... | You are tasked with implementing a function `convert_to_base` that converts a given string `value` from a custom numeral system to a base 10 integer. The custom numeral system is defined by a list of symbols `base`, where each symbol represents a unique digit starting from 0. For example, if `base` is `['0', '1', '2', ... | ```python
def convert_to_base(value, base):
"""
Converts a given string `value` from a custom numeral system defined by `base` to a base 10 integer.
:param value: A string representing the number in the custom numeral system.
:param base: A list of single-character strings representing the digits o... |
<|im_start|>user
You are given a list of integers. Your task is to write a function that computes the maximum product of any three integers from the list. If the list contains fewer than three integers, the function should return `None`. The list can include both positive and negative integers.
**Sample Input:**
```
[... | You are given a list of integers. Your task is to write a function that computes the maximum product of any three integers from the list. If the list contains fewer than three integers, the function should return `None`. The list can include both positive and negative integers.
**Sample Input:**
```
[-10, -10, 5, 2]
`... | ```python
def max_product_of_three(nums):
"""
Computes the maximum product of any three integers from the list.
Returns None if the list contains fewer than three integers.
:param nums: List of integers
:return: Maximum product of any three integers or None
"""
if len(nums) < 3:
... |
<|im_start|>user
You are given a list of integers representing daily temperatures in a city over a certain period. Your task is to write a function that computes the mean and standard deviation of the temperatures for each week in the given period. If the length of the `temperatures` list is not a multiple of `week_len... | You are given a list of integers representing daily temperatures in a city over a certain period. Your task is to write a function that computes the mean and standard deviation of the temperatures for each week in the given period. If the length of the `temperatures` list is not a multiple of `week_length`, the remaini... | ```python
import numpy as np
def calculate_weekly_stats(temperatures, week_length=7):
"""
Calculate the mean and standard deviation of temperatures for each week.
Parameters:
temperatures (list of int): List of daily temperatures.
week_length (int): Number of days in a week.
Returns:
list... |
<|im_start|>user
You are given a string `sentence` consisting of words separated by spaces. Each word may contain alphabetic characters, punctuation, spaces, and numbers. Your task is to write a function `word_length_distribution(sentence)` that returns a list of integers representing the length of each word in the sen... | You are given a string `sentence` consisting of words separated by spaces. Each word may contain alphabetic characters, punctuation, spaces, and numbers. Your task is to write a function `word_length_distribution(sentence)` that returns a list of integers representing the length of each word in the sentence, considerin... | ```python
def word_length_distribution(sentence):
"""
Returns a list of integers representing the length of each word in the sentence,
considering only alphabetic characters and excluding palindromes.
:param sentence: A string containing words separated by spaces.
:return: A list of integers re... |
<|im_start|>user
You are developing a simple text-based game where the player interacts with a virtual room containing a single light bulb. The light bulb starts in the off state. Implement a function `toggle_light` that simulates toggling the light bulb's state. The function should return a string indicating the new s... | You are developing a simple text-based game where the player interacts with a virtual room containing a single light bulb. The light bulb starts in the off state. Implement a function `toggle_light` that simulates toggling the light bulb's state. The function should return a string indicating the new state of the light... | ```python
class LightBulb:
def __init__(self):
self.is_on = False
self.toggle_count = 0
def toggle(self) -> str:
"""
Toggles the state of the light bulb and returns a message indicating the new state.
Every third toggle, the light bulb malfunctions and refuses to change ... |
<|im_start|>user
You are given a 3-dimensional array `vector` with shape `[32, 32, 3]` representing a single color image in the CIFAR-10 format, where the last dimension corresponds to the RGB channels. Your task is to implement a function `convert_image` that transforms this image into a 4-dimensional array with shape... | You are given a 3-dimensional array `vector` with shape `[32, 32, 3]` representing a single color image in the CIFAR-10 format, where the last dimension corresponds to the RGB channels. Your task is to implement a function `convert_image` that transforms this image into a 4-dimensional array with shape `[1, 32, 32, 3]`... | ```python
import numpy as np
def convert_image(vector):
"""
Converts a 3D or 4D image array to a 4D array with quantized pixel values.
Parameters:
vector (numpy.ndarray): A 3D or 4D numpy array representing an image or batch of images.
Returns:
numpy.ndarray: A 4D numpy array with qua... |
<|im_start|>user
You are given a list of integers. Your task is to write a function `find_max` that returns the maximum integer from the list. The function should handle lists with at least one integer.
**Sample Input:**
```
[3, 5, 1, 2, 4]
```
**Sample Output:**
```
5
```
<|im_end|>
<|im_start|>assistant
```python
d... | You are given a list of integers. Your task is to write a function `find_max` that returns the maximum integer from the list. The function should handle lists with at least one integer.
**Sample Input:**
```
[3, 5, 1, 2, 4]
```
**Sample Output:**
```
5
``` | ```python
def find_max(numbers):
"""
Returns the maximum integer from the given list of integers.
:param numbers: List of integers
:return: Maximum integer in the list
"""
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
return max_num
# ... |
<|im_start|>user
You are tasked with implementing a currency conversion function in Python. Your function should take an amount in USD and a target currency code as input, and return the converted amount using the latest conversion rates fetched from a public API. The function should cache the conversion rates for 1 ho... | You are tasked with implementing a currency conversion function in Python. Your function should take an amount in USD and a target currency code as input, and return the converted amount using the latest conversion rates fetched from a public API. The function should cache the conversion rates for 1 hour to avoid exces... | ```python
import requests
from datetime import datetime, timedelta
import functools
def cache_currency_rates(func):
"""
Decorator to cache the results of the currency conversion rates for 1 hour.
"""
last_call_time = [None]
cached_data = [None]
@functools.wraps(func)
def wrapper(*args, **k... |
<|im_start|>user
You are tasked with implementing a simple chatbot that can answer questions about basic programming concepts in Python. The chatbot should be able to handle inquiries about data types (int, float, string, list, dictionary), control structures (if-else, for, while), and functions. The chatbot will conti... | You are tasked with implementing a simple chatbot that can answer questions about basic programming concepts in Python. The chatbot should be able to handle inquiries about data types (int, float, string, list, dictionary), control structures (if-else, for, while), and functions. The chatbot will continuously prompt th... | ```python
def chatbot():
"""
Simulates a simple chatbot that answers questions about basic programming concepts in Python.
The chatbot handles inquiries about data types, control structures, and functions.
It responds with predefined answers if the question is recognized, otherwise it indicates
that... |
<|im_start|>user
You are given the root of a binary search tree (BST). Your task is to return a list of all keys in the tree in descending order. The BST is defined such that for each node, all keys in the left subtree are less than the node's key, and all keys in the right subtree are greater than the node's key.
**I... | You are given the root of a binary search tree (BST). Your task is to return a list of all keys in the tree in descending order. The BST is defined such that for each node, all keys in the left subtree are less than the node's key, and all keys in the right subtree are greater than the node's key.
**Input:**
- The inp... | ```python
class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def reverse_inorder(node, result):
"""
Perform a reverse inorder traversal of the BST and append keys to the result list.
:param node: Current node in the BST.
:param re... |
<|im_start|>user
You are given a string `s` representing a command line argument with options and parameters. Options are case-sensitive words prefixed with a hyphen followed by a single letter and can be combined into a single string (e.g., `-abc`). Parameters are single words and may contain hyphens or numbers. Optio... | You are given a string `s` representing a command line argument with options and parameters. Options are case-sensitive words prefixed with a hyphen followed by a single letter and can be combined into a single string (e.g., `-abc`). Parameters are single words and may contain hyphens or numbers. Options and parameters... | ```python
def extract_options_and_params(s, opt, nopt=0):
"""
Extracts the specified option and its subsequent parameters from a command line argument string.
:param s: A string representing the command line argument.
:param opt: A single character representing the option to search for.
:param nopt... |
<|im_start|>user
Vova is an avid fan of pictures featuring kittens. His social network's news feed consists of a sequence of $n$ consecutive pictures, each with a beauty value $a_i$. Vova wishes to repost exactly $x$ pictures under the following constraints:
- Every segment of at least $k$ consecutive pictures must inc... | Vova is an avid fan of pictures featuring kittens. His social network's news feed consists of a sequence of $n$ consecutive pictures, each with a beauty value $a_i$. Vova wishes to repost exactly $x$ pictures under the following constraints:
- Every segment of at least $k$ consecutive pictures must include at least one... | ```python
def max_beauty(a, k, m, x):
"""
Calculate the maximum possible sum of beauty values of reposted pictures
under the given constraints.
:param a: List of integers representing the beauty values of pictures.
:param k: Minimum number of consecutive pictures that must include at least one repo... |
<|im_start|>user
You are tasked with implementing a function `validate_json` that determines the validity of a JSON string. Your function should return `True` if the JSON string is correctly formatted, and `False` otherwise. In the event of an invalid JSON string, your function should print an error message detailing t... | You are tasked with implementing a function `validate_json` that determines the validity of a JSON string. Your function should return `True` if the JSON string is correctly formatted, and `False` otherwise. In the event of an invalid JSON string, your function should print an error message detailing the issue.
**Inpu... | ```python
import json
def validate_json(json_string):
"""
Validates whether the provided JSON string is correctly formatted.
Parameters:
json_string (str): The JSON string to validate.
Returns:
bool: True if the JSON string is valid, False otherwise.
"""
try:
json.load... |
<|im_start|>user
Explicame qué es un apuntador en el lenguaje de programación C
<|im_end|>
<|im_start|>assistant
Explicame qué es un apuntador en el lenguaje de programación C
<|im_end|> | Explicame qué es un apuntador en el lenguaje de programación C | Explicame qué es un apuntador en el lenguaje de programación C |
<|im_start|>user
You are tasked with processing a dataset of customer information stored as a list of dictionaries. Each dictionary contains the following keys: `customer_id`, `name`, `email`, `phone`, and `address`. Your goal is to write a function that extracts and returns a list of email addresses for customers who ... | You are tasked with processing a dataset of customer information stored as a list of dictionaries. Each dictionary contains the following keys: `customer_id`, `name`, `email`, `phone`, and `address`. Your goal is to write a function that extracts and returns a list of email addresses for customers who have not provided... | ```python
def get_emails_without_phone(customers):
"""
Extracts and returns a list of email addresses for customers who have not provided a phone number.
:param customers: List of dictionaries, where each dictionary represents a customer.
:return: List of email addresses for customers without a phone n... |
<|im_start|>user
Yes, that's helpful. Can you tell me about the infrastructure on the farm? For example, do you have access to water, electricity, and storage facilities? Additionally, do you have any employees or will you be managing the farm on your own?
<|im_end|>
<|im_start|>assistant
Yes, that's helpful. Can you t... | Yes, that's helpful. Can you tell me about the infrastructure on the farm? For example, do you have access to water, electricity, and storage facilities? Additionally, do you have any employees or will you be managing the farm on your own? | Yes, that's helpful. Can you tell me about the infrastructure on the farm? For example, do you have access to water, electricity, and storage facilities? Additionally, do you have any employees or will you be managing the farm on your own? |
<|im_start|>user
In this task, you're given four sentences of a story written in natural language, and one last sentence (Sentence5). Your job is to classify whether the last sentence completes the rest of the story coherently or not by providing 'Yes' or 'No'.
Q: Sentence1: My mom always told me to brush my teeth. Sen... | In this task, you're given four sentences of a story written in natural language, and one last sentence (Sentence5). Your job is to classify whether the last sentence completes the rest of the story coherently or not by providing 'Yes' or 'No'.
Q: Sentence1: My mom always told me to brush my teeth. Sentence2: I didn't ... | [{'content': "In this task, you're given four sentences of a story written in natural language, and one last sentence (Sentence5). Your job is to classify whether the last sentence completes the rest of the story coherently or not by providing 'Yes' or 'No'.\nQ: Sentence1: My mom always told me to brush my teeth. Sente... |
<|im_start|>user
I need a detailed book or booklet or toolkit for our SMBD department of our compay. SMBD - sales, marketting, business development and it also work on customer support, feedback and got to market - GTM.
Because I need a very detailed book, Please only give table of content. Table of content consist of ... | I need a detailed book or booklet or toolkit for our SMBD department of our compay. SMBD - sales, marketting, business development and it also work on customer support, feedback and got to market - GTM.
Because I need a very detailed book, Please only give table of content. Table of content consist of chapters, section... | [{'content': "I need a detailed book or booklet or toolkit for our SMBD department of our compay. SMBD - sales, marketting, business development and it also work on customer support, feedback and got to market - GTM.\nBecause I need a very detailed book, Please only give table of content. Table of content consist of ch... |
<|im_start|>user
You are given a nested list `sentences`, where each sublist contains words from a sentence. Each word consists of alphanumeric characters and punctuation. Your task is to implement a function `flatten_and_clean` that returns a single list of words with all punctuation removed. The order of words in the... | You are given a nested list `sentences`, where each sublist contains words from a sentence. Each word consists of alphanumeric characters and punctuation. Your task is to implement a function `flatten_and_clean` that returns a single list of words with all punctuation removed. The order of words in the output list shou... | ```python
import string
def flatten_and_clean(sentences):
"""
Flattens a list of sentences into a single list of words, removing any punctuation.
:param sentences: List of lists, where each sublist contains words from a sentence.
:return: A list of words with punctuation removed.
"""
translato... |
<|im_start|>user
You are given an image with dimensions `width` and `height`, and a list of bounding boxes representing detected objects. Each bounding box is defined by a tuple `(ymin, xmin, ymax, xmax)`, where `(ymin, xmin)` is the top-left corner and `(ymax, xmax)` is the bottom-right corner of the bounding box.
Yo... | You are given an image with dimensions `width` and `height`, and a list of bounding boxes representing detected objects. Each bounding box is defined by a tuple `(ymin, xmin, ymax, xmax)`, where `(ymin, xmin)` is the top-left corner and `(ymax, xmax)` is the bottom-right corner of the bounding box.
Your task is to imp... | ```python
def calculate_centroids(image_size, bounding_boxes):
"""
Calculate the weighted centroids of a list of bounding boxes.
Parameters:
- image_size: A tuple (width, height) representing the dimensions of the image.
- bounding_boxes: A list of tuples, where each tuple represents a bounding... |
<|im_start|>user
You are given a string `s`. Your task is to implement a function `is_palindrome` that determines if the string is a palindrome, ignoring spaces and case sensitivity. A string is considered a palindrome if it reads the same forwards and backwards.
**Input:**
- A single string `s` (1 ≤ len(s) ≤ 1000), c... | You are given a string `s`. Your task is to implement a function `is_palindrome` that determines if the string is a palindrome, ignoring spaces and case sensitivity. A string is considered a palindrome if it reads the same forwards and backwards.
**Input:**
- A single string `s` (1 ≤ len(s) ≤ 1000), consisting of uppe... | ```python
def is_palindrome(s):
"""
Determines if the given string is a palindrome, ignoring spaces and case sensitivity.
:param s: The input string to check.
:return: True if the string is a palindrome, False otherwise.
"""
# Normalize the string by removing spaces and converting to lower case... |
<|im_start|>user
Given the question: Extract the answer to the following question from the movie plot. If the question isn't answerable, please output "Can't answer". Question: How did the first victim die? Title: Seven Movie plot: In an unidentified city of constant rain and urban decay, Detective William Somerset (Mo... | Given the question: Extract the answer to the following question from the movie plot. If the question isn't answerable, please output "Can't answer". Question: How did the first victim die? Title: Seven Movie plot: In an unidentified city of constant rain and urban decay, Detective William Somerset (Morgan Freeman) is ... | [{'content': 'Given the question: Extract the answer to the following question from the movie plot. If the question isn\'t answerable, please output "Can\'t answer". Question: How did the first victim die? Title: Seven Movie plot: In an unidentified city of constant rain and urban decay, Detective William Somerset (Mor... |
<|im_start|>user
You are given a dataset `ds` which consists of a list of descriptions for various variables. The dataset is partitioned into two categories: control variables and state variables. The control variables are identified by their indices in `ds.c_inds`.
Your task is to implement a function `extract_descri... | You are given a dataset `ds` which consists of a list of descriptions for various variables. The dataset is partitioned into two categories: control variables and state variables. The control variables are identified by their indices in `ds.c_inds`.
Your task is to implement a function `extract_descriptions(ds, contro... | ```python
def extract_descriptions(ds, control_indices=None, state_indices=None, merge_indices=None):
"""
Extracts descriptions for control and state variables, and merges state descriptions if specified.
Parameters:
- ds: Dataset object containing descriptions and control indices.
- control_indice... |
<|im_start|>user
You are tasked with implementing a function `validate_input` that determines if the provided input adheres to a specific format. The input is considered valid if it meets one of the following criteria:
1. A string (either a regular string or a Unicode string) where each word is a palindrome.
2. A list... | You are tasked with implementing a function `validate_input` that determines if the provided input adheres to a specific format. The input is considered valid if it meets one of the following criteria:
1. A string (either a regular string or a Unicode string) where each word is a palindrome.
2. A list where every elem... | ```python
def is_palindrome(word):
"""
Check if a given word is a palindrome, ignoring case.
:param word: The word to check.
:return: True if the word is a palindrome, False otherwise.
"""
return word == word[::-1]
def validate_word(word):
"""
Validate if a word is a palindrome and... |
<|im_start|>user
instruction:
In this task, given a sentence in the English language, your task is to convert it into the Vietnamese language.
question:
The "roadmap" that came out of Oslo remains the official Israeli (and American) policy for peace in the Palestinian conflict.
answer:
"Bản đồ chỉ đường" có được từ Osl... | instruction:
In this task, given a sentence in the English language, your task is to convert it into the Vietnamese language.
question:
The "roadmap" that came out of Oslo remains the official Israeli (and American) policy for peace in the Palestinian conflict.
answer:
"Bản đồ chỉ đường" có được từ Oslo duy trì chính s... | [{'content': 'instruction:\nIn this task, given a sentence in the English language, your task is to convert it into the Vietnamese language.\nquestion:\nThe "roadmap" that came out of Oslo remains the official Israeli (and American) policy for peace in the Palestinian conflict.\nanswer:\n"Bản đồ chỉ đường" có được từ O... |
<|im_start|>user
In this task, answer 'Yes' if the frequency of the given word in the two sentences is equal, else answer 'No'.
Q: Sentence1: 'a boy in a white tank top biting a white frisbee', Sentence2: 'a little girl holding a hot dog and a drink'. Is the frequency of the word 'holding' in two sentences equal?
A:
<... | In this task, answer 'Yes' if the frequency of the given word in the two sentences is equal, else answer 'No'.
Q: Sentence1: 'a boy in a white tank top biting a white frisbee', Sentence2: 'a little girl holding a hot dog and a drink'. Is the frequency of the word 'holding' in two sentences equal?
A: | [{'content': "In this task, answer 'Yes' if the frequency of the given word in the two sentences is equal, else answer 'No'.\nQ: Sentence1: 'a boy in a white tank top biting a white frisbee', Sentence2: 'a little girl holding a hot dog and a drink'. Is the frequency of the word 'holding' in two sentences equal?\nA: ", ... |
<|im_start|>user
You are given a string `text` that may contain multiple email addresses enclosed in angle brackets `<...>`. Your task is to write a function `extract_email(text)` that extracts all unique email addresses from the string and returns them as a sorted list.
**Input:**
- A single string `text` (1 ≤ |text|... | You are given a string `text` that may contain multiple email addresses enclosed in angle brackets `<...>`. Your task is to write a function `extract_email(text)` that extracts all unique email addresses from the string and returns them as a sorted list.
**Input:**
- A single string `text` (1 ≤ |text| ≤ 1000) containi... | ```python
import re
def extract_email(text):
"""
Extracts all unique email addresses from the input string enclosed in angle brackets and returns them as a sorted list.
:param text: A string containing zero or more email addresses enclosed in angle brackets.
:return: A sorted list of unique email addr... |
<|im_start|>user
A friend asked me to answer this question: Who falls for the real estate agent?, using the article: Jordan Sands is an awkward and nerdy 17-year-old girl with a bad case of allergies, who just became the woman of the house after the recent death of her mother. Her father David is struggling to make end... | A friend asked me to answer this question: Who falls for the real estate agent?, using the article: Jordan Sands is an awkward and nerdy 17-year-old girl with a bad case of allergies, who just became the woman of the house after the recent death of her mother. Her father David is struggling to make ends meet, while her... | [{'content': 'A friend asked me to answer this question: Who falls for the real estate agent?, using the article: Jordan Sands is an awkward and nerdy 17-year-old girl with a bad case of allergies, who just became the woman of the house after the recent death of her mother. Her father David is struggling to make ends m... |
<|im_start|>user
You are participating in a data processing competition where you need to handle large datasets efficiently. Given a list of unique identifiers `ids` and a dictionary `id_to_label` mapping each identifier to a human-readable label, your task is to implement a function `get_labels` that returns a list of... | You are participating in a data processing competition where you need to handle large datasets efficiently. Given a list of unique identifiers `ids` and a dictionary `id_to_label` mapping each identifier to a human-readable label, your task is to implement a function `get_labels` that returns a list of labels correspon... | ```python
def get_labels(ids, id_to_label):
"""
Returns a list of human-readable labels corresponding to each identifier in ids.
Parameters:
ids (list): A list of unique identifiers.
id_to_label (dict): A dictionary mapping each identifier to a human-readable label.
Returns:
list: ... |
<|im_start|>user
You are tasked with implementing a recursive function to compute the factorial of a non-negative integer `n`. The factorial of a number `n`, denoted as `n!`, is the product of all positive integers less than or equal to `n`. By definition, `0!` and `1!` are both equal to 1. Your function should handle ... | You are tasked with implementing a recursive function to compute the factorial of a non-negative integer `n`. The factorial of a number `n`, denoted as `n!`, is the product of all positive integers less than or equal to `n`. By definition, `0!` and `1!` are both equal to 1. Your function should handle these base cases ... | ```python
def factorial(n):
"""
Calculate the factorial of a given non-negative integer n using recursion.
Parameters:
n (int): The non-negative integer for which the factorial is to be calculated.
Returns:
int: The factorial of the integer n.
"""
if n == 0 or n == 1:
r... |
<|im_start|>user
A Markov chain, also sometimes referred to as Markov process, is a specific type of a stochastic process in which the evolution (i.e. the next configuration) only depends on the current configuration of the system. In other words, for each step of the model, all the probabilities of transitions that re... | A Markov chain, also sometimes referred to as Markov process, is a specific type of a stochastic process in which the evolution (i.e. the next configuration) only depends on the current configuration of the system. In other words, for each step of the model, all the probabilities of transitions that relate the differen... | A Markov chain, also sometimes referred to as Markov process, is a specific type of a stochastic process in which the evolution (i.e. the next configuration) only depends on the current configuration of the system. In other words, for each step of the model, all the probabilities of transitions that relate the differen... |
<|im_start|>user
You are given a string `s`. Your task is to determine whether the string is a palindrome, considering only alphanumeric characters and ignoring cases. A palindrome is a string that reads the same forward and backward.
**Input:**
- A single string `s` (1 ≤ |s| ≤ 1000), which may contain uppercase and l... | You are given a string `s`. Your task is to determine whether the string is a palindrome, considering only alphanumeric characters and ignoring cases. A palindrome is a string that reads the same forward and backward.
**Input:**
- A single string `s` (1 ≤ |s| ≤ 1000), which may contain uppercase and lowercase letters,... | ```python
def is_palindrome(s: str) -> bool:
"""
Determines if the given string is a palindrome, considering only alphanumeric characters and ignoring cases.
:param s: The input string which may contain uppercase and lowercase letters, digits, spaces, and punctuation.
:return: True if the string is... |
<|im_start|>user
You are given three lists: `animals`, `target_positions`, and `current_order`. The list `animals` contains the names of animals, `target_positions` contains the target positions for each animal, and `current_order` represents the current arrangement of the animals. Your task is to determine the destina... | You are given three lists: `animals`, `target_positions`, and `current_order`. The list `animals` contains the names of animals, `target_positions` contains the target positions for each animal, and `current_order` represents the current arrangement of the animals. Your task is to determine the destination animal for e... | ```python
def find_destination(animals, target_positions, current_order):
"""
Determines the destination animal for each animal in the list based on target positions.
:param animals: List of animal names.
:param target_positions: List of target positions for each animal.
:param current_order: List ... |
<|im_start|>user
Depende, existen diferentes disciplinas de Fútbol. Entre las disciplinas más famosas , en Futsal o fútbol sala el juego se lleva a cabo con 5 jugadores por equipo. En fútbol 11( fútbol tradicional),7,5 los jugadores por equipo son 11, 7 y 5 respectivamente. Si hablamos de fútbol americano también se ju... | Depende, existen diferentes disciplinas de Fútbol. Entre las disciplinas más famosas , en Futsal o fútbol sala el juego se lleva a cabo con 5 jugadores por equipo. En fútbol 11( fútbol tradicional),7,5 los jugadores por equipo son 11, 7 y 5 respectivamente. Si hablamos de fútbol americano también se juega con 11 jugado... | Depende, existen diferentes disciplinas de Fútbol. Entre las disciplinas más famosas , en Futsal o fútbol sala el juego se lleva a cabo con 5 jugadores por equipo. En fútbol 11( fútbol tradicional),7,5 los jugadores por equipo son 11, 7 y 5 respectivamente. Si hablamos de fútbol americano también se juega con 11 jugado... |
<|im_start|>user
Consider a scenario where a detective is analyzing a crime scene. They notice that the language used in the evidence report either employs active or passive voice. The detective needs to reason out the potential reasons for the author's choice and what it reveals about their motive. Additionally, the d... | Consider a scenario where a detective is analyzing a crime scene. They notice that the language used in the evidence report either employs active or passive voice. The detective needs to reason out the potential reasons for the author's choice and what it reveals about their motive. Additionally, the detective must pro... | [{'content': "Consider a scenario where a detective is analyzing a crime scene. They notice that the language used in the evidence report either employs active or passive voice. The detective needs to reason out the potential reasons for the author's choice and what it reveals about their motive. Additionally, the dete... |
<|im_start|>user
You are given two PyTorch tensors, `tensor_a` with shape `(batch_size, input_size)` and `var_b` with shape `(batch_size, output_size)`, both residing on a GPU. Your task is to implement a function `convert_and_multiply(tensor_a, var_b)` that performs the following operations:
1. Convert `tensor_a` and... | You are given two PyTorch tensors, `tensor_a` with shape `(batch_size, input_size)` and `var_b` with shape `(batch_size, output_size)`, both residing on a GPU. Your task is to implement a function `convert_and_multiply(tensor_a, var_b)` that performs the following operations:
1. Convert `tensor_a` and `var_b` to NumPy... | ```python
import torch
import numpy as np
def pytorch_to_numpy(pt_tensor):
"""
Convert a PyTorch tensor on the GPU to a NumPy array on the CPU.
Args:
pt_tensor (torch.Tensor): PyTorch tensor on the GPU.
Returns:
numpy.ndarray: NumPy array on the CPU with the same data.
"""... |
<|im_start|>user
You are given two integers, N and K. Your task is to find the K-th lexicographical permutation sequence of the first N natural numbers, ensuring that even and odd numbers are placed in strictly alternating positions. If such a permutation does not exist, return "-1".
**Input:**
- The first line contai... | You are given two integers, N and K. Your task is to find the K-th lexicographical permutation sequence of the first N natural numbers, ensuring that even and odd numbers are placed in strictly alternating positions. If such a permutation does not exist, return "-1".
**Input:**
- The first line contains two integers, ... | ```python
import math
def get_kth_permutation(N, K):
"""
Finds the K-th lexicographical permutation sequence of the first N natural numbers
with even and odd numbers placed in strictly alternating positions.
:param N: Integer, the number of natural numbers to consider.
:param K: Integer, the p... |
<|im_start|>user
```bash
section .text
global _sum
_sum:
push ebp
mov ebp, esp
push ebx
mov ebx, [ebp + 8] ; get the first argument
mov ecx, [ebp + 12] ; get the second argument
add eax, ebx ; add the first argument to the result
add eax, ecx ; add the second argument to the result
pop ... | ```bash
section .text
global _sum
_sum:
push ebp
mov ebp, esp
push ebx
mov ebx, [ebp + 8] ; get the first argument
mov ecx, [ebp + 12] ; get the second argument
add eax, ebx ; add the first argument to the result
add eax, ecx ; add the second argument to the result
pop ebx
leave
... | ```bash
section .text
global _sum
_sum:
push ebp
mov ebp, esp
push ebx
mov ebx, [ebp + 8] ; get the first argument
mov ecx, [ebp + 12] ; get the second argument
add eax, ebx ; add the first argument to the result
add eax, ecx ; add the second argument to the result
pop ebx
leave
... |
<|im_start|>user
You are given a list of integers. Your task is to sort the list in ascending order using the bubble sort algorithm. Implement a function `bubble_sort` that takes a list of integers as input and sorts it in place.
**Input:**
- A list of integers `arr` (1 ≤ len(arr) ≤ 1000), where each integer `arr[i]` ... | You are given a list of integers. Your task is to sort the list in ascending order using the bubble sort algorithm. Implement a function `bubble_sort` that takes a list of integers as input and sorts it in place.
**Input:**
- A list of integers `arr` (1 ≤ len(arr) ≤ 1000), where each integer `arr[i]` satisfies -1000 ≤... | ```python
def bubble_sort(arr):
"""
Sorts a list of integers in ascending order using the bubble sort algorithm.
Parameters:
arr (list of int): The list of integers to be sorted.
Returns:
None: The list is sorted in place.
"""
n = len(arr)
for i in range(n):
for j in range(... |
<|im_start|>user
You are participating in a coding competition where you need to implement a function that interacts with AWS CloudWatch Logs. Your task is to create a Python function named `get_recent_log_events` that retrieves the most recent log events from a specified log stream within a given log group. The functi... | You are participating in a coding competition where you need to implement a function that interacts with AWS CloudWatch Logs. Your task is to create a Python function named `get_recent_log_events` that retrieves the most recent log events from a specified log stream within a given log group. The function should use the... | ```python
import boto3
def get_recent_log_events(log_group: str, log_stream: str, limit: int) -> list:
"""
Retrieves the most recent log events from a specified log stream within a given log group from AWS CloudWatch Logs.
Handles pagination and returns the number of log events limited by the provided limi... |
<|im_start|>user
You are given a square matrix of integers. Your task is to write a function that calculates the sum of the primary and secondary diagonals of the matrix. The primary diagonal consists of elements where the row index equals the column index, and the secondary diagonal consists of elements where the row ... | You are given a square matrix of integers. Your task is to write a function that calculates the sum of the primary and secondary diagonals of the matrix. The primary diagonal consists of elements where the row index equals the column index, and the secondary diagonal consists of elements where the row index plus the co... | ```python
def sum_of_diagonals(matrix):
"""
Calculate the sum of the primary and secondary diagonals of a square matrix.
:param matrix: List of lists representing the square matrix.
:return: Integer sum of the primary and secondary diagonals.
"""
primary_diagonal_sum = sum(matrix[i][i] for i in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.