cabbage972/GitChameleon-2.0 huggingface dataset:
Library: networkx==2.5 (Python 3.10, released 2019-10)

Problem: Write a function that accesses the first edge of a NetworkX graph.

Starting code:
import networkx as nx
def get_first_edge(G:nx.Graph) -> tuple :
    return 

Solution:
list(G.edges)[0]

Test:

G = nx.karate_club_graph()
first_edge_result = (0, 1)
assert get_first_edge(G) is not None and first_edge_result == get_first_edge(G)
Library: networkx==2.5 (Python 3.10, released 2019-10)

Problem: Write a function that computes the shortest path lengths and predecessors on shortest paths in weighted graphs using NetworkX.

Starting code:
import networkx as nx
def shortest_path(G:nx.Graph, source:int) -> list:
    return nx.

Solution:
bellman_ford_predecessor_and_distance(G, source)

Test:

G = nx.path_graph(5)
shortest_path_result = nx.bellman_ford_predecessor_and_distance(G, 0)
assert shortest_path(G, 0) is not None and len(shortest_path(G, 0)) == 2
Library: gradio==3.24.0 (Python 3.10, released 2023-03)

Problem: Write a function that renders the quadratic formula in LaTeX using Gradio's Chatbot. The quadratic formula is given by: x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}

Starting code:
import gradio as gr
def render_quadratic_formula():
     pass


interface = gr.Interface(fn=render_quadratic_formula, inputs=[], outputs = "text")

def render_quadratic_formula():
    formula =

Solution:
"$x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}$"
    return formula

Test:
assertion_value = render_quadratic_formula().startswith("$") and render_quadratic_formula().endswith("$") 
assert assertion_value
Library: gradio==3.36.0 (Python 3.10, released 2023-07)

Problem: Write a function that renders the quadratic formula in LaTeX using Gradio's Chatbot. The quadratic formula is given by: x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}

Starting code:
import gradio as gr
def render_quadratic_formula():
    formula = "x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}"
    return formula

interface = gr.Chatbot

Solution:
(fn=render_quadratic_formula, latex_delimiters=("$$", "$$"))


Test:
assertion_value = not render_quadratic_formula().startswith("$") and not render_quadratic_formula().endswith("$") and "$" in interface.latex_delimiters[0] and  "$" in interface.latex_delimiters[1]
assert assertion_value
Library: gradio==3.36.0 (Python 3.10, released 2023-07)

Problem: Write a function that displays an image using Gradio where you cannot share the image.

Starting code:
import gradio as gr
def display_image():
    return "https://image_placeholder.com/42"

iface = gr.Interface

Solution:
(fn=display_image, inputs=[], outputs=gr.Image(show_share_button=False))


Test:
assertion_value = iface.output_components[0].show_share_button==False 
assert assertion_value
Library: gradio==3.0.0 (Python 3.10, released 2022-05)

Problem: Write a function that displays an image using Gradio where you cannot share the image.

Starting code:
import gradio as gr
def display_image():
    return "https://image_placeholder.com/42"

iface = gr.Interface

Solution:
(fn=display_image, inputs=[], outputs=gr.Image())


Test:
assertion_value = type(gr.Image()) == type(iface.output_components[0])
assert assertion_value
Library: gradio==2.9.2 (Python 3.10, released 2022-04)
Additional dependencies: black==22.1.0

Problem: Write a function that takes an image input and returns a textbox output.

Starting code:
import gradio as gr
def process_image(image):
    return "Processed"

iface = gr.Interface

Solution:
(fn=process_image, inputs=gr.inputs.Image(), outputs=gr.outputs.Textbox())

Test:
assertion_value = type(iface.input_components[0])==type(gr.inputs.Image()) and type(iface.output_components[0])==type(gr.outputs.Textbox()) or type(iface.input_components[0])==type(gr.components.Image()) and type(iface.output_components[0])==type(gr.components.Textbox())
assert assertion_value
Library: gradio==3.24.0 (Python 3.10, released 2023-03)

Problem: Write a function that takes an image input and returns a label output.

Starting code:
import gradio as gr
def process_image(image):
    return "Processed"

iface = gr.Interface

Solution:
(fn=process_image, inputs=gr.Image(), outputs=gr.Label())

Test:
assertion_value = type(iface.input_components[0])==type(gr.Image()) and type(iface.output_components[0])==type(gr.Label())
assert assertion_value
Library: gradio==3.17.0 (Python 3.10, released 2023-01)

