cn_prompt stringlengths 38 1.08k | func_name stringlengths 1 70 | answer stringlengths 107 1.72k | en_prompt stringlengths 71 512 | test stringlengths 190 1.64M |
|---|---|---|---|---|
编写一个名为 is_perfect_num 的函数, 该函数接受一个整数 possible_perf_num 作为参数. 如果 possible_perf_num 是一个完美数, 函数返回 1, 否则返回 0. 完美数是指一个正整数, 它等于除了它自身以外的所有正约数的和. | is_perfect_num | def is_perfect_num(possible_perf_num):
if possible_perf_num <= 0:
return 0
if possible_perf_num == 1:
return 1
div_sum = 1
for possible_div in range(2, possible_perf_num // 2 + 1):
if possible_perf_num % possible_div == 0:
div_sum += possible_div
if possible_perf... | Write a function named `is_perfect_num` that takes an integer `possible_perf_num` as an argument. If `possible_perf_num` is a perfect number, the function should return 1; otherwise, it should return 0. A perfect number is a positive integer that is equal to the sum of all its proper divisors, excluding itself. |
import ast
import numpy as np
def check():
ret = is_perfect_num(1)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '1'
ret = is_perfect_num(2)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '0'
ret = is_perfect_num(6)
if is... |
给定一个混淆矩阵, 其中行表示正确的标签, 列表示预测的标签, 编写一个函数 specificity(confusion), 计算每个类别的特异度. 混淆矩阵是一个 numpy.ndarray 类型的二维数组, 其中 classes 是类别的数量. 函数返回一个 numpy.ndarray 类型的数组, 其中包含每个类别的特异度. | specificity | import numpy as np
def specificity(confusion):
true_pos = np.diagonal(confusion)
false_neg = np.sum(confusion, axis=1) - true_pos
false_pos = np.sum(confusion, axis=0) - true_pos
true_neg = np.sum(confusion) - (true_pos + false_neg + false_pos)
spec = true_neg / (true_neg + false_pos)
return ... | Given a confusion matrix where rows represent the true labels and columns represent the predicted labels, write a function specificity(confusion) to calculate the specificity for each class. The confusion matrix is a two-dimensional array of type numpy.ndarray, where classes is the number of categories. The function re... |
import ast
import numpy as np
def check():
ret = specificity(np.array([[10, 0], [0, 10]]))
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert np.isclose(ret, [1.0, 1.0]).all()
ret = specificity(np.array([[10, 5], [0, 10]]))
if isinstance(ret, np.ndarray):
ret = ret.tolist(... |
编写一个名为 make_cartesian 的函数, 该函数接收一个 Nx3 的 numpy 数组 h_points, 其中包含了 N 个点的齐次坐标.
函数的任务是将这些齐次坐标转换为 Nx2 的 numpy 数组, 其中包含了 N 个点的笛卡尔坐标.
齐次坐标转换为笛卡尔坐标的公式是:
笛卡尔坐标 = 齐次坐标 / 齐次坐标的最后一维.
请用 python 实现这个函数. | make_cartesian | import numpy as np
def make_cartesian(h_points):
dim = h_points.shape[1] - 1
points = np.zeros((h_points.shape[0], dim), h_points.dtype)
points[:, :] = h_points[:, :dim] / h_points[:, dim, None]
return points
| Write a function named `make_cartesian` that takes an Nx3 numpy array `h_points`, which contains the homogeneous coordinates of N points. The function's task is to convert these homogeneous coordinates into an Nx2 numpy array, which contains the Cartesian coordinates of N points. The formula for converting homogeneous ... |
import ast
import numpy as np
def check():
ret = make_cartesian(np.array([[1, 2, 1], [4, 5, 2], [7, 8, 3]]))
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[[1, 2], [2, 2], [2, 2]]'
ret = make_cartesian(np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]))
if isinstance(re... |
输入一个整数列表, 计算列表中等差数列的个数. 用 python 定义函数 number_of_arithmetic_slices(a) 解决这个问题. | number_of_arithmetic_slices | from typing import List
def number_of_arithmetic_slices(a: List[int]) ->int:
current_slice = 0
total_count = 0
for i in range(2, len(a)):
if a[i] + a[i - 2] == a[i - 1] << 1:
current_slice += 1
total_count += current_slice
else:
current_slice = 0
re... | Input a list of integers and calculate the number of arithmetic slices in the list. Define the function `number_of_arithmetic_slices(a)` in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = number_of_arithmetic_slices([1, 2, 3, 4])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '3'
ret = number_of_arithmetic_slices([1, 3, 5, 7])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(r... |
输入一个字符串, 格式为: master_name/sentinel_server:port,sentinel_server:port/db_id.
这个函数的任务是解析这个字符串, 返回 master name, 一个包含 (host, port) 对的列表, 和 db_id.
如果字符串格式不正确, 就抛出一个 ImproperlyConfigured 异常. 用 python 定义函数 parse_sentinel_db_connection_string(constring) 解决这个问题. | parse_sentinel_db_connection_string | from django.core.exceptions import ImproperlyConfigured
def parse_sentinel_db_connection_string(constring):
try:
connection_params = constring.split('/')
master_name = connection_params[0]
servers = [host_port.split(':') for host_port in connection_params[
1].split(',')]
... | Enter a string in the format: master_name/sentinel_server:port,sentinel_server:port/db_id. The task of this function is to parse this string and return the master name, a list of (host, port) pairs, and db_id. If the string format is incorrect, throw an ImproperlyConfigured exception. Define a function parse_sentinel_d... |
import ast
import numpy as np
def check():
ret = parse_sentinel_db_connection_string("master/host1:26379,host2:26379/0")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == "('master', [('host1', 26379), ('host2', 26379)], '0')"
ret = parse_sentinel_db_connection_string("ma... |
给定一个字符串, 找到它的所有排列方式, 保持字符的顺序, 但是改变字母的大小写. 用 python 定义函数 find_letter_case_string_permutations3(str) 解决这个问题. | find_letter_case_string_permutations3 | def find_letter_case_string_permutations3(str):
result = [str]
for i in range(len(str)):
if str[i].isalpha():
cur_len = len(result)
for j in range(cur_len):
new = list(result[j])
new[i] = new[i].swapcase()
result.append(''.join(new... | Given a string, find all its permutations by keeping the character order but changing the case of the letters. Define a function `find_letter_case_string_permutations3(str)` in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = find_letter_case_string_permutations3("")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == "['']"
ret = find_letter_case_string_permutations3("a")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert s... |
编写一个名为 collapse_runs 的函数, 它接收一个列表 L 作为参数. 这个函数应该移除列表 L 中第二个和后续的连续重复元素, 并返回修改后的列表 L.
例如, 如果 L = [1, 2, 1, 1, 1, 2, 0, 0], 那么 collapse_runs(L) 应该返回 [1, 2, 1, 2, 0] 并修改 L 为 [1, 2, 1, 2, 0]. | collapse_runs | def collapse_runs(L):
n, k = 0, 1
while k < len(L):
if L[n] == L[k]:
k += 1
else:
n, k, L[n] = n + 1, k + 1, L[k]
del L[n + 1:]
return L
| Write a function named collapse_runs that takes a list L as a parameter. This function should remove the second and subsequent consecutive duplicate elements in list L and return the modified list L.
For example, if L = [1, 2, 1, 1, 1, 2, 0, 0], then collapse_runs(L) should return [1, 2, 1, 2, 0] and modify L to [1, 2,... |
import ast
import numpy as np
def check():
ret = collapse_runs([1, 2, 1, 1, 1, 2, 0, 0])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[1, 2, 1, 2, 0]'
ret = collapse_runs([1, 1, 1, 1, 1, 1, 1, 1])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
as... |
给定两个三维数组 data1 和 data2, 计算它们的均方根误差 (RMSE). 如果 data1 或 data2 的维度不是 3, 或者它们的维度不相等, 则返回 0 并打印错误信息. 用 python 定义函数 RMSE(data1, data2) 解决这个问题. | RMSE | import numpy as np
def RMSE(data1, data2):
if data1.ndim != 3:
print('')
print('ERROR: Data1 does not have 3 dimensions')
RMSE = 0
return RMSE
if data2.ndim != 3:
print('')
print('ERROR: Data2 does not have 3 dimensions')
RMSE = 0
return RMSE
... | Given two 3-dimensional arrays data1 and data2, calculate their Root Mean Square Error (RMSE). If either data1 or data2 does not have 3 dimensions, or if their dimensions are not equal, return 0 and print an error message. Define a function RMSE(data1, data2) in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = RMSE(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]), np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]))
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]'
ret =... |
给定一个整数列表 nums, 编写一个函数 find_max_array_dp(nums) 来找到列表中连续子数组的最大和, 并返回子数组的起始和结束位置以及最大和. 例如, 如果 nums = [1,-2,3,10,-4,7,2,-48], 那么函数应该返回 (2, 6, 18), 因为从索引 2 到 6 的子数组 [3,10,-4,7,2] 的和最大, 为 18. | find_max_array_dp | def find_max_array_dp(nums):
left = right = 0
mx = nums[0]
dp = [0] * len(nums)
dp[0] = nums[0]
tmp = 0
for i in range(1, len(nums)):
if dp[i - 1] < 0:
dp[i] = dp[i] = nums[i]
tmp = i
else:
dp[i] = nums[i] + dp[i - 1]
if dp[i] > mx:
... | Given a list of integers `nums`, write a function `find_max_array_dp(nums)` to find the maximum sum of a contiguous subarray in the list. The function should return the starting and ending positions of the subarray, as well as the maximum sum. For example, if `nums = [1,-2,3,10,-4,7,2,-48]`, the function should return ... |
import ast
import numpy as np
def check():
ret = find_max_array_dp([1, -2, 3, 10, -4, 7, 2, -48])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '(2, 6, 18)'
ret = find_max_array_dp([-1, -2, -3, -4, -5])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
... |
编写一个名为 find_peak 的函数, 该函数接收一个无序整数列表作为输入, 并返回列表中的一个峰值. 峰值是指在列表中, 某个元素的值大于其相邻元素的值. 如果列表为空, 则返回 None. | find_peak | def find_peak(list_of_integers):
a = 0
b = len(list_of_integers) - 1
if len(list_of_integers) == 0:
return None
while a < b:
m = int((a + b) / 2)
if list_of_integers[m] < list_of_integers[m + 1]:
a = m + 1
else:
b = m
return list_of_integers[a... | Write a function named find_peak that takes an unordered list of integers as input and returns a peak value from the list. A peak is an element in the list that is greater than its neighboring elements. If the list is empty, return None. |
import ast
import numpy as np
def check():
ret = find_peak([])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == 'None'
ret = find_peak([1])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '1'
ret = find_peak([1, 2])
if isinst... |
定义一个函数 compute_error(patch1, patch2), 该函数接受两个参数 patch1 和 patch2, 它们都是灰度图像的 patch, 形状为 (patch_size, patch_size). 该函数的功能是:
1. 对 patch1 和 patch2 进行归一化处理, 即将它们的值除以它们的范数.
2. 计算 patch1 和 patch2 之间的均方误差 (MSE), 即 (patch1 - patch2) 的平方的平均值.
3. 返回 MSE 的值.
请用 python 实现这个函数. | compute_error | import numpy as np
def compute_error(patch1, patch2):
assert patch1.shape == patch2.shape, 'Differnt patch shapes'
error = 0
normalized_patch1 = patch1 / np.linalg.norm(patch1)
normalized_patch2 = patch2 / np.linalg.norm(patch2)
error = np.mean((normalized_patch1 - normalized_patch2) ** 2)
re... | Define a function `compute_error(patch1, patch2)` that takes two parameters, `patch1` and `patch2`, both of which are grayscale image patches of shape `(patch_size, patch_size)`. The function should:
1. Normalize `patch1` and `patch2` by dividing their values by their norms.
2. Compute the Mean Squared Error (MSE) bet... |
import ast
import numpy as np
def check():
ret = compute_error(np.array([[1, 2], [3, 4]]), np.array([[1, 2], [3, 4]]))
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert np.isclose(ret, 0.0)
ret = compute_error(np.array([[1, 2], [3, 4]]), np.array([[2, 3], [4, 5]]))
if isinstance(... |
给定一个只包含0、1和2的输入数组, 在一次遍历中对数组进行排序. 用 python 定义函数 sort_012(arr) 解决这个问题. | sort_012 | def sort_012(arr):
index_of_0 = 0
index_of_2 = len(arr) - 1
i = 0
while i <= index_of_2:
if arr[i] == 0:
arr[index_of_0], arr[i] = 0, arr[index_of_0]
index_of_0 += 1
i += 1
elif arr[i] == 2:
arr[index_of_2], arr[i] = 2, arr[index_of_2]
... | Given an input array containing only 0, 1, and 2, sort the array in a single pass. Define a function `sort_012(arr)` in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = sort_012([0, 0, 0, 0, 0])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[0, 0, 0, 0, 0]'
ret = sort_012([1, 1, 1, 1, 1])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[1, 1, 1, ... |
输入一个三维矩阵, 将其中的每个二维矩阵(frame)转换为一维向量. 用 python 定义函数 resize(mat) 解决这个问题. | resize | import numpy as np
def resize(mat):
frame_number, height, width = np.shape(mat)
A_mat = np.zeros((frame_number, height * width), dtype='float16')
for i in range(frame_number):
resized = mat[i]
A_mat[i] = resized.ravel()
A_mat = np.transpose(A_mat)
return A_mat
| Input a 3D matrix, convert each 2D matrix (frame) within it to a 1D vector. Define a function resize(mat) in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = resize(np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]]))
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[[1.0, 5.0, 9.0], [2.0, 6.0, 10.0], [3.0, 7.0, 11.0], [4.0, 8.0, 12.0]]'
ret = resize(np.array([... |
给定一个字典 user_to_city, 其中键是用户的 id, 值是城市的名称.
定义一个函数 cities_to_labels(user_to_city), 该函数将城市名称转换为整数标签,
其中每个城市对应一个唯一的整数标签. 返回一个新的字典 user_to_label, 其中键是用户的 id,
值是城市的标签, 以及标签的数量. | cities_to_labels | def cities_to_labels(user_to_city):
city_to_label = {}
counter = 0
user_to_label = {}
for user in user_to_city.keys():
city = user_to_city[user]
if not city in city_to_label:
city_to_label[city] = counter
counter += 1
user_to_label[user] = city_to_label[c... | Given a dictionary `user_to_city`, where the keys are user IDs and the values are city names.
Define a function `cities_to_labels(user_to_city)` that converts city names to integer labels,
with each city corresponding to a unique integer label. Return a new dictionary `user_to_label`,
where the keys are user IDs and... |
import ast
import numpy as np
def check():
ret = cities_to_labels({})
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '({}, 0)'
ret = cities_to_labels({"user1": "city1"})
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == "({'user1': 0... |
定义一个函数 unflatten_dict(dt, delimiter='/') 来实现字典的反展平操作. 这个函数不支持对列表进行反展平操作. | unflatten_dict | def unflatten_dict(dt, delimiter='/'):
dict_type = type(dt)
out = dict_type()
for key, val in dt.items():
path = key.split(delimiter)
item = out
for k in path[:-1]:
item = item.setdefault(k, dict_type())
item[path[-1]] = val
return out
| Define a function `unflatten_dict(dt, delimiter='/')` to unflatten a dictionary. This function does not support unflattening lists. |
import ast
import numpy as np
def check():
ret = unflatten_dict({"a/b/c": 1, "a/b/d": 2, "e/f/g": 3})
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert ret == {'a': {'b': {'c': 1, 'd': 2}}, 'e': {'f': {'g': 3}}}
ret = unflatten_dict({"a/b/c": "hello", "a/b/d": "world", "e/f/g": "!"})... |
定义一个函数 clean_list(column_lst, char_to_remove='', char_to_add='') 来清洗一个字符串列表. 清洗包括移除空行/空格, 移除任何指定的字符, 以及添加任何新的字符. 输入参数 column_lst 是一个字符串列表, char_to_remove 和 char_to_add 是字符串, 默认为空字符串. 函数返回清洗后的字符串列表. | clean_list | def clean_list(column_lst, char_to_remove='', char_to_add=''):
clean_data = []
for data_elem in column_lst:
if not (data_elem == '' or data_elem == ' ' or data_elem == '\n'):
data_elem = data_elem.replace(char_to_remove, '')
data_elem = char_to_add + data_elem + char_to_add
... | Define a function `clean_list(column_lst, char_to_remove='', char_to_add='')` to clean a list of strings. Cleaning includes removing empty lines/spaces, removing any specified characters, and adding any new characters. The input parameter `column_lst` is a list of strings, `char_to_remove` and `char_to_add` are strings... |
import ast
import numpy as np
def check():
ret = clean_list([], '', '')
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[]'
ret = clean_list(['a', 'b', 'c'], 'a', 'b')
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == "['bb', 'bbb', ... |
给定一个物品的重量列表 w, 一个物品的价值列表 v, 一个背包的最大承重量 c, 以及一个物品的索引 i, 以及一个缓存字典 cache.
定义一个函数 knapsack(w, v, c, i, cache), 这个函数的功能是计算在给定的物品列表和背包最大承重量的情况下, 能够获得的最大价值. | knapsack | def knapsack(w, v, c, i, cache):
ck = '%s:%s' % (c, i)
if ck in cache:
return cache[ck]
if i >= len(w):
return 0
l = 0
r = 0
if c >= w[i]:
r = knapsack(w, v, c - w[i], i, cache) + v[i]
l = knapsack(w, v, c, i + 1, cache)
cache[ck] = max(l, r)
return max(l, r)... | Given a list of item weights `w`, a list of item values `v`, a knapsack's maximum carrying capacity `c`, an item index `i`, and a cache dictionary `cache`, define a function `knapsack(w, v, c, i, cache)`. The function's purpose is to calculate the maximum value that can be obtained given the list of items and the knaps... |
import ast
import numpy as np
def check():
ret = knapsack([5,3,4,2], [60,50,70,30], 5, 0, {})
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '80'
ret = knapsack([4,3,6,2], [70,50,80,30], 6, 0, {})
if isinstance(ret, np.ndarray):
ret = ret.tolist()
asser... |
编写一个名为 peaks 的函数, 该函数接受一个整数列表作为输入, 并返回一个列表, 其中包含输入列表中峰值元素的索引. 峰值元素是指其值大于其相邻元素的元素. | peaks | def peaks(list=[]):
peaks_list = []
peaks_list = [i for i in range(1, len(list) - 1) if list[i - 1] < list[
i] and list[i] > list[i + 1]]
return peaks_list
| Write a function named `peaks` that takes a list of integers as input and returns a list containing the indices of the peak elements in the input list. A peak element is an element that is greater than its neighboring elements. |
import ast
import numpy as np
def check():
ret = peaks([])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[]'
ret = peaks([1])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[]'
ret = peaks([1, 2])
if isinstance(ret, np.... |
给定一个字典, 键是书名, 值是包含单词和它们频率的元组列表.
这个函数通过使用杰卡德相似度度量来找到哪个书与其他书最相似.
函数名为 text_similarities(book_signatures).
返回一个字典, 其中每个文本是键, 值是它最相似的文本. | text_similarities | def text_similarities(book_signatures):
list_of_keys = list(book_signatures.keys())
list_of_sets = []
for key in list_of_keys:
set_of_words = set()
for tuple in book_signatures[key]:
set_of_words.add(tuple[0])
list_of_sets.append(set_of_words)
measures_list = []
... | Given a dictionary where the keys are book titles and the values are lists of tuples containing words and their frequencies, this function finds which book is most similar to each other book using the Jaccard similarity measure. The function is named text_similarities(book_signatures). It returns a dictionary where eac... |
import ast
import numpy as np
def check():
ret = text_similarities({})
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert ret == {}
ret = text_similarities({"Book1": [("word1", 1), ("word2", 1)], "Book2": [("word1", 1), ("word3", 1)]})
if isinstance(ret, np.ndarray):
ret =... |
定义一个函数 ebay_fee(sell_price), 输入一个浮点数 sell_price, 表示在 ebay.com 上售卖的固定价格书籍、电影、音乐或视频游戏的售价. 该函数返回 ebay.com 收取的费用, 费用包括 $0.50 的列表费和售卖价格的 13% (如果售卖价格小于等于 $50), 售卖价格从 $50.01 到 $1000 的部分的 5%, 以及售卖价格大于 $1000 的部分的 2%. | ebay_fee | def ebay_fee(sell_price):
p50 = 0.13
p50_to_1000 = 0.05
p1000 = 0.02
fee = 0.5
if sell_price <= 50:
fee = fee + sell_price * p50
elif sell_price <= 1000:
fee = fee + 50 * p50 + (sell_price - 50) * p50_to_1000
else:
fee = fee + 50 * p50 + (1000 - 50) * p50_to_1000 + (... | Define a function ebay_fee(sell_price) that takes a float sell_price, representing the selling price of a fixed-price book, movie, music, or video game on ebay.com. The function returns the fee charged by ebay.com, which includes a $0.50 listing fee and 13% of the selling price (if the selling price is less than or equ... |
import ast
import numpy as np
def check():
ret = ebay_fee(0)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert np.isclose(ret, 0.5)
ret = ebay_fee(50)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert np.isclose(ret, 7.0)
ret = ebay_fee(51)
if isinstan... |
编写一个名为 pascal_triangle 的函数, 该函数接受一个整数 n 作为输入, 并返回一个列表的列表, 该列表的列表代表了帕斯卡三角形的前 n 行. 如果 n 小于等于 0, 则返回一个空列表. 帕斯卡三角形的每一行都是由前一行相邻元素的和构成的, 每一行的第一个和最后一个元素都是 1. | pascal_triangle | def pascal_triangle(n):
if n <= 0:
return []
arr = [[] for i in range(n)]
for i in range(n):
for j in range(i + 1):
if j < i:
if j == 0:
arr[i].append(1)
else:
arr[i].append(arr[i - 1][j] + arr[i - 1][j - 1]... | Write a function named `pascal_triangle` that takes an integer `n` as input and returns a list of lists representing the first `n` rows of Pascal's triangle. If `n` is less than or equal to 0, return an empty list. Each row of Pascal's triangle is constructed by summing adjacent elements from the previous row, and each... |
import ast
import numpy as np
def check():
ret = pascal_triangle(0)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[]'
ret = pascal_triangle(1)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[[1]]'
ret = pascal_triangle(2)
... |
定义一个函数 wireframe(x, y, fn), 该函数接受三个参数 x, y, fn. x 和 y 是数组, fn 是一个接受两个实数参数并返回一个实数的函数. 函数 wireframe 的目的是绘制一个由函数 fn(x, y) 定义的曲面的线框架. 线框架的 x 线和 y 线分别由 x 和 y 的值以及函数 fn 的值确定. 请用 python 实现这个函数. | wireframe | def wireframe(x, y, fn):
x_lines, y_lines = [], []
for xval in x:
temp = []
for yval in y:
temp.append(fn(xval, yval))
x_lines.append(temp)
for yval in y:
temp = []
for xval in x:
temp.append(fn(xval, yval))
y_lines.append(temp)
re... | Define a function `wireframe(x, y, fn)`, which takes three parameters `x`, `y`, and `fn`. `x` and `y` are arrays, and `fn` is a function that accepts two real number parameters and returns a real number. The purpose of the `wireframe` function is to plot a wireframe of a surface defined by `fn(x, y)`. The wireframe's x... |
import ast
import numpy as np
def check():
ret = wireframe([1, 2, 3], [4, 5, 6], lambda x, y: x + y)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '([[5, 6, 7], [6, 7, 8], [7, 8, 9]], [[5, 6, 7], [6, 7, 8], [7, 8, 9]])'
ret = wireframe([1, 2, 3], [4, 5, 6], lambda x, ... |
给定一个字典 arb_matrix, 其中包含每个可能结果的最佳赔率和对应的博彩公司, 以及一个押注金额 stake. 如果存在套利机会, 则计算出可能的套利赔付和套利策略. 如果套利机会存在, 则返回修改后的 arb_matrix, 其中包含可能的套利赔付和套利策略. 如果套利机会不存在, 则返回原始的 arb_matrix. 用 python 定义函数 calc_arb(arb_matrix, stake) 解决这个问题. | calc_arb | def calc_arb(arb_matrix, stake):
arb_matrix = arb_matrix.copy()
s = 0
outcomes = list(arb_matrix.keys())
for outcome in outcomes:
try:
s += 1 / arb_matrix[outcome]['price']
except TypeError:
continue
if s < 1:
arb_matrix['arbitrage'] = True
else:
... | Given a dictionary arb_matrix that contains the best odds and corresponding bookmakers for each possible outcome, and a stake amount. If there is an arbitrage opportunity, calculate the possible arbitrage payout and strategy. If an arbitrage opportunity exists, return the modified arb_matrix including the possible arbi... |
import ast
import numpy as np
def check():
ret = calc_arb({}, 100)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert ret == {'arbitrage': True, 'nvig': 1, 'profit': 100, 'strat': []}
ret = calc_arb({"outcome1": {"price": 2.0}, "outcome2": {"price": 3.0}}, 100)
if isinstance(ret, ... |
给定一个根目录路径和一个训练子目录名称列表, 编写一个函数 get_class_id(root_path, train_names), 该函数返回一个列表, 其中包含所有训练目录中的图像, 以及一个列表, 其中包含所有图像的类别ID. | get_class_id | import os
def get_class_id(root_path, train_names):
listImages = []
listClasses = []
for root, _, files in os.walk(root_path):
for file in sorted(files):
if file.endswith('jpg'):
listImages.append(os.path.join(root, file))
listClasses.append(train_names... | Given a root directory path and a list of training subdirectory names, write a function `get_class_id(root_path, train_names)` that returns a list containing all images in the training directories, as well as a list containing the class IDs of all the images. |
import ast
import numpy as np
def check():
ret = get_class_id("/path/to/root", ["class1", "class2", "class3"])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '([], [])'
ret = get_class_id("/path/to/another/root", ["classA", "classB"])
if isinstance(ret, np.ndarray)... |
输入一个无序列表, 使用比较计数法对列表进行排序. 返回一个新的列表, 该列表包含了输入列表的元素, 并按照升序排列. 用 python 定义函数 comparison_count_sort(unordered_lst) 解决这个问题. | comparison_count_sort | def comparison_count_sort(unordered_lst):
lst_size = len(unordered_lst)
count_lst = [(0) for i in range(lst_size)]
sorted_lst = [(0) for i in range(lst_size)]
for i in range(lst_size - 1):
for j in range(i + 1, lst_size):
if unordered_lst[i] < unordered_lst[j]:
count... | Input an unordered list, use the comparison count method to sort the list. Return a new list that contains the elements of the input list sorted in ascending order. Define a function *comparison_count_sort(unordered_lst)* in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = comparison_count_sort([1, 2, 3, 4, 5])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[1, 2, 3, 4, 5]'
ret = comparison_count_sort([5, 4, 3, 2, 1])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
asse... |
定义一个函数 get_complementary_sequence(dna), 这个函数接收一个 DNA 序列作为输入, 返回与输入 DNA 序列互补的 DNA 序列. 互补的 DNA 序列是通过将输入 DNA 序列中的每个碱基替换为其互补碱基来得到的. 其中, A 的互补碱基是 T, T 的互补碱基是 A, C 的互补碱基是 G, G 的互补碱基是 C.
例如, 输入 'ATCGGC', 输出应该是 'TAGCCG'.
输入 'ACGTACG', 输出应该是 'TGCATGC'. | get_complementary_sequence | def get_complementary_sequence(dna):
complement_dna = ''
for char in dna:
if char == 'A':
complement_nucleotide = 'T'
complement_dna = complement_dna + complement_nucleotide
elif char == 'T':
complement_nucleotide = 'A'
complement_dna = complement... | Define a function `get_complementary_sequence(dna)`, which takes a DNA sequence as input and returns the complementary DNA sequence. The complementary DNA sequence is obtained by replacing each base in the input DNA sequence with its complementary base. Here, A's complementary base is T, T's complementary base is A, C'... |
import ast
import numpy as np
def check():
ret = get_complementary_sequence("")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == ''
ret = get_complementary_sequence("A")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == 'T'
ret = g... |
给定一个多维索引和维度, 编写一个函数 ravel_multi_index(multi_index, dims), 将多维索引转换为单一索引.
输入:
- multi_index (torch.Tensor): 多维索引, 形状为 (N, D) 的张量.
- dims (torch.Tensor): 多维索引的维度.
输出:
- torch.Tensor: 单一索引, 形状为 (N,) 的张量. | ravel_multi_index | import torch
def ravel_multi_index(multi_index, dims):
dims_cumprod = torch.tensor(tuple(dims[1:]) + (1,), device=multi_index.
device)
dims_cumprod = dims_cumprod.flip(0).cumprod(0).flip(0)
return torch.sum(multi_index * dims_cumprod, dim=-1)
| Given a multi-dimensional index and dimensions, write a function `ravel_multi_index(multi_index, dims)` to convert the multi-dimensional index into a single index.
Input:
- `multi_index` (torch.Tensor): A tensor of shape (N, D) representing the multi-dimensional index.
- `dims` (torch.Tensor): The dimensions of the mu... |
import ast
import numpy as np
def check():
ret = ravel_multi_index(torch.tensor([[1, 2, 3], [4, 5, 6]]), torch.tensor([2, 3, 4]))
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == 'tensor([23, 74])'
ret = ravel_multi_index(torch.tensor([[0, 0, 0], [1, 1, 1]]), torch.tenso... |
编写一个名为 pascal_triangle 的函数, 该函数接受一个整数 n 作为输入, 返回一个列表的列表, 表示帕斯卡三角形. 三角形的行数由输入的整数 n 决定. 每一行的数字都是通过二项式展开计算得到的. 例如, 输入 5 应该返回 [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]. | pascal_triangle | def pascal_triangle(n):
result = []
if type(n) is not int or n <= 0:
return result
for row in range(n):
temp = []
for j in range(row + 1):
if j == 0 or j == row:
temp.append(1)
elif row > 0 and j > 0:
temp.append(result[row - 1... | Write a function named `pascal_triangle` that takes an integer `n` as input and returns a list of lists representing Pascal's triangle. The number of rows in the triangle is determined by the input integer `n`. The numbers in each row are calculated using binomial expansion. For example, an input of 5 should return `[[... |
import ast
import numpy as np
def check():
ret = pascal_triangle(0)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[]'
ret = pascal_triangle(1)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[[1]]'
ret = pascal_triangle(2)
... |
给定一个状态向量或计数, 计算最可能的二进制字符串. 如果输入是字典, 则按照值的降序排序, 并返回键值对中值最大的键. 如果输入是 numpy 数组, 则找到绝对值最大的元素的索引, 并将其转换为二进制形式, 作为二进制字符串返回. 用 python 定义函数 sample_most_likely(state_vector) 解决这个问题. | sample_most_likely | import numpy as np
from collections import OrderedDict
def sample_most_likely(state_vector):
if isinstance(state_vector, (OrderedDict, dict)):
binary_string = sorted(state_vector.items(), key=lambda kv: kv[1])[-1][
0]
x = np.asarray([int(y) for y in reversed(list(binary_string))])
... | Given a state vector or count, compute the most likely binary string. If the input is a dictionary, sort by value in descending order and return the key with the highest value. If the input is a numpy array, find the index of the largest absolute value element and convert this index to binary form to return as a binary... |
import ast
import numpy as np
def check():
ret = sample_most_likely(np.array([1, 0, 0, 0]))
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert np.isclose(ret, [0.0, 0.0]).all()
ret = sample_most_likely(np.array([0, 1, 0, 0]))
if isinstance(ret, np.ndarray):
ret = ret.tolis... |
编写一个名为 to_mm_ss 的函数, 该函数接受一个浮点数 seconds 作为输入, 并返回一个字符串. 这个字符串的格式是 *mm:ss, 其中 mm 和 ss 都是两位数, 如果需要, 前导的零会被添加.
例如, 如果输入是 65.5, 那么输出应该是 '01:05'. | to_mm_ss | def to_mm_ss(seconds: float) ->str:
m = int(seconds / 60)
s = seconds % 60
ret = str(m) + ':'
if m < 10:
ret = '0' + ret
if s < 10:
ret += '0'
ret += str(s).rstrip('.')
return ret
| Write a function named `to_mm_ss` that takes a floating-point number `seconds` as input and returns a string. The format of the string should be *mm:ss, where mm and ss are both two digits, with leading zeros added if necessary.
For example, if the input is 65.5, the output should be '01:05'. |
import ast
import numpy as np
def check():
ret = to_mm_ss(0)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '00:00'
ret = to_mm_ss(60)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '01:00'
ret = to_mm_ss(61)
if isinstance... |
定义一个函数 get_permutations(sequence), 这个函数接收一个字符串 sequence 作为输入, 返回这个字符串的所有排列组合. 你必须使用递归的方法来解决这个问题, 不能使用非递归的方法.
例如:
get_permutations('abc') 应该返回 ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
注意: 由于排列组合的顺序可能会有所不同, 所以你的函数返回的结果可能与这里列出的顺序不同. | get_permutations | def get_permutations(sequence):
if len(sequence) <= 1:
return list(sequence)
tem = get_permutations(sequence[1:])
ans = []
for instance in tem:
for i in range(len(instance) + 1):
tem_list = list(instance)
tem_list.insert(i, sequence[0])
ans.append(''.... | Define a function get_permutations(sequence). This function takes a string sequence as input and returns all permutations of this string. You must use a recursive approach to solve this problem and cannot use a non-recursive method.
For example:
get_permutations('abc') should return ['abc', 'acb', 'bac', 'bca', 'cab',... |
import ast
import numpy as np
def check():
ret = get_permutations("")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[]'
ret = get_permutations("a")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == "['a']"
ret = get_permutation... |
输入一个矩阵 A 和一个向量 x, 使用列向量化的方式进行矩阵乘法运算, 得到一个新的向量 b. 用 python 定义函数 matvec_col(A, x) 解决这个问题. | matvec_col | import numpy as np
def matvec_col(A, x):
import numpy as np
m, n = np.shape(A)
if n != x.size:
raise ValueError('matvec_col error: A and x are incompatible')
b = np.zeros(m, dtype=float)
for j in range(n):
b += A[:, j] * x[j]
return b
| Input a matrix A and a vector x, use column vectorization to perform matrix multiplication, and obtain a new vector b. Define a Python function matvec_col(A, x) to solve this problem. |
import ast
import numpy as np
def check():
ret = matvec_col(np.array([[1, 2], [3, 4]]), np.array([1, 2]))
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert np.isclose(ret, [5.0, 11.0]).all()
ret = matvec_col(np.array([[1, 0], [0, 1]]), np.array([1, 2]))
if isinstance(ret, np.ndar... |
输入一个单词列表, 构建一个 trigrams 字典. 字典的键是单词对, 值是后续单词的列表. 用 python 定义函数 build_trigrams(words) 解决这个问题. | build_trigrams | def build_trigrams(words):
trigrams = {}
for word in range(len(words) - 2):
pair = tuple(words[word:word + 2])
follower = words[word + 2]
trigrams.setdefault(pair, []).append(follower)
return trigrams
| Enter a list of words, build a trigrams dictionary. The keys of the dictionary are word pairs, and the values are lists of subsequent words. Define a Python function build_trigrams(words) to solve this problem. |
import ast
import numpy as np
def check():
ret = build_trigrams([])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert ret == {}
ret = build_trigrams(["a"])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert ret == {}
ret = build_trigrams(["a", "b"])
if ... |
编写一个名为 mode 的函数, 该函数接收一个列表和一个可选的布尔值作为参数. 该函数计算列表中元素的出现频率, 并返回出现频率最高的元素. 如果可选的布尔值为 True, 则打印出出现频率最高的元素. 用 python 实现这个函数. | mode | def mode(data_list, print_out=False):
freq = dict()
mode = list()
for ele in data_list:
if ele not in freq:
freq[ele] = 1
else:
freq[ele] += 1
sorted_freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
for ele in sorted_freq:
if ele[1] == so... | Write a function called `mode` that takes a list and an optional boolean value as parameters. The function calculates the frequency of elements in the list and returns the element with the highest frequency. If the optional boolean value is `True`, print the element with the highest frequency. Implement this function i... |
import ast
import numpy as np
def check():
ret = mode([1, 2, 2, 3, 4, 5])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[2]'
ret = mode(['a', 'b', 'b', 'c', 'c', 'c'])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == "['c']"
r... |
给定一个二维数组 'grid', 其中 '1' 表示陆地, '0' 表示水. 计算这个 'grid' 中岛的周长. 用 python 定义函数 island_perimeter(grid) 解决这个问题. | island_perimeter | def island_perimeter(grid):
rows = len(grid)
cols = len(grid[0])
perimeter = 0
for row in range(rows):
for col in range(cols):
if grid[row][col] == 1:
perimeter += 4
if row > 0 and grid[row - 1][col] == 1:
perimeter -= 2
... | Given a 2D array 'grid', where '1' represents land and '0' represents water, calculate the perimeter of the island in this 'grid'. Define a function `island_perimeter(grid)` in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = island_perimeter([[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '16'
ret = island_perimeter([[1,0]])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert st... |
给定一个单词列表, 返回具有最多字母异位词的单词. 例如, 如果输入是 ['cat', 'dog', 'tac', 'god', 'act'], 输出应该是 'cat'. 用 python 定义函数 find_most_anagrams_from_wordlist(wordlist) 解决这个问题. | find_most_anagrams_from_wordlist | def find_most_anagrams_from_wordlist(wordlist):
word_dict = {}
for word in wordlist:
alpha = ''.join(sorted(word))
if word_dict.get(alpha) == None:
word_dict[alpha] = [word]
else:
word_dict[alpha].append(word)
most_ana_word = None
max_ana = 0
for word... | Given a list of words, return the word with the most anagrams. For example, if the input is ['cat', 'dog', 'tac', 'god', 'act'], the output should be 'cat'. Define a function in Python named `find_most_anagrams_from_wordlist(wordlist)` to solve this problem. |
import ast
import numpy as np
def check():
ret = find_most_anagrams_from_wordlist(["cat", "act", "tac", "dog", "god"])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == 'act'
ret = find_most_anagrams_from_wordlist(["abc", "cba", "bca", "def", "fed"])
if isinstance(ret... |
输入一个由元组组成的列表, 每个元组包含一个名为 allele 的字符串和一个名为 p_value 的浮点数.
这个函数返回该组中最可能的两个等位基因. 用 python 定义函数 most_probable_alleles(allele_list) 解决这个问题. | most_probable_alleles | import re
from collections import defaultdict
def most_probable_alleles(allele_list):
all_alleles = defaultdict()
for allele, pvalue in allele_list:
allele = re.split(':', allele)
if len(allele) < 2:
continue
allele = ':'.join([allele[0], allele[1]])
try:
... | Input a list composed of tuples, each tuple contains a string named allele and a float named p_value.
This function returns the two most probable alleles in the group. Define the function `most_probable_alleles(allele_list)` in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = most_probable_alleles([("A:1", 0.01), ("B:2", 0.02), ("C:3", 0.03), ("D:4", 0.04)])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == "['A:1', 'B:2']"
ret = most_probable_alleles([("A:1", 0.01), ("B:2", 0.02), ("C:3", 0.03)... |
编写一个函数 clean_name(name), 这个函数接收一个字符串 name 作为输入, 并返回一个新的字符串 newname. 这个函数会删除 name 中的所有非字母和非数字字符, 并将所有字母转换为小写. 例如, 如果 name 是 "John Doe", 那么 newname 就是 "johndoe". 如果 name 是 "Jane_Doe123", 那么 newname 就是 "janedoe123". | clean_name | def clean_name(name):
newname = ''
for i in range(len(name)):
char = name[i]
if ord(char) > 96 and ord(char) < 123:
newname += char
elif ord(char) > 64 and ord(char) < 91:
newname += chr(ord(char) + 32)
elif ord(char) > 47 and ord(char) < 58:
... | Write a function `clean_name(name)`, which takes a string `name` as input, and returns a new string `newname`. This function will remove all non-alphabetic and non-numeric characters from `name`, and convert all letters to lowercase. For example, if `name` is "John Doe", then `newname` will be "johndoe". If `name` is "... |
import ast
import numpy as np
def check():
ret = clean_name("John Doe")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == 'johndoe'
ret = clean_name("Jane_Doe")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == 'janedoe'
ret = clean... |
定义一个名为 card_value 的函数, 它接受一个字符串列表作为输入, 列表中的每个字符串代表一张牌.
函数需要计算每张牌的值, 方法是将牌的字符串与一个字典中的键进行比较, 并获取对应的键值.
然后将每张牌的值加到一个变量 sum 中. 最后返回 sum 的值. | card_value | def card_value(cards):
sum = 0
values = {'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven':
7, 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Ace': 11, 'Jack': 12, 'Queen':
13, 'King': 14}
for key in values:
for card in cards:
if key in card:
sum += value... | Define a function named `card_value` that accepts a list of strings as input, where each string represents a card. The function needs to calculate the value of each card by comparing the card's string with the keys in a dictionary and retrieving the corresponding key value. Then, add the value of each card to a variabl... |
import ast
import numpy as np
def check():
ret = card_value([])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '0'
ret = card_value(["Two"])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '2'
ret = card_value(["Two", "Three"])... |
编写一个名为 get_comments 的函数, 该函数接受一个字符串参数 source, 表示一段 Python 代码. 该函数应该返回一个字符串, 其中包含了这段代码中的所有注释. 注释应该不包含 '#' 符号.
| get_comments | import tokenize
import io
def get_comments(source: str) ->str:
comments = []
g = tokenize.generate_tokens(io.StringIO(source).readline)
for toknum, tokval, _, _, _ in g:
if toknum == tokenize.COMMENT:
comments.append((toknum, tokval))
return tokenize.untokenize(comments).replace('... | Write a function called `get_comments` which takes a string parameter `source` representing a piece of Python code. The function should return a string containing all the comments in the code. The comments should not include the '#' symbol. |
import ast
import numpy as np
def check():
ret = get_comments("")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == ''
ret = get_comments("# This is a comment")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == ' This is a comment'
... |
给定两个一维的 numpy 数组 spikeTimeArray 和 NeurIndexArray, 其中 spikeTimeArray 存储了每个神经元的脉冲时间, NeurIndexArray 存储了每个神经元的索引. 这个函数会生成一个 N x T 的数组, 其中每一行对应网络中的一个神经元 (N 维度), 每一列对应一个脉冲时间 (T 维度). 请用 python 定义函数 spikeMon_To_Matrix(spikeTimeArray, NeurIndexArray) 来解决这个问题. | spikeMon_To_Matrix | import numpy as np
def spikeMon_To_Matrix(spikeTimeArray, NeurIndexArray):
spikeTimeArray = np.array(spikeTimeArray)
NeurIndexArray = np.array(NeurIndexArray)
iter = np.amax(NeurIndexArray)
i = 0
ind = 0
NeurInd = []
for i in range(iter + 1):
ind = np.where(NeurIndexArray == i)
... | Given two 1-dimensional numpy arrays spikeTimeArray and NeurIndexArray, where spikeTimeArray stores the spike times of each neuron and NeurIndexArray stores the indices of each neuron, this function will generate an N x T array, where each row corresponds to a neuron in the network (N dimension), and each column corres... |
import ast
import numpy as np
def check():
ret = spikeMon_To_Matrix(np.array([1, 2, 3, 4, 5]), np.array([0, 1, 2, 3, 4]))
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[array([1]), array([2]), array([3]), array([4]), array([5])]'
ret = spikeMon_To_Matrix(np.array([1,... |
定义一个名为 pegar_dados(arq_excel) 的函数, 该函数接收一个 excel 文件作为参数,
并返回一个字典, 其中包含两个键值对, 'nomes' 和 'emails', 分别对应 excel 文件中的所有名字和邮箱.
你可以使用 python 的 pyexcel 库来读取 excel 文件.
例如:
valores = pegar_dados(arq_excel)
print(valores['nomes'])
print(valores['emails'])
| pegar_dados | def pegar_dados(arq_excel):
indice_nome = 0
indice_email = 0
nomes = []
emails = []
for linha in arq_excel:
if 'nome' in linha:
indice_nome += linha.index('nome')
if 'email' in linha:
indice_email += linha.index('email')
n = 0
for linha in arq_excel:
... | Define a function named `pegar_dados(arq_excel)`, which accepts an Excel file as a parameter and returns a dictionary containing two key-value pairs, 'nomes' and 'emails', corresponding to all names and emails in the Excel file. You can use Python's pyexcel library to read the Excel file.
For example:
```python
valor... |
import ast
import numpy as np
def check():
ret = pegar_dados([["nome", "email"], ["John", "john@example.com"], ["Jane", "jane@example.com"]])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert ret == {'nomes': ['John', 'Jane'], 'emails': ['john@example.com', 'jane@example.com']}
ret =... |
输入一个字典, 字典的键是书名, 值是页数. 定义一个函数 get_top_ten_longest_books(dict_of_title_and_pages), 这个函数返回一个列表, 列表包含页数最多的十本书的书名和页数. | get_top_ten_longest_books | def get_top_ten_longest_books(dict_of_title_and_pages):
dict_copy = dict_of_title_and_pages.copy()
sorted_dict = {k: v for k, v in sorted(dict_copy.items(), key=lambda x:
x[1], reverse=True)}
top_ten = dict(list(sorted_dict.items())[0:10])
return top_ten
| Input a dictionary where the keys are book titles and the values are page numbers. Define a function `get_top_ten_longest_books(dict_of_title_and_pages)` that returns a list containing the titles and page numbers of the top ten longest books. |
import ast
import numpy as np
def check():
ret = get_top_ten_longest_books({})
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert ret == {}
ret = get_top_ten_longest_books({"Book1": 100, "Book2": 200, "Book3": 300, "Book4": 400, "Book5": 500, "Book6": 600, "Book7": 700, "Book8": 800, ... |
定义一个名为 compute_check_digit(eleven_dig_num) 的函数, 该函数接收一个字符串 eleven_dig_num, 并计算一个校验位.
这个校验位是通过将字符串中的奇数位数字相加, 然后乘以3, 再加上偶数位数字的和,
然后取这个和的最后一位数字, 如果这个数字是0, 那么校验位就是0, 如果不是0,
那么校验位就是10减去这个数字. 返回计算得到的校验位. | compute_check_digit | def compute_check_digit(eleven_dig_num):
part_1 = 0
part_2 = 0
for digit in range(len(eleven_dig_num)):
if (digit + 1) % 2 != 0:
part_1 += int(eleven_dig_num[digit])
if (digit + 1) % 2 == 0:
part_2 += int(eleven_dig_num[digit])
dig_sum = part_1 * 3 + part_2
p... | Define a function named `compute_check_digit(eleven_dig_num)` that takes a string `eleven_dig_num` and calculates a check digit. The check digit is calculated by summing the digits in the odd positions of the string, multiplying that sum by 3, then adding the sum of the digits in the even positions. Next, take the last... |
import ast
import numpy as np
def check():
ret = compute_check_digit("12345678901")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '2'
ret = compute_check_digit("00000000000")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '0'
... |
定义一个函数 get_players_highest_valued_card(player1_hand, player2_hand), 该函数接收两个玩家的手牌,
每个手牌都是一个字典列表, 每个字典都有一个键 'pow_lvl' 表示卡牌的力量等级.
函数需要找到每个玩家手牌中力量等级最高的卡牌, 并返回这些卡牌的力量等级. | get_players_highest_valued_card | def get_players_highest_valued_card(player1_hand, player2_hand):
if player1_hand[0]['pow_lvl'] > player1_hand[1]['pow_lvl']:
player1_highest_valued_card = player1_hand[0]['pow_lvl']
else:
player1_highest_valued_card = player1_hand[1]['pow_lvl']
if player2_hand[0]['pow_lvl'] > player2_hand[1... | Define a function `get_players_highest_valued_card(player1_hand, player2_hand)`, which receives the hands of two players, where each hand is a list of dictionaries. Each dictionary has a key 'pow_lvl' representing the power level of the card. The function needs to find the highest power level card in each player's hand... |
import ast
import numpy as np
def check():
ret = get_players_highest_valued_card([{'pow_lvl': 10}, {'pow_lvl': 20}], [{'pow_lvl': 30}, {'pow_lvl': 40}])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '(20, 40)'
ret = get_players_highest_valued_card([{'pow_lvl': 50}, {'... |
给定一个二维的 numpy 数组 img, 这个函数会把 img 的较短边用黑色像素填充, 使其成为一个正方形, 并返回这个正方形的图像. 如果图像是竖直的, 那么会在右边填充黑色像素使其成为正方形. 如果图像是横向的, 那么会在底部填充黑色像素使其成为正方形. 请用 python 定义函数 padInverted(img) 解决这个问题. | padInverted | import numpy as np
def padInverted(img: np.ndarray, logger=None, dtype=np.float64) ->np.ndarray:
paddedImg = img
try:
if len(img.shape) == 2:
nRows, nCols = img.shape
else:
nRows, nCols = img.shape[0], img.shape[1]
if nRows != nCols:
if nCols < nRow... | Given a 2D numpy array `img`, this function will pad the shorter side of `img` with black pixels to make it a square and return the squared image. If the image is vertical, it will pad the right side with black pixels to make it a square. If the image is horizontal, it will pad the bottom with black pixels to make it a... |
import ast
import numpy as np
def check():
ret = padInverted(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[[1, 2, 3], [4, 5, 6], [7, 8, 9]]'
ret = padInverted(np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]))
i... |
给定一个 y 轴刻度列表和一个刻度差值, 更新 y 轴刻度列表, 使得列表中的每个值都增加刻度差值. 用 python 定义函数 set_yaxis(yticks_list, scale_difference) 解决这个问题. | set_yaxis | import numpy as np
def set_yaxis(yticks_list, scale_difference):
new_yticks = []
new_yticks.append(yticks_list[int(len(yticks_list) / 2)])
yticks_list = np.delete(yticks_list, int(len(yticks_list) / 2))
for i in range(int(len(yticks_list) / 2)):
new_yticks.append(new_yticks[0] - (i + 1) * sca... | Given a list of y-axis ticks and a tick difference, update the y-axis tick list so that each value in the list is increased by the tick difference. Define a function set_yaxis(yticks_list, scale_difference) in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = set_yaxis([1, 2, 3, 4, 5], 1.0)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[1.0, 2.0, 3, 4.0]'
ret = set_yaxis([1.0, 2.0, 3.0, 4.0, 5.0], 0.5)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
asser... |
定义一个函数 img_mirror(image, is_horizontal_mirror), 这个函数接受一个二维或三维的图像张量 image 和一个布尔值 is_horizontal_mirror. 如果 is_horizontal_mirror 为 True, 那么函数应该返回一个水平镜像的图像. 如果 is_horizontal_mirror 为 False, 那么函数应该返回一个垂直镜像的图像. 如果图像张量的维度不是 2 或 3, 那么函数应该抛出一个 ValueError 异常. | img_mirror | import numpy as np
def img_mirror(image, is_horizontal_mirror):
if len(image.shape) < 2 or len(image.shape) > 3:
raise ValueError('Tensor image must have 2 or 3 dimensions.')
height = image.shape[0]
width = image.shape[1]
is_rgb = len(image.shape) == 3
mirrored = np.zeros(shape=image.shap... | Define a function `img_mirror(image, is_horizontal_mirror)`. This function accepts a 2D or 3D image tensor `image` and a boolean value `is_horizontal_mirror`. If `is_horizontal_mirror` is True, the function should return a horizontally mirrored image. If `is_horizontal_mirror` is False, the function should return a ver... |
import ast
import numpy as np
def check():
ret = img_mirror(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), True)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[[3.0, 2.0, 1.0], [6.0, 5.0, 4.0], [9.0, 8.0, 7.0]]'
ret = img_mirror(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9... |
给定一个数值列表, 计算每个数值的指数, 然后将每个指数除以所有指数的总和, 得到一个新的数值列表. 用 python 定义函数 softmax(values) 解决这个问题. | softmax | from math import exp
def softmax(values):
e_values = []
mx = max(values)
for v in values:
v = v - mx
ev = exp(v)
e_values.append(ev)
s = sum(e_values)
inv_s = 1.0 / s
return [(ev * inv_s) for ev in e_values]
| Given a list of values, calculate the exponent of each value, then divide each exponent by the sum of all the exponents to obtain a new list of values. Define a Python function softmax(values) to solve this problem. |
import ast
import numpy as np
def check():
ret = softmax([1, 2, 3, 4, 1])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert np.isclose(ret, [0.031062774127550947, 0.08443737445244952, 0.22952458061688555, 0.6239124966755631, 0.031062774127550947]).all()
ret = softmax([0, 0, 0, 0, 0])... |
输入一个单词列表, 构建一个 trigram 字典. 用 python 定义函数 make_trigrams(words) 解决这个问题. | make_trigrams | def make_trigrams(words):
tris = {}
for i in range(len(words) - 2):
first = words[i]
second = words[i + 1]
third = words[i + 2]
pair = first, second
print(pair, third)
tris.setdefault(pair, []).append(third)
return tris
| Input a list of words and construct a trigram dictionary. Define the function `make_trigrams(words)` in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = make_trigrams([])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert ret == {}
ret = make_trigrams(["a"])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert ret == {}
ret = make_trigrams(["a", "b"])
if isi... |
输入一个字符列表和一个句子, 返回一个列表, 其中包含句子中出现的字符, 以及一个列表, 其中包含句子中未出现的字符. 用 python 定义函数 characters_in_sentence(characters, sentence) 解决这个问题. | characters_in_sentence | def characters_in_sentence(characters, sentence):
characters_mentioned = []
if len(characters) == 0:
return characters_mentioned, characters
character = characters.pop(0)
while character in sentence:
sentence = sentence.split(character, 1)[1]
characters_mentioned.append(characte... | Enter a list of characters and a sentence, and return a list containing the characters that appear in the sentence, as well as a list containing the characters that do not appear in the sentence. Define a function `characters_in_sentence(characters, sentence)` in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = characters_in_sentence([], "")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '([], [])'
ret = characters_in_sentence(["a"], "a")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == "(['... |
定义一个函数 ackermann_function(m, n), 它接受两个参数 m 和 n, 并返回使用 Ackermann 函数计算得到的值. | ackermann_function | def ackermann_function(m: int, n: int) ->int:
if m == 0:
return n + 1
elif m > 0 and n == 0:
return ackermann_function(m - 1, 1)
elif m > 0 and n > 0:
return ackermann_function(m - 1, ackermann_function(m, n - 1))
else:
print('Please enter positive numbers only')
| Define a function `ackermann_function(m, n)` that takes two parameters `m` and `n`, and returns the value computed using the Ackermann function. |
import ast
import numpy as np
def check():
ret = ackermann_function(0, 0)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '1'
ret = ackermann_function(1, 0)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '2'
ret = ackermann_fun... |
给定一个 MIDI 音高列表, 生成每个音高的正弦波信号.
函数名为 generate_sinusoid_pitches(pitches=[69], dur=0.5, Fs=4000, amp=1)
参数:
- pitches (list): MIDI 音高列表 (默认值 = [69])
- dur (float): 每个正弦波信号的持续时间 (秒) (默认值 = 0.5)
- Fs (scalar): 采样率 (默认值 = 4000)
- amp (float): 生成信号的幅度 (默认值 = 1)
返回值:
- x (np.ndarray): 信号
- t (np.ndarray): 时间轴 (秒) | generate_sinusoid_pitches | import numpy as np
def generate_sinusoid_pitches(pitches=[69], dur=0.5, Fs=4000, amp=1):
N = int(dur * Fs)
t = np.arange(N) / Fs
x = []
for p in pitches:
freq = 2 ** ((p - 69) / 12) * 440
x = np.append(x, np.sin(2 * np.pi * freq * t))
x = amp * x / np.max(x)
return x, t
| Given a list of MIDI pitches, generate the sinusoidal signal for each pitch.
Function name: `generate_sinusoid_pitches(pitches=[69], dur=0.5, Fs=4000, amp=1)`
Parameters:
- pitches (list): List of MIDI pitches (default = [69])
- dur (float): Duration of each sinusoidal signal (in seconds) (default = 0.5)
- Fs (scalar... |
import ast
import numpy as np
def check():
ret = generate_sinusoid_pitches(pitches=[69], dur=0.5, Fs=4000, amp=1)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '(array([ 0. , 0.63742399, 0.98228725, ..., -0.87630668,\n -0.98228725, -0.63742399]), array([0.0... |
给定一个数组代表一个迷宫, 返回需要的步数来走出迷宫.
数组的元素必须是整数.
定义一个函数 steps_to_exit(maze), 这个函数接受一个数组 maze 作为输入, 返回一个整数, 表示从迷宫中走出的步数. | steps_to_exit | def steps_to_exit(maze):
position = 0
steps = 0
maze_length = len(maze)
while 0 <= position < maze_length:
steps += 1
previous_position = position
position = position + maze[previous_position]
if maze[previous_position] >= 3:
maze[previous_position] -= 1
... | Given an array representing a maze, return the number of steps needed to exit the maze.
The elements of the array must be integers.
Define a function steps_to_exit(maze), which takes an array maze as input and returns an integer representing the number of steps to exit the maze. |
import ast
import numpy as np
def check():
ret = steps_to_exit([1, 2, 3, 4, 5])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '3'
ret = steps_to_exit([5, 4, 3, 2, 1])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '1'
ret = s... |
输入一个 OpenCV 轮廓, 计算凸包和凸性缺陷. 通过深度过滤噪声凸性缺陷. 用 python 定义函数 filter_defects_and_hull(cnt) 解决这个问题. | filter_defects_and_hull | import numpy as np
import cv2 as cv
def filter_defects_and_hull(cnt):
hull = cv.convexHull(cnt, returnPoints=False)
defects = cv.convexityDefects(cnt, hull)
if defects is not None:
defects[:, 0, 3] = defects[:, 0, 3] / 256.0
depth_thesh = 4.0
filtered_defects = defects[np.where(de... | Input an OpenCV contour, calculate the convex hull and convexity defects. Filter the noise in convexity defects through depth. Define a function filter_defects_and_hull(cnt) in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = filter_defects_and_hull(np.array([[0, 0], [1, 1], [2, 2], [3, 3]]))
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '(array([], dtype=float64), array([], dtype=float64))'
ret = filter_defects_and_hull(np.array([[0, 0], [1... |
给定一个按钮列表和一个格式, 生成一个按钮组. 如果格式是 'toolbar', 则生成一个工具栏按钮组. 如果格式是 'vertical', 则生成一个垂直按钮组. 如果 'pull' 参数为真, 则生成的按钮组将被拉伸. 用 python 定义函数 buttonGroup(buttonList=[], format='default', pull=False) 解决这个问题.
| buttonGroup | def buttonGroup(buttonList=[], format='default', pull=False):
thisButtonList = ''
count = 1
for button in buttonList:
thisButtonList = '%(thisButtonList)s %(button)s' % locals()
count += 1
if pull is not False:
pull = 'pull-%(pull)s' % locals()
else:
pull = ''
if... | Given a list of buttons and a format, generate a button group. If the format is 'toolbar', generate a toolbar button group. If the format is 'vertical', generate a vertical button group. If the 'pull' parameter is true, the generated button group will be stretched. Define a function in Python `buttonGroup(buttonList=[]... |
import ast
import numpy as np
def check():
ret = buttonGroup(buttonList=[], format='default', pull=False)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '\n <div class="btn-group " id=" ">\n \n </div>'
ret = buttonGroup(buttonList=['button1... |
给定一个一维数组或一个三维数组, 编写一个名为 skew_symmetric_3d 的函数, 该函数接受一个数组作为输入, 并返回一个新的数组, 该数组是输入数组的反对称矩阵. 反对称矩阵是一个满足 a_ij = -a_ji 的矩阵. 如果输入数组是一维的, 则将其转换为三维数组. | skew_symmetric_3d | import numpy as np
def skew_symmetric_3d(vector: np.array) ->np.array:
vector = vector.squeeze()
skew_sym = np.array([[0.0, -vector[2], vector[1]], [vector[2], 0.0, -
vector[0]], [-vector[1], vector[0], 0]])
return skew_sym
| Given a one-dimensional or three-dimensional array, write a function named skew_symmetric_3d. This function accepts an array as input and returns a new array that is the skew-symmetric matrix of the input array. A skew-symmetric matrix is a matrix that satisfies a_ij = -a_ji. If the input array is one-dimensional, conv... |
import ast
import numpy as np
def check():
ret = skew_symmetric_3d(np.array([1, 2, 3]))
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[[0.0, -3.0, 2.0], [3.0, 0.0, -1.0], [-2.0, 1.0, 0.0]]'
ret = skew_symmetric_3d(np.array([0, 0, 0]))
if isinstance(ret, np.ndarra... |
定义一个函数 get_ZGNR_interactions(nAtoms), 输入参数为 nAtoms, 表示 ZGNR 中的原子数量. 这个函数的功能是返回 ZGNR 的跳跃交互矩阵 t00, t, td, 以及 onsite_list, 其中 onsite_list 是本征能量, 全为零. 请用 python 实现这个函数. | get_ZGNR_interactions | import numpy as np
def get_ZGNR_interactions(nAtoms):
try:
assert nAtoms % 4 == 0
except:
print(
'number of atoms should be multiple of 4, since each cell has 4 atoms'
)
ones = np.asarray(np.ones(nAtoms - 1))
t00 = np.diag(ones, k=1) + np.diag(ones, k=-1)
t... | Define a function `get_ZGNR_interactions(nAtoms)`, where the input parameter `nAtoms` represents the number of atoms in a ZGNR. The function should return the hopping interaction matrices `t00`, `t`, `td`, and `onsite_list` for the ZGNR, where `onsite_list` consists of on-site energies, all set to zero. Implement this ... |
import ast
import numpy as np
def check():
ret = get_ZGNR_interactions(4)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '(array([[0., 1., 0., 0.],\n [1., 0., 1., 0.],\n [0., 1., 0., 1.],\n [0., 0., 1., 0.]]), array([[0., 1., 0., 0.],\n [0., 0., 0.,... |
定义一个函数 my_function(a), 该函数接收一个列表 a 作为输入, 统计列表中每种类型的元素的数量, 并返回一个字典, 其中键是类型名称, 值是该类型元素的数量. 例如, 如果输入列表 a 是 ['hello', 123, (1, 2, 3)], 那么输出应该是 {'str': 1, 'int': 1, 'tuple': 1}. | my_function | def my_function(a):
types = []
counted_types = {}
defoult_types = ['str', 'int', 'tuple']
for i in a:
types.append(type(i))
types = str(types)
for i in defoult_types:
if i in types:
counted_types[i] = types.count(i)
return counted_types
| Define a function `my_function(a)`, which takes a list `a` as input. The function should count the number of elements of each type in the list and return a dictionary where the keys are the type names and the values are the counts of elements of that type. For example, if the input list `a` is `['hello', 123, (1, 2, 3)... |
import ast
import numpy as np
def check():
ret = my_function([])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert ret == {}
ret = my_function([1, 2, 3])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert ret == {'int': 3}
ret = my_function(['a', 'b', 'c'])... |
定义一个函数 getMsTime(t_hms), 输入一个时间 t_hms, 格式为 HH:MM:SS, 将其转换为毫秒并返回. | getMsTime | def getMsTime(t_hms):
t_hours, t_minutes, t_seconds = (['0', '0'] + t_hms.split(':'))[-3:]
t_hours = int(t_hours)
t_minutes = int(t_minutes)
t_seconds = float(t_seconds)
t_time = int(3600000 * t_hours + 60000 * t_minutes + 1000 * t_seconds)
return t_time
| Define a function getMsTime(t_hms), input a time t_hms in the format HH:MM:SS, convert it to milliseconds and return it. |
import ast
import numpy as np
def check():
ret = getMsTime("00:00:00")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '0'
ret = getMsTime("01:00:00")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '3600000'
ret = getMsTime("00... |
给定一个字典 messages_mapping, 其中每个键对应一个字典, 每个字典中有一个键为 'message' 的值.
另外给定一个字符串 key_path, 它是一个以点号分隔的键路径.
编写一个函数 extract_metadata_values(messages_mapping, key_path),
该函数使用给定的键路径从 messages_mapping 中提取元数据值.
如果在给定的键路径上没有找到数据, 函数应返回字符串 '-'. | extract_metadata_values | from typing import Any
def extract_metadata_values(messages_mapping: dict[str, dict[str, Any]],
key_path: str) ->(str | Any):
keys: list[str] = key_path.split('.')
data: list[Any] = [value['message'] for _, value in messages_mapping.
items() if value.get('message')]
for key in keys:
d... | Given a dictionary `messages_mapping`, where each key corresponds to a dictionary, and each dictionary contains a value with the key 'message'.
Additionally given is a string `key_path`, which is a dot-separated key path.
Write a function `extract_metadata_values(messages_mapping, key_path)` that uses the given key p... |
import ast
import numpy as np
def check():
ret = extract_metadata_values({"message1": {"message": {"key1": "value1"}}}, "message.key1")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '-'
ret = extract_metadata_values({"message1": {"message": {"key1": {"key2": "value2"}... |
给定一个列表 bucket, 其中 bucket[i] 表示类别 i 的样本数量. 编写一个函数 entropy(bucket), 该函数计算列表 bucket 的熵. 熵是衡量数据集混乱程度的指标, 熵越高, 数据集的混乱程度越高. | entropy | import numpy as np
import math
def entropy(bucket):
bucket = np.array(bucket)
entro = 0
bucket_size = np.sum(np.array(bucket))
for i in range(bucket.shape[0]):
if bucket_size == 0:
continue
probs = bucket[i] / bucket_size
if probs == 0:
continue
... | Given a list `bucket` where `bucket[i]` represents the number of samples in category `i`. Write a function `entropy(bucket)` that calculates the entropy of the list `bucket`. Entropy is a measure of the disorder or randomness in the dataset; the higher the entropy, the more disordered the dataset. |
import ast
import numpy as np
def check():
ret = entropy([1, 1, 1, 1])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert np.isclose(ret, 2.0)
ret = entropy([1, 2, 3, 4])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert np.isclose(ret, 1.8464393446710154)
... |
给定一个整数列表和一个整数size, 编写一个函数make_text(blocks, size=3), 该函数将列表中的每个整数转换为字符, 并将它们合并成一个字符串. 每个整数都代表一个字符, 使用ASCII码进行转换. 例如, 整数65代表字符'A', 整数97代表字符'a'. 函数make_text(blocks, size=3)的输入是一个列表blocks和一个整数size, 输出是一个字符串text. | make_text | def make_text(blocks, size=3):
text = ''
text_tmp = ''
for i in range(len(blocks)):
tmp = str(blocks[i])
if i < len(blocks) - 1:
while len(tmp) < size:
tmp = '0' + tmp
text_tmp += tmp
text_tmp = [int(text_tmp[i * 2:(i + 1) * 2]) for i in range((len(
... | Given a list of integers and an integer size, write a function `make_text(blocks, size=3)` that converts each integer in the list into a character using ASCII code, and combines them into a string. Each integer represents a character, with integers 65 representing 'A', and 97 representing 'a', for example. The input to... |
import ast
import numpy as np
def check():
ret = make_text([410, 76, 798, 669, 8, 82, 797, 182, 657, 777, 737, 871])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == 'I love programming'
ret = make_text([100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200])
... |
给定一个字符串列表 token_list, 一个整数 start 和 end, 以及一个字符串 mention, 编写一个函数 token_pos_to_char_pos(token_list, start, end, mention), 该函数将 token_list 中从 start 到 end 的字符串转换为字符级别的位置, 并返回字符级别的起始和结束位置. 如果转换后的字符串与 mention 不一致, 则打印警告信息. | token_pos_to_char_pos | from typing import List
def token_pos_to_char_pos(token_list: List[str], start: int, end: int,
mention: str) ->List[int]:
char_start = len(' '.join(token_list[:start]))
char_start += 0 if start == 0 else 1
char_end = len(' '.join(token_list[:end]))
if ' '.join(token_list)[char_start:char_end] != ... | Given a list of strings `token_list`, an integer `start` and `end`, and a string `mention`, write a function `token_pos_to_char_pos(token_list, start, end, mention)`. This function converts the strings in `token_list` from positions `start` to `end` into character-level positions and returns the character-level start a... |
import ast
import numpy as np
def check():
ret = token_pos_to_char_pos(["Hello", "world"], 0, 1, "Hello")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[0, 5]'
ret = token_pos_to_char_pos(["I", "am", "a", "robot"], 2, 3, "a")
if isinstance(ret, np.ndarray):
... |
给定一个价格列表, 我们需要找到所有的峰值和谷值. 我们需要考虑每一个峰值紧接着一个谷值的情况. 总利润等于所有峰值减去谷值的差值. 用 python 定义函数 maxProfitPeakValley(prices) 解决这个问题. | maxProfitPeakValley | def maxProfitPeakValley(prices):
i = 0
price_len = len(prices) - 1
valley = prices[0]
peak = prices[0]
max_profit = 0
while i < price_len:
while i < price_len and prices[i] >= prices[i + 1]:
i += 1
valley = prices[i]
while i < price_len and prices[i] <= price... | Given a price list, we need to find all peaks and valleys. We need to consider each peak that is immediately followed by a valley. The total profit is equal to the sum of the differences between all peaks and their corresponding valleys. Define a Python function `maxProfitPeakValley(prices)` to solve this problem. |
import ast
import numpy as np
def check():
ret = maxProfitPeakValley([7,1,5,3,6,4])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '7'
ret = maxProfitPeakValley([1,2,3,4,5])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '4'
r... |
输入一个单词列表, 构建一个 trigrams 字典. 字典的键是单词对, 值是后续单词的列表. 用 python 定义函数 build_trigrams(words) 解决这个问题. | build_trigrams | def build_trigrams(words):
trigrams = {}
for i in range(len(words) - 2):
curr_word = words[i]
next_word = words[i + 1]
next1_word = words[i + 2]
key = curr_word, next_word
if key in trigrams:
trigrams[key].append(next1_word)
else:
trigrams... | Input a list of words, construct a trigrams dictionary. The keys of the dictionary are word pairs, and the values are lists of subsequent words. Define a function build_trigrams(words) in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = build_trigrams([])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert ret == {}
ret = build_trigrams(["a"])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert ret == {}
ret = build_trigrams(["a", "b"])
if ... |
输入一个二维列表, 表示一个方阵, 求出该方阵的主对角线元素和副对角线元素的和. 用 python 定义函数 diagonal_sum(mat) 解决这个问题. | diagonal_sum | def diagonal_sum(mat):
left = 0
right = 0
for i in range(0, len(mat)):
left += mat[i][i]
right += mat[i][len(mat) - i - 1]
total = left + right
if len(mat) % 2 != 0:
return total - mat[len(mat) // 2][len(mat) // 2]
return total
| Enter a two-dimensional list representing a square matrix and calculate the sum of the main diagonal elements and the secondary diagonal elements of the matrix. Define the Python function `diagonal_sum(mat)` to solve this problem. |
import ast
import numpy as np
def check():
ret = diagonal_sum([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '25'
ret = diagonal_sum([[1, 2], [3, 4]])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) ... |
给定一个一维的 numpy 数组 obs 和一个可选的权重数组 weights, 计算加权经验分布函数. 如果 weights 为 None, 则每个点权重为 1/len(obs). 返回排序后的唯一观测值 sorted_unique_obs 和加权经验分布函数 weighted_edf 在 sorted_unique_obs 中的值. 用 python 定义函数 compute_weighted_edf(obs, weights=None) 解决这个问题. | compute_weighted_edf | import numpy as np
def compute_weighted_edf(obs, weights=None):
if weights is None:
weights = np.ones(len(obs))
weights /= weights.shape[0]
sorted_unique_obs = np.sort(np.unique(obs))
obs_to_idx = {obs: idx for idx, obs in enumerate(sorted_unique_obs)}
weighted_edf = np.zeros(len(sort... | Given a one-dimensional numpy array `obs` and an optional weight array `weights`, calculate the weighted empirical distribution function. If `weights` is `None`, each point's weight is `1/len(obs)`. Return the sorted unique observations `sorted_unique_obs` and the values of the weighted empirical distribution function ... |
import ast
import numpy as np
def check():
ret = compute_weighted_edf(np.array([1, 2, 3, 4, 5]), None)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '(array([1, 2, 3, 4, 5]), array([0.2, 0.4, 0.6, 0.8, 1. ]))'
ret = compute_weighted_edf(np.array([1, 2, 2, 3, 3, 3, 4, ... |
给定一个点云, 使用 python 定义一个函数 compute_plane(points), 该函数计算出一个平面. 点云是一个大小为 3 x 3 的 numpy 数组, 表示平面上的点. 函数返回两个 numpy 数组, 一个是大小为 3 x 1 的参考点, 另一个是大小为 3 x 1 的平面法向量. | compute_plane | import numpy as np
def compute_plane(points):
point = points[0].reshape((3, 1))
normal = np.cross(points[1] - point.T, points[2] - point.T).reshape((3, 1))
return point, normal / np.linalg.norm(normal)
| Given a point cloud, define a function compute_plane(points) in Python that calculates a plane. The point cloud is a 3 x 3 numpy array representing points on the plane. The function returns two numpy arrays: one is a 3 x 1 reference point, and the other is a 3 x 1 plane normal vector. |
import ast
import numpy as np
def check():
ret = compute_plane(np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]))
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '(array([[1],\n [0],\n [0]]), array([[0.57735027],\n [0.57735027],\n [0.57735027]]))'
ret ... |
给定一个二维数组 features_ranking, 其中每一行包含一个排序好的投票, 以及一个整数 req_winners, 表示应该返回多少个赢家. 使用 max 方法, 返回赢家. 用 python 定义函数 voting_max(features_ranking, req_winners) 解决这个问题. | voting_max | import numpy as np
def voting_max(features_ranking, req_winners):
max_array = np.zeros(len(features_ranking[0]))
for i in np.arange(len(features_ranking[0])):
max_array[i] = features_ranking[:, i].max()
fs_winners = max_array.argsort()
return fs_winners[0:req_winners]
| Given a two-dimensional array `features_ranking`, where each row contains a sorted vote, and an integer `req_winners` representing how many winners should be returned. Use the `max` method to return the winners. Define the function `voting_max(features_ranking, req_winners)` in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = voting_max(np.array([[1, 2, 3], [2, 3, 1], [3, 1, 2]]), 2)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[0, 1]'
ret = voting_max(np.array([[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]]), 3)
if isinstance... |
定义一个函数 as_torch_type(type_string: str) -> torch.dtype, 这个函数接收一个字符串类型的数据类型, 比如 'int32', 然后返回对应的 torch 数据类型. 如果输入的字符串不在支持的类型列表中, 就抛出一个 ValueError 异常. | as_torch_type | import torch
def as_torch_type(type_string: str) ->torch.dtype:
type_map = {'int': torch.int, 'int8': torch.int8, 'int16': torch.int16,
'int32': torch.int32, 'int64': torch.int64, 'double': torch.double,
'float': torch.float, 'float16': torch.float16, 'float32': torch.
float32, 'float64':... | Define a function `as_torch_type(type_string: str) -> torch.dtype`. This function takes a string representing a data type, such as 'int32', and returns the corresponding torch data type. If the input string is not in the list of supported types, it should raise a `ValueError` exception. |
import ast
import numpy as np
def check():
ret = as_torch_type("int")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == 'torch.int32'
ret = as_torch_type("int8")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == 'torch.int8'
ret = a... |
给定一个字符串, 判断是否可以重新排列其中的字符形成一个回文串. 用 python 定义函数 palindromeRearranging(inputString) 解决这个问题. | palindromeRearranging | def palindromeRearranging(inputString):
codes = [(0) for i in range(256)]
for s in inputString:
codes[ord(s)] += 1
foundOdd = False
for i in range(len(codes)):
if codes[i] % 2 == 1:
if foundOdd:
return False
foundOdd = True
return True
| Given a string, determine whether its characters can be rearranged to form a palindrome. Define a function `palindromeRearranging(inputString)` in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = palindromeRearranging("")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == 'True'
ret = palindromeRearranging("a")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == 'True'
ret = pali... |
给定一个三维的 numpy 数组 volume, 以及一个整数 axis 和 slice_location, 编写一个名为 volume_reslice(volume, axis, slice_location) 的函数, 该函数根据给定的 axis 和 slice_location 创建一个新的二维切片. 如果 axis 为 0, 则切片是沿着 z 轴 (axial) 的, 如果 axis 为 1, 则切片是沿着 y 轴 (sagittal) 的, 如果 axis 为 2, 则切片是沿着 x 轴 (coronal) 的. 返回创建的切片. | volume_reslice | import numpy as np
def volume_reslice(volume, axis, slice_location):
if axis == 0:
res_slice = volume[slice_location, :, :]
elif axis == 1:
res_slice = np.rot90(volume[:, slice_location, :])
elif axis == 2:
res_slice = np.rot90(volume[:, :, slice_location])
return res_slice
| Given a three-dimensional numpy array `volume`, and two integers `axis` and `slice_location`, write a function named `volume_reslice(volume, axis, slice_location)` that creates a new two-dimensional slice based on the given `axis` and `slice_location`. If `axis` is 0, the slice is along the z-axis (axial). If `axis` is... |
import ast
import numpy as np
def check():
ret = volume_reslice(np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]], [[19, 20, 21], [22, 23, 24], [25, 26, 27]]]), 0, 1)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[[10, 11, 12], [13, ... |
输入一个字符串, 表示 DNA 序列, 其中包含字符 'A', 'T', 'G', 'C'.
定义一个函数 get_complementary_sequence(sequence), 返回与输入序列互补的序列.
互补的规则是: 'A' 和 'T' 互补, 'C' 和 'G' 互补.
例如:
get_complementary_sequence('A') 应该返回 'T'
get_complementary_sequence('C') 应该返回 'G' | get_complementary_sequence | def get_complementary_sequence(sequence):
seq = ''
for char in sequence:
if char == 'A':
seq = seq + 'T'
if char == 'T':
seq = seq + 'A'
if char == 'G':
seq = seq + 'C'
if char == 'C':
seq = seq + 'G'
return seq
| Input a string that represents a DNA sequence, which contains the characters 'A', 'T', 'G', 'C'. Define a function get_complementary_sequence(sequence) that returns the complementary sequence to the input sequence. The complementary rules are: 'A' complements with 'T', and 'C' complements with 'G'. For example:
get_com... |
import ast
import numpy as np
def check():
ret = get_complementary_sequence("")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == ''
ret = get_complementary_sequence("A")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == 'T'
ret = g... |
给定一个非负整数列表 walls, 表示一组墙的高度. 计算这些墙在下雨后可以保留多少水. 雨水会从较低的墙流向较高的墙. 用 python 定义函数 rain(walls) 解决这个问题. | rain | def rain(walls):
n = len(walls)
res = 0
for i in range(1, n - 1):
left = walls[i]
for j in range(i):
left = max(left, walls[j])
right = walls[i]
for j in range(i + 1, n):
right = max(right, walls[j])
res = res + (min(left, right) - walls[i])
... | Given a list of non-negative integers `walls` representing the heights of a group of walls, calculate how much water these walls can retain after raining. The rainwater will flow from lower walls to higher walls. Define a function `rain(walls)` in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = rain([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '6'
ret = rain([2, 0, 0, 1, 0, 2, 0, 1])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '8'... |
编写一个名为 clean_lines 的函数, 该函数接收一个字符串列表 vm_lines 作为输入, 并返回一个新的字符串列表 new_lines. 该函数的目的是清理列表中的每一行, 即将每一行中的注释 ("//") 删除. 如果一行是空的或者以注释开始, 那么该行将被忽略. | clean_lines | def clean_lines(vm_lines):
new_lines = []
for i in range(len(vm_lines)):
line = vm_lines[i].strip()
comment_start = line.find('//')
if line == '' or comment_start == 0:
continue
elif comment_start > 0:
line = line[:comment_start]
new_lines.append(... | Create a function named `clean_lines` that takes a list of strings `vm_lines` as input and returns a new list of strings `new_lines`. The purpose of this function is to clean each line in the list by removing any comments ("//"). If a line is empty or starts with a comment, it will be ignored. |
import ast
import numpy as np
def check():
ret = clean_lines([])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[]'
ret = clean_lines(["// This is a comment"])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[]'
ret = clean_l... |
给定两个列表 x 和 y, 其中 y 是 x 的标签. 我们需要根据一个分割点 split_point 将 y 列表分成两个列表. 第一个列表包含所有小于等于分割点的 x 对应的标签, 第二个列表包含所有大于分割点的 x 对应的标签. 用 python 定义函数 partition_classes(x, y, split_point) 解决这个问题. | partition_classes | def partition_classes(x, y, split_point):
left = []
right = []
for i in range(len(x)):
if x[i] <= split_point:
left.append(y[i])
if x[i] > split_point:
right.append(y[i])
return left, right
| Given two lists x and y, where y contains the labels for x, we need to split the y list into two lists based on a split point. The first list should contain all labels from y corresponding to x values that are less than or equal to the split point, and the second list should contain all labels from y corresponding to x... |
import ast
import numpy as np
def check():
ret = partition_classes([], [], 5)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '([], [])'
ret = partition_classes([2,4,6,7,3,7,9], [1,1,1,0,1,0,0], 5)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
asser... |
给定一个元素集合和一个值函数, 选择值最高的 len_query 个元素. 如果 always_included 不为 None, 那么 always_included 中的元素也应该被包含在结果中. 如果 always_included 中的元素不在 best 中, 那么用 always_included 中的元素替换 best 中的元素. 用 python 定义函数 best_selection(selection_elements, val, len_query, always_included) 解决这个问题.
| best_selection | def best_selection(selection_elements: list, val: list, len_query: int,
always_included=None) ->list:
always_included = always_included or []
n = len_query
elem_val = dict(zip(selection_elements, val))
best = sorted(selection_elements, key=elem_val.get, reverse=True)[0:n]
replacements = [item f... | Given a set of elements and a value function, select the top len_query elements with the highest values. If always_included is not None, the elements in always_included should also be included in the result. If the elements in always_included are not among the best, replace the elements in the best selection with the o... |
import ast
import numpy as np
def check():
ret = best_selection(["a", "b", "c"], [1, 2, 3], 2, ["a"])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == "['c', 'a']"
ret = best_selection(["a", "b", "c"], [3, 2, 1], 1, ["b"])
if isinstance(ret, np.ndarray):
ret ... |
输入一个整数列表, 如果列表中的奇数比偶数多, 返回字符串 "odds win", 如果偶数比奇数多, 返回字符串 "evens win", 如果两者数量相等, 返回字符串 "tie". 用 python 定义函数 battle(soldiers) 解决这个问题. | battle | def battle(soldiers):
odds = evens = 0
for num in soldiers:
bits = bin(num).count(str(num % 2))
if num % 2 == 0:
bits -= 1
evens = evens + bits if num > 0 else evens - bits
else:
odds = odds + bits if num > 0 else odds - bits
if odds > evens:
... | Define a function `battle(soldiers)` in Python that takes a list of integers as input. If the list contains more odd numbers than even numbers, return the string "odds win". If there are more even numbers than odd numbers, return the string "evens win". If the quantities are equal, return the string "tie". |
import ast
import numpy as np
def check():
ret = battle([1, 2, 3, 4, 5])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == 'odds win'
ret = battle([2, 4, 6, 8, 10])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == 'evens win'
ret =... |
输入一个整数列表, 使用插入排序算法对列表进行排序. 用 python 定义函数 insertion_sort(nums) 解决这个问题. | insertion_sort | def insertion_sort(nums):
for i in range(1, len(nums)):
index = i
while nums[index] < nums[index - 1] and index > 0:
nums[index - 1], nums[index] = nums[index], nums[index - 1]
index -= 1
return nums
| Input a list of integers and use the insertion sort algorithm to sort the list. Define the function insertion_sort(nums) in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = insertion_sort([])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[]'
ret = insertion_sort([1])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[1]'
ret = insertion_sort([3, 2,... |
输入一个三维矩阵, 其中第一个维度表示帧数, 第二个和第三个维度表示视频的宽度和高度.
你的任务是将这个三维矩阵重塑为一个二维矩阵, 其中每一行表示一个像素, 每一列表示一个帧.
像素的顺序应该保持与视频的光栅扫描顺序一致. 用 python 定义函数 video_raster_reshape(vid) 解决这个问题. | video_raster_reshape | import numpy as np
def video_raster_reshape(vid):
vid = np.swapaxes(vid, 0, 2)
vid = np.swapaxes(vid, 0, 1)
n_pixels = vid.shape[0] * vid.shape[1]
n_frames = vid.shape[2]
matrix = vid.reshape((n_pixels, n_frames))
return matrix
| Input a three-dimensional matrix where the first dimension represents the frame count, and the second and third dimensions represent the video's width and height.
Your task is to reshape this three-dimensional matrix into a two-dimensional matrix where each row represents a pixel, and each column represents a frame.
Th... |
import ast
import numpy as np
def check():
ret = video_raster_reshape(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]))
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[[1, 7], [2, 8], [3, 9], [4, 10], [5, 11], [6, 12]]'
ret = video_raster_reshape(np.array... |
定义一个函数 parse_params(event), 这个函数接收一个字典 event 作为输入,
如果 event 中存在 'body' 键, 那么就把 event['body'] 的值解析为 json 格式,
否则直接使用 event 作为解析后的字典. 然后从解析后的字典中获取 'feed_source', 'base_url', 'feed_url', 'feed_name' 的值,
并返回一个包含这四个值的元组. | parse_params | import json
def parse_params(event):
if 'body' in event.keys():
params_dict = json.loads(event['body'])
else:
params_dict = event
feed_source = params_dict['feed_source']
base_url = params_dict['base_url']
feed_url = params_dict['feed_url']
feed_name = params_dict['feed_name']... | Define a function `parse_params(event)`, which receives a dictionary `event` as input. If the `event` contains the key 'body', parse the value of `event['body']` as JSON format. Otherwise, use `event` directly as the parsed dictionary. Then, retrieve the values of 'feed_source', 'base_url', 'feed_url', and 'feed_name' ... |
import ast
import numpy as np
def check():
ret = parse_params({"feed_source": "source1", "base_url": "url1", "feed_url": "feed1", "feed_name": "name1"})
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == "('source1', 'url1', 'feed1', 'name1')"
ret = parse_params({"feed_sou... |
给定两个相机内参矩阵 K1 和 K2, 以及一个旋转矩阵 R 和一个平移向量 t, 计算两个相机的投影矩阵 P1 和 P2. 投影矩阵的形状为 3x4. 使用 python 定义函数 camera_matrices(K1, K2, R, t) 解决这个问题. | camera_matrices | import numpy as np
def camera_matrices(K1, K2, R, t):
PI = np.zeros((3, 4))
PI[:, :3] = np.eye(3)
P1 = K1 @ PI
PI2 = np.empty((3, 4))
PI2[:, :3] = R[:, :]
PI2[:, 3] = t[:]
P2 = K2 @ PI2
return P1, P2
| Given two camera intrinsic matrices K1 and K2, a rotation matrix R, and a translation vector t, compute the projection matrices P1 and P2 for the two cameras. The shape of the projection matrices is 3x4. Define a function camera_matrices(K1, K2, R, t) in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = camera_matrices(K1=np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), K2=np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), R=np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), t=np.array([0, 0, 0]))
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret... |
定义一个名为 minOperations 的函数, 该函数接收一个整数 n 作为输入, 并返回一个整数. 如果 n 小于 2, 则返回 0. 否则, 函数会计算出一个操作数, 该操作数是将 n 除以一个从 2 开始的连续整数, 直到 n 小于该整数. 这个操作数会被累加, 并且 n 会被更新为除以该整数的结果. 这个过程会一直持续, 直到 n 小于当前的整数. 最后, 函数会返回这个操作数. | minOperations | def minOperations(n) ->int:
if n < 2:
return 0
operations, root = 0, 2
while root <= n:
if n % root == 0:
operations += root
n = n / root
root -= 1
root += 1
return operations
| Define a function named minOperations that takes an integer n as input and returns an integer. If n is less than 2, return 0. Otherwise, the function calculates an operation count, which involves dividing n by consecutive integers starting from 2 until n is less than that integer. This operation count will be accumulat... |
import ast
import numpy as np
def check():
ret = minOperations(0)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '0'
ret = minOperations(1)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '0'
ret = minOperations(2)
if isins... |
输入一个0-259的整数, 表示手指的阶段. 如果把这个函数画出来, 它就是每个手指运动的图形.
这个函数的返回值是:
angle: 手指步开始位置的偏移角度
z: 从地球平面上的高度偏移
用 python 定义函数 finger_path(phase) 解决这个问题. | finger_path | from math import radians
from math import cos
def finger_path(phase):
stepHeight = 40
if 0 <= phase <= 215:
angle = phase / 215
z = 0
elif 215 < phase < 360:
angle = -phase / 145 + 72 / 29
z = stepHeight / 2 * cos(radians(phase - 215) / 0.4) - stepHeight / 2
else:
... | Enter an integer from 0 to 259, representing the phase of the finger. If you plot this function, it would be the movement graph for each finger. The return values of this function are:
angle: The offset angle from the starting position of the finger step
z: The height offset from the Earth's plane
Define a Pyt... |
import ast
import numpy as np
def check():
ret = finger_path(0)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '(0.0, 0)'
ret = finger_path(215)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '(1.0, 0)'
ret = finger_path(216)
... |
给定一个字符串数组, 编写一个函数来反转这个字符串. 不能为另一个数组分配额外的空间, 必须通过修改输入数组来原地进行操作, 使用 O(1) 的额外内存. 你可以假设所有的字符都是可打印的 ASCII 字符. 用 python 定义函数 reverseString(chars) 解决这个问题. | reverseString | def reverseString(chars):
p1 = 0
p2 = len(chars) - 1
while p1 < p2:
chars[p1], chars[p2] = chars[p2], chars[p1]
p1 += 1
p2 -= 1
return chars
| Given a string array, write a function to reverse this string. You cannot allocate extra space for another array; you must modify the input array in place using O(1) extra memory. You can assume all the characters are printable ASCII characters. Define the function `reverseString(chars)` in Python to solve this problem... |
import ast
import numpy as np
def check():
ret = reverseString([])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[]'
ret = reverseString(['a'])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == "['a']"
ret = reverseString(['a',... |
定义一个函数 parse_chunk_header_file_range(file_range), 这个函数接收一个字符串 file_range, 这个字符串的格式是 "<start line number>,<number of lines changed>". 这个函数的任务是解析这个字符串, 并返回一个元组 (range_start, range_end). 这个元组的起始点和结束点是根据改变的索引进行调整的, 这样迭代 [range_start, range_end) 就可以得到改变的索引. | parse_chunk_header_file_range | def parse_chunk_header_file_range(file_range):
if ',' in file_range:
file_range_parts = file_range.split(',')
start = int(file_range_parts[0])
amount = int(file_range_parts[1])
if amount == 0:
return start, start
return start - 1, start + amount - 1
else:
... | Define a function `parse_chunk_header_file_range(file_range)`, which takes a string `file_range`. The format of this string is "<start line number>,<number of lines changed>". The task of this function is to parse this string and return a tuple `(range_start, range_end)`. The start and end points of this tuple are adju... |
import ast
import numpy as np
def check():
ret = parse_chunk_header_file_range("1,0")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '(1, 1)'
ret = parse_chunk_header_file_range("1,1")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) =... |
给定一个列表和一个值, 使用二分查找在列表中找到值的位置. 列表中的元素和值之间的关系是二元的, 并且元素根据值的值有一定的顺序. 用 python 定义函数 binary_search_index(sequence: list, value: any, key: Callable=lambda x: x, ascending: bool=True) 解决这个问题. | binary_search_index | from typing import Callable
def binary_search_index(sequence: list, value: any, key: Callable=lambda x:
x, ascending: bool=True):
i, j = 0, len(sequence)
while i < j:
m = (i + j) // 2
if (not ascending) ^ (key(sequence[m]) <= value):
i = m + 1
else:
j = m
... | Given a list and a value, use binary search to find the position of the value in the list. The relationship between the elements in the list and the value is binary, and the elements are ordered according to the value. Define a function in Python called `binary_search_index(sequence: list, value: any, key: Callable=lam... |
import ast
import numpy as np
def check():
ret = binary_search_index([1, 2, 3, 4, 5], 3, lambda x: x, True)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '3'
ret = binary_search_index([5, 4, 3, 2, 1], 3, lambda x: x, False)
if isinstance(ret, np.ndarray):
... |
定义一个函数 extract_count(data), 该函数接收一个列表 data, 列表中的每个元素都是一个包含多个元素的列表.
函数需要从每个元素中提取出第4, 5, 6个元素, 并将它们转换为浮点数后存储在三个单独的列表中.
函数返回这三个列表. | extract_count | def extract_count(data):
forward_count_data = list()
comment_count_data = list()
like_count_data = list()
for element in data:
forward_count_data.append(float(element[4]))
comment_count_data.append(float(element[5]))
like_count_data.append(float(element[6]))
return forward_c... | Define a function `extract_count(data)`, which takes a list `data` as input, where each element in the list is itself a list containing multiple elements. The function needs to extract the 4th, 5th, and 6th elements from each inner list, convert them to float, and store them in three separate lists. The function return... |
import ast
import numpy as np
def check():
ret = extract_count([["a", "b", "c", "d", "1.0", "2.0", "3.0"], ["e", "f", "g", "h", "4.0", "5.0", "6.0"]])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '([1.0, 4.0], [2.0, 5.0], [3.0, 6.0])'
ret = extract_count([["i", "j", ... |
编写一个名为 dict_to_str 的函数, 该函数接收一个字典 some_dict 和一个可选的前缀 prefix, 并返回一个字符串. 该字符串是根据 some_dict 的键值对生成的, 并且键值对的顺序是按照键的字典序排序的. 如果提供了前缀, 则在字符串的开头添加前缀. 例如, 如果 some_dict 是 {'b': 2, 'a': 1} 并且 prefix 是 'prefix_', 那么返回的字符串应该是 'prefix_a=1|b=2'. | dict_to_str | def dict_to_str(some_dict, prefix=''):
keys_sorted = sorted(some_dict.keys())
parts = [prefix]
for k in keys_sorted:
parts.append('|')
parts.append(str(k))
parts.append('=')
parts.append(str(some_dict[k]))
return ''.join(parts)
| Write a function named `dict_to_str` that takes a dictionary `some_dict` and an optional prefix `prefix`, and returns a string. The string is generated based on the key-value pairs from `some_dict`, and the order of the key-value pairs is sorted according to the dictionary order of the keys. If a prefix is provided, it... |
import ast
import numpy as np
def check():
ret = dict_to_str({}, "")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == ''
ret = dict_to_str({"a": 1}, "prefix")
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == 'prefix|a=1'
ret = dic... |
定义一个函数 adjust_color(color, lightness_factor=1.0, saturation_factor=1.0,
lightness_value=None, saturation_value=None), 这个函数可以改变颜色的亮度和饱和度. 输入可以是 matplotlib 颜色字符串, 十六进制字符串, 或者 RGB 元组.
例如:
>> adjust_color('g', 0.3)
>> adjust_color('#F034A3', 0.6)
>> adjust_color((.3,.55,.1), 0.5) | adjust_color | import colorsys
import matplotlib.colors as mc
def adjust_color(color, lightness_factor=1.0, saturation_factor=1.0,
lightness_value=None, saturation_value=None):
try:
c = mc.cnames[color]
except:
c = color
c = colorsys.rgb_to_hls(*mc.to_rgb(c))
if lightness_value is not None:
... | Define a function adjust_color(color, lightness_factor=1.0, saturation_factor=1.0, lightness_value=None, saturation_value=None). This function can change the lightness and saturation of a color. The input can be a matplotlib color string, a hexadecimal string, or an RGB tuple. For example:
>> adjust_color('g', 0.3)
>> ... |
import ast
import numpy as np
def check():
ret = adjust_color('g', 0.3, 0.6, None, None)
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '(0.06375, 0.08625, 0.06375)'
ret = adjust_color('#F034A3', 0.6, 0.6, None, None)
if isinstance(ret, np.ndarray):
ret = r... |
输入一个列表的列表, 每个列表代表一行歌词. 删除空行, 并返回缺失歌词的索引. 用 python 定义函数 process_missing_lyrics(sentences) 解决这个问题. | process_missing_lyrics | def process_missing_lyrics(sentences):
missing_lyric_indices = []
for i in range(len(sentences)):
line = sentences[i]
if len(line) == 0:
missing_lyric_indices.append(i)
for i in range(len(missing_lyric_indices)):
sentences.remove([])
return [int(item) for item in mis... | Input a list of lists, each list representing a line of lyrics. Remove empty lines and return the indices of the missing lyrics. Define a function `process_missing_lyrics(sentences)` in Python to solve this problem. |
import ast
import numpy as np
def check():
ret = process_missing_lyrics([["I", "am", "a", "song"], ["", "", "", ""], ["I", "am", "a", "song"]])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[]'
ret = process_missing_lyrics([["I", "am", "a", "song"], ["", "", "", ""],... |
输入一个矩阵 A, 如果 A 是上三角矩阵, 返回 True, 否则返回 False. 用 python 定义函数 is_echelon(A) 解决这个问题. | is_echelon | def is_echelon(A):
k = -1
for r in A:
for i, j in enumerate(r):
if j != 0:
if i <= k:
return False
else:
k = i
break
if i + 1 == len(r):
k = i
return True
| Input a matrix A, if A is an upper triangular matrix, return True, otherwise return False. Define a function is_echelon(A) using Python to solve this problem. |
import ast
import numpy as np
def check():
ret = is_echelon([[1,1,1],[0,1,1],[0,0,1]])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == 'True'
ret = is_echelon([[0,1,1],[0,1,0],[0,0,1]])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) =... |
实现一个名为 insertion_sort 的函数, 它接受一个数字列表作为输入, 并返回一个新的列表, 该列表是输入列表的排序版本. 使用插入排序算法对列表进行排序, 插入排序算法的时间复杂度为 Theta(n^2). 用 python 编写这个函数. | insertion_sort | def insertion_sort(list_to_sort):
for i in range(len(list_to_sort)):
mem = list_to_sort[i]
j = i - 1
while j >= 0 and list_to_sort[j] > mem:
list_to_sort[j + 1] = list_to_sort[j]
j -= 1
list_to_sort[j + 1] = mem
return list_to_sort
| Implement a function named `insertion_sort` that takes a list of numbers as input and returns a new list, which is a sorted version of the input list. Use the insertion sort algorithm to sort the list, and note that the time complexity of the insertion sort algorithm is Theta(n^2). Write this function in Python. |
import ast
import numpy as np
def check():
ret = insertion_sort([])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[]'
ret = insertion_sort([1])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[1]'
ret = insertion_sort([2, 1]... |
给定一个整数列表, 编写一个名为 get_median_score 的函数, 该函数返回列表中所有整数的中位数. 如果列表为空, 返回 0. 如果列表只有一个元素, 返回该元素. 如果列表有奇数个元素, 返回中间的元素. 如果列表有偶数个元素, 返回中间两个元素的平均值. | get_median_score | def get_median_score(lst_param):
if not isinstance(lst_param, list):
print('List argument expected')
return -1
elif len(lst_param) == 0:
return 0
elif len(lst_param) == 1:
return lst_param[0]
elif len(lst_param) % 2 == 1:
copy = lst_param[:]
copy.sort()
... | Given a list of integers, write a function named get_median_score that returns the median of all the integers in the list. If the list is empty, return 0. If the list has only one element, return that element. If the list has an odd number of elements, return the middle element. If the list has an even number of elemen... |
import ast
import numpy as np
def check():
ret = get_median_score([])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '0'
ret = get_median_score([1])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '1'
ret = get_median_score([1,... |
给定一个二维矩阵 H, 其中每个元素都是 0 或 1. 定义一个函数 calc_min_dist(H), 该函数计算矩阵 H 中所有行向量中 1 的最小数量. 如果没有满足条件的行向量, 返回 None.
例如, 给定矩阵 H = [[1, 1, 1, 1, 0], [0, 0, 1, 0, 1]], 函数 calc_min_dist(H) 应该返回 2. | calc_min_dist | import numpy as np
def calc_min_dist(H):
r, n = H.shape
wmin = None
for i in range(1, 2 ** n):
vi = np.unpackbits(np.array([i], np.int64).view(np.uint8).reshape(-
1, 1), axis=-1)[:, ::-1].ravel()[:n]
if not np.all(np.dot(H, vi) % 2 == 0):
continue
w = np.su... | Given a 2D matrix H where each element is either 0 or 1, define a function calc_min_dist(H) that calculates the minimum number of 1s in any row vector of matrix H. If no row vectors meet the condition, return None.
For example, given the matrix H = [[1, 1, 1, 1, 0], [0, 0, 1, 0, 1]], the function calc_min_dist(H) shou... |
import ast
import numpy as np
def check():
ret = calc_min_dist(np.array([[1, 1, 1, 1, 0], [0, 0, 1, 0, 1]], dtype=np.uint8))
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '2'
ret = calc_min_dist(np.array([[1, 0, 1, 0, 1], [0, 1, 0, 1, 0]], dtype=np.uint8))
if isin... |
定义一个函数 accepts_hat(letter), 这个函数接收一个字母作为参数, 判断这个字母是否可以接受一个帽子 (accent)。例如, 'c' 可以接受一个帽子 (ĉ)。如果字母是 'c', 'g', 'h', 'j', 's', 或者 'u' 中的一个, 函数返回 True, 否则返回 False。 | accepts_hat | def accepts_hat(letter):
if (letter == 'c' or letter == 'C' or letter == 'g' or letter == 'G' or
letter == 'h' or letter == 'H' or letter == 'j' or letter == 'J' or
letter == 's' or letter == 'S' or letter == 'u' or letter == 'U'):
return True
return False
| Define a function `accepts_hat(letter)`. This function receives a letter as a parameter and determines if the letter can accept a hat (accent). For example, 'c' can accept a hat (ĉ). If the letter is one of 'c', 'g', 'h', 'j', 's', or 'u', the function returns True, otherwise it returns False. |
import ast
import numpy as np
def check():
ret = accepts_hat('c')
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == 'True'
ret = accepts_hat('C')
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == 'True'
ret = accepts_hat('g')
if... |
输入一个数字列表, 将列表中的数字顺序向下移动一位. 用 python 定义函数 shiftOrder(order) 解决这个问题. | shiftOrder | def shiftOrder(order):
new = [x for x in range(len(order))]
for i in range(len(order)):
if i == len(order) - 1:
new[0] = order[i]
else:
new[i + 1] = order[i]
return new
| Enter a list of numbers, shift the order of the numbers in the list down by one position. Define a function in Python called `shiftOrder(order)` to solve this problem. |
import ast
import numpy as np
def check():
ret = shiftOrder([1, 2, 3, 4, 5])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[5, 1, 2, 3, 4]'
ret = shiftOrder([5, 4, 3, 2, 1])
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '[1, 5,... |
定义一个名为 in_thirds 的函数, 该函数接收一个包含 10 个元素的元组作为参数, 并返回一个新的元组, 其中包含原始元组的最后一个三分之一, 第一个三分之一和中间三分之一的元素, 但顺序是最后一个三分之一, 第一个三分之一和中间三分之一. | in_thirds | def in_thirds(sequence):
size = len(sequence)
third = int(size * 0.33)
first_third = sequence[0:third]
length = len(first_third)
middle_third = sequence[length:-length]
two_lengths = length * 2
last_third = sequence[two_lengths:-1]
return last_third + first_third + middle_third
| Define a function named `in_thirds`, which takes a tuple containing 10 elements as a parameter and returns a new tuple. The new tuple should include the last third, the first third, and the middle third of the original tuple's elements, in that order. |
import ast
import numpy as np
def check():
ret = in_thirds((1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '(7, 8, 9, 1, 2, 3, 4, 5, 6, 7)'
ret = in_thirds(('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'))
if isinstance(ret, np.nda... |
输入两个 numpy 数组 X 和 C. X 是一个形状为 (n, d) 的二维数组, 包含数据集. C 是一个形状为 (k, d) 的二维数组, 包含每个聚类的质心均值. 你不允许使用任何循环. 返回 var, 如果失败则返回 None. var 是总的方差. 用 python 定义函数 variance(X, C) 解决这个问题. | variance | import numpy as np
def variance(X, C):
if type(X) is not np.ndarray or len(X.shape) != 2:
return None
if type(C) is not np.ndarray or len(C.shape) != 2:
return None
try:
return np.square(np.apply_along_axis(np.subtract, 1, X, C)).sum(axis=2
).min(axis=1).sum()
exce... | Enter two numpy arrays X and C. X is a 2D array with shape (n, d) containing the dataset. C is a 2D array with shape (k, d) containing the mean of each cluster centroid. You are not allowed to use any loops. Return var, or None if it fails. var is the total variance. Define a function variance(X, C) in Python to solve ... |
import ast
import numpy as np
def check():
ret = variance(np.array([[1, 2], [3, 4]]), np.array([[1, 1], [2, 2]]))
if isinstance(ret, np.ndarray):
ret = ret.tolist()
assert str(ret) == '6'
ret = variance(np.array([[1, 2, 3], [4, 5, 6]]), np.array([[1, 1, 1], [2, 2, 2]]))
if isinstance(ret... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.