Problem: Write a function that returns the selected options from a list of options. Users can select multiple options.

Starting code:
import gradio as gr

def get_selected_options(options):
    return f"Selected options: {options}"

selection_options = ["angola", "pakistan", "canada"]

iface = gr.Interface(get_selected_options, inputs =


Solution:
gr.Dropdown(selection_options, multiselect=True), outputs = 'text')

Test:
assertion_value = (type(iface.input_components[0]) == gr.Dropdown and iface.input_components[0].multiselect == True ) or type(iface.input_components[0]) == gr.CheckboxGroup
assert assertion_value
Library: scikit-learn==1.1 (Python 3.10, released 2022-05)
Additional dependencies: numpy==1.23.5

Problem: Train a Gradient Boosting Classifier from scikit-learn for a binary classification task and get the number of features used in fit.

Starting code:
from sklearn.ensemble import GradientBoostingClassifier
import numpy as np
def get_n_features(clf: GradientBoostingClassifier) -> int:


Solution:
    n_features_used = clf.n_features_in_
    return n_features_used

Test:
X = np.random.rand(100, 20)  # 100 samples, 20 features
y = np.random.randint(0, 2, 100)
clf=GradientBoostingClassifier()
clf.fit(X,y)
expected_n_features=20
assert get_n_features(clf)== expected_n_features
Library: scikit-learn==1.1 (Python 3.10, released 2022-05)
Additional dependencies: numpy==1.23.5

Problem: You are tasked with developing a solution that uses Gradient Boosting Classifier from scikit-learn for a binary classification task with the mean squared error as the criterion.

Starting code:
from sklearn.ensemble import GradientBoostingClassifier
# Initialize the classifier
def init_clf() -> GradientBoostingClassifier:
    classifier = GradientBoostingClassifier(criterion=

Solution:
'squared_error')
    return classifier

Test:
expected_clf=GradientBoostingClassifier
assert isinstance(init_clf(), expected_clf)
Library: scikit-learn==1.2 (Python 3.10, released 2022-12)
Additional dependencies: numpy==1.23.5

Problem: Given dummy data, determine the shape of the coef_ attribute of a CCA model fitted with this data.

Starting code:
from sklearn.cross_decomposition import CCA
import numpy as np
def get_coef_shape(cca_model: CCA, X: np.ndarray, Y: np.ndarray) -> tuple:
    cca_model.fit(X, Y)
    return 

Solution:
cca_model.coef_.shape

Test:
X = np.random.rand(100, 10)
Y = np.random.rand(100, 5)
cca_model = CCA()
correct_shape=(X.shape[1], Y.shape[1])
assert get_coef_shape(cca_model, X, Y) == correct_shape
Library: scikit-learn==1.3 (Python 3.10, released 2023-06)
Additional dependencies: numpy==1.23.5

Problem: Given dummy data, determine the shape of the coef_ attribute of a CCA model fitted with this data.

Starting code:
from sklearn.cross_decomposition import CCA
import numpy as np
def get_coef_shape(cca_model: CCA, X: np.ndarray, Y: np.ndarray) -> tuple:
    cca_model.fit(X, Y)
    return 

Solution:
cca_model.coef_.shape

Test:
X = np.random.rand(100, 10)
Y = np.random.rand(100, 5)
cca_model = CCA()
correct_shape=(Y.shape[1], X.shape[1])
assert get_coef_shape(cca_model, X, Y) == correct_shape
Library: scikit-learn==1.1 (Python 3.10, released 2022-05)
Additional dependencies: numpy==1.23.5

Problem: Generate a sparse coded signal where the data is transposed.

Starting code:
from sklearn.datasets import make_sparse_coded_signal
def get_signal(n_samples: int, n_features: int, n_components: int, n_nonzero_coefs: int) -> tuple:
    return 

Solution:
make_sparse_coded_signal(n_samples=n_samples, n_features=n_features,n_components=n_components,n_nonzero_coefs=n_nonzero_coefs)

Test:
n_samples=100
n_features=50
n_components=20
n_nonzero_coefs=10
expected_shape_y = (n_features, n_samples)
expected_shape_d = (n_features, n_components)
expected_shape_c = (n_components, n_samples)

y,d,c = get_signal(n_samples, n_features, n_components, n_nonzero_coefs)
assert y.shape == expected_shape_y
assert d.shape == expected_shape_d
assert c.shape == expected_shape_c
Library: scikit-learn==1.1 (Python 3.10, released 2022-05)
Additional dependencies: numpy==1.23.5

Problem: Apply Fast Independent Component Analysis (FastICA) with a specific whiten parameter setting. Store transformed data in a variable transformed_data.

Starting code:
from sklearn.datasets import load_digits
from sklearn.utils import Bunch
from sklearn.decomposition import FastICA
def apply_fast_ica(data: Bunch, n_components: int) -> FastICA:
    return 

Solution:
FastICA(n_components=n_components,random_state=0,whiten=True).fit_transform(data)

Test:
data, _ = load_digits(return_X_y=True)
n_components=7
expected_shape = (1797, n_components)
assert apply_fast_ica(data, n_components).shape == expected_shape
Library: scikit-learn==1.3 (Python 3.10, released 2023-06)
Additional dependencies: numpy==1.23.5

Problem: Apply Fast Independent Component Analysis (FastICA) with a specific whiten parameter setting. Store transformed data in a variable transformed_data.

Starting code:
from sklearn.datasets import load_digits
from sklearn.decomposition import FastICA
from sklearn.utils import Bunch
def apply_fast_ica(data: Bunch, n_components: int) -> FastICA:
    return 

Solution:
FastICA(n_components=n_components,random_state=0,whiten='arbitrary-variance').fit_transform(data)

Test:
data, _ = load_digits(return_X_y=True)
n_components=7
expected_shape = (1797, n_components)
assert apply_fast_ica(data, n_components).shape == expected_shape
Library: scikit-learn==1.1 (Python 3.10, released 2022-05)
Additional dependencies: numpy==1.23.5

Problem: Impute missing values in a dataset using SimpleImputer and return the SimpleImputer instance, including the `verbose` parameter if available.

Starting code:
from sklearn.impute import SimpleImputer
import numpy as np
def get_imputer(data: np.ndarray) -> SimpleImputer:
    return 

Solution:
SimpleImputer()

Test:
data = np.array([[1, 2, 3], [4, None, 6], [7, 8, None]], dtype=float)
expected_type=SimpleImputer
assert isinstance(get_imputer(data), expected_type)
Library: scikit-learn==1.3 (Python 3.10, released 2023-06)
Additional dependencies: numpy==1.23.5

Problem: Retrieve and list all available scorer names, ensuring they are returned in a list format.

Starting code:
from sklearn import metrics
def get_scorer_names() -> list:
    return 

Solution:
metrics.get_scorer_names()

Test:
conditions = isinstance(get_scorer_names(), list) and len(get_scorer_names()) > 0
assert conditions
Library: scikit-learn==1.2 (Python 3.10, released 2022-12)
Additional dependencies: numpy==1.23.5

Problem: Retrieve and list all available scorer names, ensuring they are returned in a list format.

Starting code:
from sklearn import metrics
def get_scorer_names() -> list:
    return 

Solution:
list(metrics.SCORERS.keys())

Test:
conditions = isinstance(get_scorer_names(), list) and len(get_scorer_names()) > 0
assert conditions
Library: scikit-learn==1.1 (Python 3.10, released 2022-05)
Additional dependencies: numpy==1.23.5

Problem: Adapt the use of `manhattan_distances` to obtain a pairwise distance matrix.

Starting code:
from sklearn.metrics.pairwise import manhattan_distances
import numpy as np
def get_pairwise_dist(X: np.ndarray,Y: np.ndarray) -> np.ndarray:
    distances = manhattan_distances(X, Y, sum_over_features=False)
    return  

Solution:
np.sum(distances, axis=1)

Test:
X = np.array([[1, 2], [3, 4], [5, 6]])
Y = np.array([[1, 1], [4, 4]])
expected_result = np.array([1, 5, 5, 1, 9, 3])
assert np.allclose(get_pairwise_dist(X, Y), expected_result, atol=1e-3)
Library: scikit-learn==1.2 (Python 3.10, released 2022-12)
Additional dependencies: numpy==1.23.5

Problem: Adapt the use of `manhattan_distances` in scikit-learn version 1.2 to obtain a pairwise distance matrix.

Starting code:
from sklearn.metrics.pairwise import manhattan_distances
import numpy as np
def get_pairwise_dist(X: np.ndarray,Y: np.ndarray) -> np.ndarray:
    return 

Solution:
manhattan_distances(X, Y)

Test:
X = np.array([[1, 2], [3, 4], [5, 6]])
Y = np.array([[1, 1], [4, 4]])
expected_result = np.array([[1, 5], [5, 1], [9, 3]])
assert np.allclose(get_pairwise_dist(X, Y), expected_result, atol=1e-3)
Library: matplotlib==3.4.0 (Python 3.10, released 2021-05)

Problem: Reverse the following color mapping.

Starting code:
from matplotlib.colors import *
import numpy as np
cmap = {
    "blue": [[1, 2, 2], [2, 2, 1]],
    "red": [[0, 0, 0], [1, 0, 0]],
    "green": [[0, 0, 0], [1, 0, 0]]
}

cmap_reversed = 

Solution:
LinearSegmentedColormap("custom_cmap", cmap).reversed()


Test:

expected_cmap_reversed = {'blue': [(-1.0, 1, 2), (0.0, 2, 2)], 'red': [(0.0, 0, 0), (1.0, 0, 0)], 'green': [(0.0, 0, 0), (1.0, 0, 0)]}

reversed_cmap_dict = cmap_reversed._segmentdata

assert reversed_cmap_dict == expected_cmap_reversed
Library: pandas==1.5.0 (Python 3.10, released 2015-10)
Additional dependencies: numpy==1.21.6

Problem: Use the pandas groupby operation, where the intention is to include unobserved categories without dropping NA values, and sum over it.

Starting code:
import pandas as pd
def get_grouped_df(df: pd.DataFrame) -> pd.DataFrame:
    return 

Solution:
df.groupby('x', observed=False, dropna=False).sum()

Test:
df = pd.DataFrame({'x': pd.Categorical([1, None], categories=[1, 2, 3]), 'y': [3, 4]})
expected_output=pd.DataFrame({'y': [3, 4]}, index=pd.Index([1, None], name='x'))
assert get_grouped_df(df).equals(expected_output)
Library: pandas==1.5.1 (Python 3.10, released 2015-10)
Additional dependencies: numpy==1.21.6

Problem: Use the pandas groupby operation with observed=False and dropna=False, where the intention is to include unobserved categories without dropping NA values. Your job is to predict the expected output after this operation.

Starting code:
import pandas as pd
def get_grouped_df(df: pd.DataFrame) -> pd.DataFrame:
    return 

Solution:
df.groupby('x', observed=False, dropna=False).sum()

Test:
df = pd.DataFrame({'x': pd.Categorical([1, None], categories=[1, 2, 3]), 'y': [3, 4]})
expected_output = pd.DataFrame({'y': [3, 0, 0]}, index=pd.Index([1, 2, 3], name='x'))
assert get_grouped_df(df).equals(expected_output)
Library: pandas==1.5.0 (Python 3.10, released 2015-10)
Additional dependencies: numpy==1.21.6

Problem: Predict behaviour of setting values with iloc inplace.

Starting code:
import pandas as pd
import numpy as np
def get_expected_value(df: pd.DataFrame) -> pd.Series:
    return 

Solution:
pd.Series([11.1, 12.2], index=['book1', 'book2'], dtype=np.float64)

Test:

df = pd.DataFrame({'price': [11.1, 12.2]}, index=['book1', 'book2'])
original_prices = df['price']
new_prices = np.array([98, 99])
df.iloc[:, 0] = new_prices
correct_prices = pd.Series({'book1': 11.1, 'book2': 12.2})
assert get_expected_value(df).equals(correct_prices)
Library: pandas==2 (Python 3.10, released 2017-01)
Additional dependencies: numpy==1.21.6

Problem: Predict behaviour of setting values with iloc inplace.

Starting code:
import pandas as pd
import numpy as np
def get_expected_value(df: pd.DataFrame) -> pd.Series:
    return 

Solution:
pd.Series([98.0, 99.0], index=['book1', 'book2'], dtype=np.float64)

Test:
df = pd.DataFrame({'price': [11.1, 12.2]}, index=['book1', 'book2'])
original_prices = df['price']
new_prices = np.array([98, 99])
df.iloc[:, 0] = new_prices
correct_prices = pd.Series({'book1': 98.0, 'book2': 99.0})
assert get_expected_value(df).equals(correct_prices)
Library: pandas==1.5.0 (Python 3.10, released 2015-10)
Additional dependencies: numpy==1.21.6

Problem: Predict behaviour of integer slicing on a Series.

Starting code:
import pandas as pd
import numpy as np
def get_slice(ser: pd.Series, start: int, end: int) -> pd.Series:
    return 

Solution:
ser[start:end]

Test:
ser = pd.Series([1, 2, 3, 4, 5], index=[2, 3, 5, 7, 11])
start,end=2,4
sliced_ser = pd.Series([3, 4], index=[5, 7])
assert sliced_ser.equals(get_slice(ser, start, end)), 'Slicing does not match expected output'
Library: pandas==2 (Python 3.10, released 2017-01)
Additional dependencies: numpy==1.21.6

Problem: Predict behaviour of integer slicing on a Series.

Starting code:
import pandas as pd
import numpy as np
def get_slice(ser: pd.Series, start: int, end: int) -> pd.Series:
    return 

Solution:
ser.iloc[start:end]

Test:
ser = pd.Series([1, 2, 3, 4, 5], index=[2, 3, 5, 7, 11])
start,end=2,4
sliced_ser = pd.Series([3, 4], index=[5, 7])
assert sliced_ser.equals(get_slice(ser, start, end)), 'Slicing does not match expected label-based output'
Library: pandas==1.4.0 (Python 3.10, released 2014-08)
Additional dependencies: numpy==1.21.6

Problem: Write a function to return the correct type of an int index.

Starting code:
import pandas as pd
def correct_type(index: pd.Index) -> str:
    return

Solution:
 'int64'

Test:
index = pd.Index([1, 2, 3], dtype='int32')
assertion_1_value = isinstance(correct_type(index), str)
assertion_2_value =  correct_type(index) == 'int64'
assert assertion_1_value
assert assertion_2_value
Library: pandas==1.4.0 (Python 3.10, released 2014-08)
Additional dependencies: numpy==1.21.6

Problem: Combine series and dataframes and return a tuple with combined dataframes first then combined series.

Starting code:
import pandas as pd
def combined(df1: pd.DataFrame, df2: pd.DataFrame, series1: pd.Series, series2: pd.Series) -> tuple:
    return 

Solution:
df1.append(df2, ignore_index=True), series1.append(series2, ignore_index=True)

Test:
series1 = pd.Series([1, 2])
series2 = pd.Series([3, 4])
df1 = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
expected_series_values = [1, 2, 3, 4]
expected_dataframe_values = [[1, 2], [3, 4], [5, 6], [7, 8]]
combined_dataframe, combined_series = combined(df1, df2, series1, series2)
assert list(combined_series) == expected_series_values, 'Combined series values are incorrect'
assert combined_dataframe.values.tolist() == expected_dataframe_values, 'Combined dataframe values are incorrect'
Library: pandas==2 (Python 3.10, released 2017-01)
Additional dependencies: numpy==1.21.6

Problem: Write a function to return the correct type of an int index.

Starting code:
import pandas as pd
def correct_type(index: pd.Index) -> str:
    return 

Solution:
str(index.dtype)

Test:
index = pd.Index([1, 2, 3], dtype='int32')
assert isinstance(correct_type(index), str)
assert correct_type(index) == "int32"
Library: pandas==2 (Python 3.10, released 2017-01)
Additional dependencies: numpy==1.21.6

Problem: Combine series and dataframes. return a tuple of the combined dataframes then the series.

Starting code:
import pandas as pd
def combined(df1: pd.DataFrame, df2: pd.DataFrame, series1: pd.Series, series2: pd.Series) -> tuple:
    return 

Solution:
pd.concat([df1, df2], ignore_index=True), pd.concat([series1,series2],ignore_index=True)

Test:
series1 = pd.Series([1, 2])
series2 = pd.Series([3, 4])
df1 = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
expected_series_values = [1, 2, 3, 4]
expected_dataframe_values = [[1, 2], [3, 4], [5, 6], [7, 8]]
combined_dataframe, combined_series = combined(df1, df2, series1, series2)
assert list(combined_series) == expected_series_values, 'Combined series values are incorrect'
assert combined_dataframe.values.tolist() == expected_dataframe_values, 'Combined dataframe values are incorrect'
Library: numpy==1.21.0 (Python 3.10, released 2021-06)

Problem: Implement a function that calculates the convolution of two arrays with the mode set to full.

Starting code:
import numpy as np

def apply_convolution_full(arr1 : np.ndarray, arr2 : np.ndarray) -> np.ndarray:
    return 

Solution:
np.convolve(arr1, arr2, mode="full")

Test:

arr1 = np.array([1, 2, 3])
arr2 = np.array([0, 1, 0.5])
assertion_result = apply_convolution_full(arr1, arr2).all() == False
assert assertion_result
Library: numpy==1.21.0 (Python 3.10, released 2021-06)

Problem: Implement a function that calculates the convolution of two arrays with the mode set to valid.

Starting code:
import numpy as np

def apply_convolution_valid(arr1 : np.ndarray , arr2 : np.ndarray) -> np.ndarray:
    return 

Solution:
np.convolve(arr1, arr2, mode="valid")

Test:

arr1 = np.array([1, 2, 3])
arr2 = np.array([0, 1, 0.5])
assertion_result = apply_convolution_valid(arr1, arr2).all() == True
assert assertion_result
Library: numpy==1.21.0 (Python 3.10, released 2021-06)

Problem: Implement a function that calculates the Cross-correlation of two 1-dimensional sequences with the mode set to full.

Starting code:
import numpy as np

def apply_correlate_full(arr1 : np.ndarray, arr2 : np.ndarray) -> np.ndarray:
    return 

Solution:
np.correlate(arr1, arr2, mode="full")

Test:

arr1 = np.array([1, 2, 3])
arr2 = np.array([0, 1, 0.5])
assertion_value = apply_correlate_full(arr1, arr2).all() == False
assert assertion_value
Library: numpy==1.25.0 (Python 3.10, released 2023-06)

Problem: Given two arrays, find their common types.

Starting code:
import numpy as np

def find_common_type(arr1:np.ndarray, arr2:np.ndarray) -> np.dtype:
    return np.

Solution:
common_type(arr1, arr2)

Test:

array1 = np.array([1, 2, 3])
array2 = np.array([4.0, 5.0, 6.0])
expected_common_type = np.float64
assertion_value = find_common_type(array1, array2) == expected_common_type
assert assertion_value
Library: numpy==1.21.0 (Python 3.10, released 2021-06)

Problem: Given two arrays, find their common types.

Starting code:
import numpy as np

def find_common_type(arr1:np.ndarray, arr2:np.ndarray) -> np.dtype:
    return np.

Solution:
find_common_type(arr1, arr2)

Test:

array1 = np.array([1, 2, 3])
array2 = np.array([4.0, 5.0, 6.0])
expected_common_type = np.float64

assertion_value = find_common_type(array1, array2) == expected_common_type
assert assertion_value
Library: numpy==1.25.0 (Python 3.10, released 2023-06)

Problem: Write a function that rounds an array of numbers.

Starting code:
import numpy as np

def custom_round(arr:np.ndarray) -> np.ndarray:
    return 

Solution:
np.round(arr)

Test:

def test_custom_round():
    arr = np.array([1.5, 2.3, 3.7])
    result = custom_round(arr)
    expected = np.array([2.0, 2.0, 4.0])
    assert np.array_equal(result, expected)

test_custom_round()
Library: numpy==1.25.0 (Python 3.10, released 2023-06)

Problem: Write a function that computes the product of an array.

Starting code:
import numpy as np

def custom_product(arr:np.ndarray) -> np.ndarray:
    return 

Solution:
np.prod(arr)

Test:

def test_custom_product():
    arr = np.array([1, 2, 3, 4])
    result = custom_product(arr)
    expected = 24
    assert result == expected

test_custom_product()
Library: numpy==1.25.0 (Python 3.10, released 2023-06)

Problem: Write a function that computes the cumulative product of an array.

Starting code:
import numpy as np

def custom_cumproduct(arr:np.ndarray) -> np.ndarray:
    return 

Solution:
np.cumprod(arr)

Test:

def test_custom_cumproduct():
    arr = np.array([1, 2, 3, 4])
    result = custom_cumproduct(arr)
    expected = np.array([1, 2, 6, 24])
    assert np.array_equal(result, expected)

test_custom_cumproduct()
Library: numpy==1.25.0 (Python 3.10, released 2023-06)

Problem: Write a function that checks if any elements in an array are true.

Starting code:
import numpy as np

def custom_sometrue(arr:np.ndarray) -> np.ndarray:
    return 

Solution:
np.any(arr)

Test:


def test_custom_sometrue():
    arr = np.array([0, 0, 1, 0])
    result = custom_sometrue(arr)
    expected = True
    assert result == expected

test_custom_sometrue()
Library: numpy==1.25.0 (Python 3.10, released 2023-06)

Problem: Write a function that checks if all elements in an array are true.

Starting code:
import numpy as np

def custom_alltrue(arr:np.ndarray) -> np.ndarray:
    return 

Solution:
np.all(arr)

Test:


def test_custom_alltrue():
    arr = np.array([1, 1, 1, 1])
    result = custom_alltrue(arr)
    expected = True
    assert result == expected

test_custom_alltrue()