#L2_B_58
from rdkit import Chem
from rdkit.Chem.Scaffolds import MurckoScaffold
from rdkit.Chem import AllChem
from rdkit import DataStructs

def solve(smiles_lst):
    new_mols = []
    for smiles in smiles_lst:
        mol = Chem.MolFromSmiles(smiles)
        scaff = MurckoScaffold.GetScaffoldForMol(mol)
        new_mols.append(scaff)

    simi_lst = []
    for idx, mol1 in enumerate(new_mols):
        fp1 = AllChem.GetMorganFingerprintAsBitVect(mol1, 2, nBits=1024)
        for mol2 in new_mols[idx+1:]:
            fp2 = AllChem.GetMorganFingerprintAsBitVect(mol2, 2, nBits=1024)
            simi = DataStructs.TanimotoSimilarity(fp1,fp2)
            simi_lst.append(simi)
    mean_simi = round(sum(simi_lst)/len(simi_lst), 4)
    return mean_simi

Please write a complete Python function `solve(smiles_lst)`.
The input is a list of SMILES of molecules.
Remove the side chain atoms from these molecules
(atoms not in the ring or between the rings on the shortest path are called side chain atoms),
and then calculate the 1024-bit ECFP4 fingerprint Tanimoto similarity between these molecules with side chain atoms removed.
The function should return the average similarity between them, with the result rounded to 4 decimal places.
In RDKit, the function `rdkit.Chem.Scaffolds.MurckoScaffold.GetScaffoldForMol()` can get the Bemis-Murcko scaffold of a molecule;
`rdkit.Chem.AllChem.GetMorganFingerprintAsBitVect()` can calculate the ECFP fingerprint of a molecule;
`rdkit.DataStructs.TanimotoSimilarity()` can calculate the Tanimoto similarity of two fingerprints.
First, extract the Bemis-Murcko scaffold of these molecules to get a list of scaffolds.
Then just traverse the list of Bemis-Murcko scaffolds of molecules,
calculate the Tanimoto similarity between their fingerprints,
and then calculate the average of all similarities, keeping four decimal places.

#<INSERT>

def check(solve):
    assert solve(['CC(c1ccccc1)C(CCl)C(C)c1ccccc1', 'CC(c1ccccc1)C(CNC1CC1)C(c1ccccc1)C1CCCC1', 'COC(C)C(N)C(C(CO)c1ccccc1)C1CCCC1C']) == 0.3302
    assert solve(['CCC(CC)c1ccccc1', 'Cc1cccc(-c2ccc(F)cc2)c1', 'CC(C)c1ccccc1-c1ccccc1C(C)Cc1cccc2c1CCC2']) == 0.2267

check(solve)


import pandas as pd

# Load the dataset
def proc_data():
    file_path = 'last_match.csv'
    # Load the CSV file into a DataFrame
    data = pd.read_csv(file_path)

    # Calculate total transaction amount
    total_transaction_amount = (data['price'] * data['size']).sum()
    return total_transaction_amount

There is a dataset named 'last_match.csv', the data format is as follows:
|   Unnamed: 0 | _id                      | maker_order_id                       |   price | product_id   |   sequence | side   |   size | taker_order_id                       | time                        |   trade_id | type       |
|-------------:|:-------------------------|:-------------------------------------|--------:|:-------------|-----------:|:-------|-------:|:-------------------------------------|:----------------------------|-----------:|:-----------|
|            0 | 5ad545e5e3ae712cb8091acc | 6279e0f7-567a-4c93-9b0c-5169ce21e43d | 8042.91 | BTC-USD      | 5693129275 | sell   | 0.6535 | 2a6c1214-6232-4567-9ff6-5e5fb452b428 | 2018-04-17T00:54:57.887000Z |   41766820 | last_match |

Question:
Calculate the sum of the transaction volume (prize * size) based on the 'price' and 'size' columns.

The answer needs to meet the following requirements:
1. The data file is 'last_match.csv'. Please refer to the data header strictly and use Python code to answer the question.
2. Use 'pandas.read_csv' to read the data, the default is that the data is in the same path as the code.
3. The analysis code is made into a function called 'proc_data()', and this function does not require any input parameters, with the sum of the transaction volume in the question as the return value.

Question: There is a dataset named 'person.csv', the data schema is as follows:

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| email       | varchar |
+-------------+---------+

Where id is the primary key column (column with unique values) of this table. Each row of the table contains an email. The emails will not contain uppercase letters.

Write a solution using the python pandas library to remove all duplicate emails, keeping only one unique email with the smallest id.

The answer needs to meet the following requirements:
1. The data file is 'person.csv', please strictly refer to the data header and answer the question with python code.
2. Use 'pandas.read_csv' to read the data, it is assumed that the data is in the same path as the code.
3. Write the analysis code into a function called 'proc_data()', this function does not need any input parameters, and it should return the processed dataframe.

Answer:
```python
import pandas as pd

def proc_data():
    # read CSV file and create DataFrame
    df = pd.read_csv('person.csv')

    # Convert the email column to lower case
    df['email'] = df['email'].str.lower()

    # Sort by the email column, then sort by the id column
    df.sort_values(['email', 'id'], inplace=True)

    # Remove duplicate emails, keep only the unique email with the smallest id
    df.drop_duplicates(subset='email', keep='first', inplace=True)

    return df
```

----------------

Question: There is a dataset named 'animals.csv', the data schema is as follows:

+-------------+--------+
| Column Name | Type   |
+-------------+--------+
| name        | object |
| species     | object |
| age         | int    |
| weight      | int    |
+-------------+--------+

Write a solution to list the names of animals that strictly weigh more than 100 kilograms. Return the animal names in descending order of weight.

The answer needs to meet the following requirements:
1. The data file is 'animals.csv', please strictly refer to the data header and answer the question with python code.
2. Use 'pandas.read_csv' to read the data, it is assumed that the data is in the same path as the code.
3. Write the analysis code into a function called 'proc_data()', this function does not need any input parameters, and it should return a python list.

Answer:
```python
import pandas as pd

def proc_data():
    # read CSV file and create DataFrame
    df = pd.read_csv('animals.csv')

    # filter animals that strictly weigh more than 100 kilograms
    filtered_df = df[df['weight'] > 100]

    # sort by weight in descending order
    sorted_df = filtered_df.sort_values('weight', ascending=False)

    # get the list of animal names
    animal_names = sorted_df['name'].tolist()

    return animal_names
```

----------------

#<INSERT>

answer = proc_data()
assert round(answer, 3) == 5256.042

# 数据只有一行


import pandas as pd

from datetime import datetime

def proc_data():
    # Load the dataset
    data = pd.read_csv("AES.csv")

    data['Date'] = pd.to_datetime(data['Date'])

    start_date = datetime.strptime('2015-01-01', "%Y-%m-%d")
    end_date = datetime.strptime('2015-02-01', "%Y-%m-%d")

    data['Date'] = pd.to_datetime(data['Date'],"%Y-%m-%d")

    jan_2015_data = data[(data['Date'] >= start_date) & (data['Date'] < end_date)]

    # Filter the data for January 2015
    # jan_2015_data = data[(data['Date'] >= '2015-01-01') & (data['Date'] <= '2015-01-31')]

    # Find the minimum opening price for January 2015
    min_open_price = jan_2015_data['Open'].min()

    return min_open_price

There is a dataset named 'AES.csv', the first two rows of the data are as follows:
| Symbol   | Date       |   Close |   High |   Low |   Open |   Volume |
|:---------|:-----------|--------:|-------:|------:|-------:|---------:|
| AES      | 2015-01-01 |   13.77 |  13.77 | 13.77 |  13.77 |        0 |
| AES      | 2015-01-02 |   13.7  |  13.87 | 13.51 |  13.86 |  5228725 |

Question:
Analyze the given dataset to find out the lowest opening price in January 2015.

Requirements for the answer:
1. The data file is 'AES.csv', please strictly follow the data header and use Python code to answer the question.
2. Use 'pandas.read_csv' to read the data, by default the data is in the same path as the code.
3. Write the analysis code in a function called 'proc_data()', this function does not require any input parameters, use the lowest opening price in the question as the return value.

#<INSERT>

answer = proc_data()
assert round(answer, 3) == 12.220


# 导入所需模块
import pandas as pd

def proc_data():
    # 加载CSV文件
    file_path = '管理员后台分组数据表_0.csv'
    df = pd.read_csv(file_path)

    # 查找分组id为3634的部门的父分组id
    parent_group_id = df.loc[df['分组id'] == 3634, '父分组id'].values[0]

    return parent_group_id

Here's a dataset called 'admin_backstage_group_data_0.csv'. The first two lines of the data are as follows:
|   Unnamed: 0 |   Group ID | Group Name   |   Parent Group ID |   Level |   Status | Creation Time         | Update Time          | Group Keywords   | Effective Time       | Target Region ID |
|-------------:|---------:|:-----------|-----------:|-------:|-------:|:--------------------|:--------------------|:-------------|:--------------------|:---------------|
|            0 |     5421 | Sales Department |          0 |      1 |      0 | 2020-04-20 08:30:00 | 2020-05-20 08:30:00 | Key1         | 2020-05-01 08:30:00 | Region1        |
|            1 |     3634 | Customer Service Department |       5421 |      2 |      1 | 2020-04-20 08:31:00 | 2020-05-20 08:31:00 | Key2         | 2020-05-01 08:31:00 | Region2        |

Question:
Given the CSV data, under which Parent Group ID does the department with Group ID 3634 belong?

The answer must meet the following requirements:
1. The data file is 'admin_backstage_group_data_0.csv', please strictly conform to the data header, use Python code to answer the question.
2. Use 'pandas.read_csv' to read the data, by default, the data is in the same path as the code.
3. Write the analysis code as a function called 'proc_data()', and this function does not require any input parameters, use the ID in the question as the return value. The ID should be of integer type.

#<INSERT>

answer = proc_data()
assert answer == 5421


import pandas as pd

def proc_data():
    # Load the CSV file into a dataframe
    df = pd.read_csv("DES=+3454989.csv")

    import numpy as np

    # Extract the X, Y, Z values for the first two rows
    x1, y1, z1 = df.loc[0, ["X", "Y", "Z"]]
    x2, y2, z2 = df.loc[1, ["X", "Y", "Z"]]

    # Calculate the distance between the two points using the distance formula
    distance = np.sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2 - z1)**2)

    return distance

There is a dataset named 'DES=+3454989.csv', and the first two rows of the data are as follows:
|       JDTDB | Calendar Date (TDB)            |            X |            Y |            Z |   Unnamed: 5 |
|------------:|:-------------------------------|-------------:|-------------:|-------------:|-------------:|
| 2.45131e+06 | A.D. 1999-May-13 11:22:05.0000 | -1.79592e+08 | -1.85163e+08 | -6.54105e+07 |          nan |
| 2.45131e+06 | A.D. 1999-May-14 11:22:05.0000 | -1.78221e+08 | -1.86545e+08 | -6.57302e+07 |          nan |

Question:
Calculate the distance between the first and the second row, using the values of X, Y, and Z to calculate the Euclidean distance.

The answer needs to meet the following requirements:
1. The data file is 'DES=+3454989.csv'. Please strictly refer to the data header and do the coding with python to answer the question.
2. Use 'pandas.read_csv' to read the data, the default is that the data is in the same directory as the code.
3. The analysis code should be written as a function named 'proc_data()', and this function does not require any input parameters, use the distance from the question as the return value.

#<INSERT>

answer = proc_data()
assert round(answer, 3) == 1972998.639


import pandas as pd

def proc_data():
    # Load the CSV file into a DataFrame
    bond_df = pd.read_csv('jamesbond.csv')

    # Filter the DataFrame for movies where Sean Connery is the actor
    connery_movies = bond_df[bond_df['Actor'] == 'Sean Connery']

    # Calculate the total box office for Sean Connery's Bond movies
    total_box_office = connery_movies['Box Office'].sum()

    return total_box_office

There is a dataset named 'jamesbond.csv', the first two lines of the data are as follows:
| Film                  |   Year | Actor        | Director      |   Box Office |   Budget |   Bond Actor Salary |
|:----------------------|-------:|:-------------|:--------------|-------------:|---------:|--------------------:|
| Dr. No                |   1962 | Sean Connery | Terence Young |        448.8 |      7   |                 0.6 |
| From Russia with Love |   1963 | Sean Connery | Terence Young |        543.8 |     12.6 |                 1.6 |

Question:
Please calculate the total box office of all Bond films starring Sean Connery.

The answer should meet the following requirements:
1. The data file is 'jamesbond.csv', please strictly refer to the header of the data, and use python code to answer the question.
2. Use 'pandas.read_csv' to read data, the data is by default in the same path as the code.
3. Write the analysis code as a function called 'proc_data()', and this function does not need any input parameters, use the total box office in the question as the return value.

#<INSERT>

answer = proc_data()
assert round(answer, 3) == 3997.800


import pandas as pd

def proc_data():
    # Load the data from the provided CSV file
    file_path = '02-02-2020_2100.csv'
    data = pd.read_csv(file_path)

    # Sort the dataframe based on the 'Deaths' column in descending order
    sorted_data = data.sort_values(by='Deaths', ascending=False)

    # Find the province/state that ranks fourth in terms of the number of deaths
    fourth_ranked_province = sorted_data.iloc[3]['Province/State']

    return fourth_ranked_province

There is a dataset named '02-02-2020_2100.csv', and the first two rows of the data are as follows:
| Province/State   | Country/Region   | Last Update    |   Confirmed |   Deaths |   Recovered |
|:-----------------|:-----------------|:---------------|------------:|---------:|------------:|
| Hubei            | Mainland China   | 2/2/2020 23:43 |       11177 |      350 |         295 |
| Zhejiang         | Mainland China   | 2/3/2020 1:33  |         724 |        0 |          36 |

Question:
Which province ranks fourth in terms of death cases among all the provinces in the dataset?

The answer needs to meet the following requirements:
1. The data file is '02-02-2020_2100.csv', please strictly refer to the header of the data and use python code to answer the question.
2. Use 'pandas.read_csv' to read the data, and assume that the data is in the same path as the code by default.
3. The analysis code should be written as a function called 'proc_data()', and the function doesn't require any input parameters, it should return the name of the province.

#<INSERT>

answer = proc_data()
assert answer == 'Heilongjiang'


#L2_B_55
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit import DataStructs

def solve(smiles):
    mol = Chem.MolFromSmiles(smiles)
    if mol is None:
        return None
    rxn_dBOC = AllChem.ReactionFromSmarts("[#7:1][CX3:2](=[OD1])[OD2]C([CH3])([CH3])[CH3]>>[#7:1][H:2]")

    mol.UpdatePropertyCache()
    prod = rxn_dBOC.RunReactants([mol])
    if prod:
        prod = prod[0][0]
        Chem.SanitizeMol(prod)

    fp1 = AllChem.GetMorganFingerprintAsBitVect(mol, 2, nBits=2048)
    fp2 = AllChem.GetMorganFingerprintAsBitVect(prod, 2, nBits=2048)
    simi = DataStructs.TanimotoSimilarity(fp1,fp2)
    return round(simi, 3)

It is known that the reaction SMARTS for Boc deprotection is `[#7:1][CX3:2](=[OD1])[OD2]C([CH3])([CH3])[CH3]>>[#7:1][H:2]`. The Tanimoto similarity between two molecular fingerprints can be calculated using the TanimotoSimilarity function found in the DataStructs module of the rdkit package. Implement a complete Python function `solve(smiles)` that takes a molecule's SMILES as input. First, read the SMILES, then define the deprotection reaction rxn_dBOC using the `AllChem.ReactionFromSmarts` function. After that, run the reaction with rxn_dBOC.RunReactants([mol]) to obtain the product molecule. Next, use the `GetMorganFingerprintAsBitVect` function to calculate the 2048-bit ECFP4 fingerprint of both reactants and product molecules. Finally, call the `TanimotoSimilarity` function to calculate the Tanimoto similarity of the fingerprints and return this value with the result rounded to 3 decimal places.

Question: Write a piece of python code to achieve the following function.
Find the maximum perfect square number that is less than the nth Fibonacci number.
The function's name is max_square_number, and the input is an integer n.

Answer:
```python
def max_square_number(n):
    if n <= 2:
        return 0  # For the first two numbers in the Fibonacci sequence, no complete square numbers can be used.

    fibs = [0, 1]  # Store the first two numbers of the Fibonacci sequence
    squares = []  # Store the list of perfect square numbers

    max_square = 0
    i = 2

    while i <= n:
        fibs.append(fibs[i-1] + fibs[i-2])  # Calculate the next Fibonacci number
        i += 1

    fib = fibs[-1]
    perfect_squares = [i**2 for i in range(1, int(math.sqrt(fib)) + 1)]
    max_square = max(filter(lambda x: x < fib, perfect_squares))
    return max_square
```

----------------

#<INSERT>

def check(solve):
    assert abs(solve('Cc1ccccc1CNC(=O)OC(C)(C)C') - 0.3333) < 1e-3
    assert abs(solve('CCC(C)CCNC(=O)OC(C)(C)C') - 0.2778) < 1e-3
    assert abs(solve('CCN(C)C(=O)OC(C)(C)C') - 0.1071) < 1e-3

check(solve)


#L2_C_59
from rdkit import Chem
from itertools import combinations
from rdkit import DataStructs

def solve(smiles, N=1):
    mol = Chem.MolFromSmiles(smiles)
    out_mol_list = []
    used = set()
    aromatic_cH = Chem.MolFromSmarts("[cH]")
    match_atms = [x[0] for x in mol.GetSubstructMatches(aromatic_cH)]
    n_combos = combinations(match_atms, N)
    for combo in n_combos:
        new_mol = Chem.RWMol(mol)
        for idx in combo:
            atm = new_mol.GetAtomWithIdx(idx)
            atm.SetAtomicNum(7)
        smi = Chem.MolToSmiles(new_mol)
        if smi not in used:
            used.add(smi)
            out_mol_list.append(new_mol)
    return used

Please write a complete Python function `solve(smiles, N)`,
which takes a molecule's SMILES and the quantity of nitrogen (N) as inputs.
This function should replace the "N" number of unsubstituted
aromatic carbon atoms (these carbon atoms are connected to one hydrogen atom) in the molecule with nitrogen atoms,
and return the set of SMILES of all possible molecular structures that may be produced by this substitution.
The aromatic carbon atoms to be replaced can be matched by SMARTS "[cH]".
First, use `mol.GetSubstructMatches()` to find all the carbon atoms to be replaced,
then iterate over all combinations of extracting N atoms from them and perform the replacement for the N atoms in each combination.
You can convert `mol` to `RWMol` object through `rdkit.Chem.RWMol()`,
then get the corresponding atom through `rwmol.GetAtomWithIdx()`.
You can replace the atom with a nitrogen atom using `atom.SetAtomicNum(7)`.
Once you obtain a new molecular structure, save it as SMILES and add it to the set.
Finally, return the set of new molecule SMILES.

#<INSERT>

def check(solve):
    assert solve('CCc1cc(C)ccn1', 1) == {'CCc1cc(C)ncn1', 'CCc1nccc(C)n1', 'CCc1cc(C)cnn1'}
    assert solve('CC(C)CC1C=Cc2c(F)cccc21', 2) == {'CC(C)CC1C=Cc2c(F)ncnc21', 'CC(C)CC1C=Cc2c1cnnc2F', 'CC(C)CC1C=Cc2c(F)cnnc21'}
    assert solve('CC(CC1N=Cc2c(F)cccc21)n1cccc1', 2) == {'CC(CC1N=Cc2c1ccnc2F)n1ccnc1', 'CC(CC1N=Cc2c1cnnc2F)n1cccc1', 'CC(CC1N=Cc2c(F)cnnc21)n1cccc1',
                                                  'CC(CC1N=Cc2c1ccnc2F)n1cccn1', 'CC(CC1N=Cc2c(F)ccnc21)n1cccn1', 'CC(CC1N=Cc2c(F)cccc21)n1ccnn1',
                                                  'CC(CC1N=Cc2c(F)cncc21)n1cccn1', 'CC(CC1N=Cc2c(F)ccnc21)n1ccnc1', 'CC(CC1N=Cc2c(F)ncnc21)n1cccc1',
                                                  'CC(CC1N=Cc2c(F)cncc21)n1ccnc1', 'CC(CC1N=Cc2c(F)cccc21)n1nccn1', 'CC(CC1N=Cc2c(F)cccc21)n1cnnc1',
                                                  'CC(CC1N=Cc2c(F)cccc21)n1cncn1'}

check(solve)


import pandas as pd

def process_csv_data():
    customer_csv_filename = 'structured_io_test_data_customers.csv'
    order_csv_filename = 'structured_io_test_data_orders.csv'
    output_filename = 'output.csv'
    # 读取CSV文件
    df_customers = pd.read_csv(customer_csv_filename)
    df_orders = pd.read_csv(order_csv_filename)

    # 合并数据集
    merged_data = pd.merge(df_orders, df_customers, on='CustomerID')

    # 计算每个城市的订单总金额
    city_order_totals = merged_data.groupby('City')['Amount'].sum().reset_index()

    # 保存结果
    city_order_totals.to_csv(output_filename, index=False)

You are a data analyst who needs to extract and analyze data from two CSV files. These two files contain the following contents:

Customer Information (filename: structured_io_test_data_customers.csv): contains the following columns:

CustomerID: Customer ID
Name: Customer Name
Age: Customer Age
City: The city where the customer is located.

Order information (file name: structured_io_test_data_orders.csv): include the following columns:

OrderID: Order ID
CustomerID: Customer ID
OrderDate: Order Date
Amount: Order Amount

Write a function, process_csv_data(), with no arguments. The function needs to meet the following requirements:
1. Read these two CSV files (located in the current path).
2. Merge these two datasets and generate the total order amount for each city.
3. Write the output table to the 'output.csv' file in CSV format.

The output file includes the following columns:
City: City Name
Amount: The total amount of all the orders in that city.

#<INSERT>

import csv
import os
process_csv_data()

data = {}
with open('output.csv') as csv_file:
    csv_reader = csv.reader(csv_file)
    next(csv_reader)
    for row in csv_reader:
        data[row[0]] = int(row[1])
assert data == {
    'Chicago': 280,
    'Los Angeles': 570,
    'New York': 350
}

os.remove('output.csv', )


import pandas as pd

def proc_data():
    # Load the data
    file_path = 'spx.csv'
    spx_data = pd.read_csv(file_path)

    # Convert the date column to datetime object for filtering
    spx_data['Unnamed: 0'] = pd.to_datetime(spx_data['Unnamed: 0'])

    # Filter the data to get the rows corresponding to the first quarter of 1990
    start_date = '1990-01-01'
    end_date = '1990-03-31'
    spx_q1_1990 = spx_data[(spx_data['Unnamed: 0'] >= start_date) & (spx_data['Unnamed: 0'] <= end_date)]

    # Calculate the average of 'SPX' for the first quarter of 1990
    average_spx_q1_1990 = spx_q1_1990['SPX'].mean()

    return average_spx_q1_1990

There is a dataset named 'spx.csv', the first two rows of the data are as follows:
| Unnamed: 0          |    SPX |
|:--------------------|-------:|
| 1990-02-01 00:00:00 | 328.79 |
| 1990-02-02 00:00:00 | 330.92 |

Question:
Calculate the average value of 'SPX' for the first quarter of 1990.

The answer needs to meet the following requirements:
1. The data file is 'spx.csv', please strictly refer to the data header, use python code to answer the question.
2. Use 'pandas.read_csv' to read the data, the default is that the data is in the same path as the code.
3. Write the analysis code as a function called 'proc_data()', and this function does not need any input parameters, use the average value of the question as the return value.

#<INSERT>

answer = proc_data()
assert round(answer, 3) == 334.752


import pandas as pd

def proc_data():
    file_path = 'sample.csv'
    # Load the CSV file into a DataFrame
    data = pd.read_csv(file_path)

    # Extract interest rates for January and February 1991
    ir_jan_1991 = data[data['month_tag'] == 199101]['IR'].values[0]
    ir_feb_1991 = data[data['month_tag'] == 199102]['IR'].values[0]

    # Calculate the month-on-month ratio
    mom_ratio = (ir_feb_1991 / ir_jan_1991) * 100

    return mom_ratio

There is a dataset named 'sample.csv', and the first two rows are as follows:
|   month_tag |   IR |
|------------:|-----:|
|      199101 | 9.53 |
|      199102 | 9.46 |

Question:
Calculate the month-on-month ratio of the interest rate (IR) for February 1991 (199102) to January 1991 (199101) and express it as a percentage.

The answer must meet the following requirements:
1. The data file is 'sample.csv'. Please strictly refer to the data headers and use Python code to answer the question.
2. Use 'pandas.read_csv' to read the data, assuming the data is in the same path as the code.
3. Write the analysis code as a function named 'proc_data()'. This function does not require any input parameters and uses the percentage in the question as the return value.
Note: A floating point number needs to be returned. That is, if the percentage is 50.5%, return 50.5.

#<INSERT>

answer = proc_data()
assert round(answer, 3) == 99.265


import pandas as pd

def proc_data():
    file_path = 'housing-data-wide1-100.csv'
    # Load the CSV file into a DataFrame
    housing_data = pd.read_csv(file_path)
    # Check for rows where both price1 and price2 are not NaN
    complete_price_data = housing_data.dropna(subset=['price1', 'price2'])

    # Get the count of such properties
    complete_price_count = complete_price_data.shape[0]
    return complete_price_count

There is a dataset named 'housing-data-wide1-100.csv', the first two lines of the data are as follows:
|   property_id |   bedrooms |   price1 |   price2 |
|--------------:|-----------:|---------:|---------:|
|   1.23039e+08 |          1 |   148000 |   244900 |
|   3.02e+08    |          3 |   169100 |   250000 |

Question:
Find out the number of properties with complete price information (both price1 and price2 are not NaN).

The answer needs to meet the following requirements:
1. The data file is 'housing-data-wide1-100.csv', please strictly refer to the header of the data, and use python code to answer the question.
2. Use 'pandas.read_csv' to read the data, the default data is in the same path as the code.
3. Write the analysis code into a function called 'proc_data()', and this function does not need any input parameters, use the number of properties in the question as the return value.

#<INSERT>

answer = proc_data()
assert answer == 80


import pandas as pd

def proc_data():
    # Load the uploaded file into a DataFrame
    data = pd.read_csv('DES=+3433236.csv')

    # Calculate the standard deviation for the Z column
    std_dev_z = data['Z'].std()

    return std_dev_z

There's a dataset named 'DES=+3433236.csv', the first two lines of the data are as follows:

|       JDTDB | Calendar Date (TDB)            |            X |            Y |           Z |   Unnamed: 5 |
|------------:|:-------------------------------|-------------:|-------------:|------------:|-------------:|
| 2.45081e+06 | A.D. 1997-Dec-29 12:11:24.0000 | -4.23695e+07 | -6.55086e+08 | 9.65504e+07 |          nan |
| 2.45081e+06 | A.D. 1997-Dec-30 12:11:24.0000 | -4.12188e+07 | -6.55086e+08 | 9.66462e+07 |          nan |

Question:
Please calculate the standard deviation of the celestial body's position change on the Z axis.

The answer needs to meet the following requirements:
1. The data file is 'DES=+3433236.csv', please strictly refer to the data's header and use python code to answer the question.
2. Use 'pandas.read_csv' to read the data, assuming that the data is in the same path as the code by default.
3. Write the analysis code into a function called 'proc_data()', and this function does not require any input parameters, use the standard deviation in the question as the return value.

#<INSERT>

answer = proc_data()
assert round(answer, 3) == 12904338.174


import pandas as pd

def proc_data():
    # Load the data
    file_path = 'Simple Linear Regression.csv'
    data = pd.read_csv(file_path)

    # Filter the data for the years 1978 to 1982
    filtered_data = data[data['year'].between(1978, 1982)]

    # Calculate the correlation between staff_wage_mean and shanghai_GDP
    correlation = filtered_data['staff_wage_mean'].corr(filtered_data['shanghai_GDP'])
    return correlation

There is a dataset named 'Simple Linear Regression.csv', the first two rows of the data are as follows:

|   year |   staff_wage_mean |   shanghai_GDP |
|-------:|------------------:|---------------:|
|   1978 |               672 |         272.81 |
|   1979 |               784 |         286.43 |

Question:
Please calculate the correlation between the average employee wage and the GDP in Shanghai from 1978 to 1982.

The answer needs to meet the following requirements:
1. The data file name is 'Simple Linear Regression.csv'. Please strictly reference the header of the data and use python code to answer the question.
2. Use 'pandas.read_csv' to read the data, assuming that the data is under the same path as the code.
3. Write the analysis code into a function named 'proc_data()', and this function doesn't need any input parameters. Use the correlation in the question as the return value.

#<INSERT>

answer = proc_data()
assert round(answer, 3) == 0.922


import pandas as pd

def proc_data():
    # Load the data
    sat_scores = pd.read_csv("sat_scores.csv")

    # Filter the data for states with a Rate higher than 75
    filtered_data = sat_scores[sat_scores["Rate"] > 75]

    # Calculate the correlation between Verbal and Math scores for these states
    correlation = filtered_data["Verbal"].corr(filtered_data["Math"])
    return correlation

There is a dataset named 'sat_scores.csv', the first two lines of the data are as follows:

| State   |   Rate |   Verbal |   Math |
|:--------|-------:|---------:|-------:|
| CT      |     82 |      509 |    510 |
| NJ      |     81 |      499 |    513 |

Question:
What is the correlation between Verbal and Math scores for states with a Rate higher than 75?

The answer needs to meet the following requirements:
1. The data file is 'sat_scores.csv', please strictly refer to the header of the data and use python code to answer the question.
2. Use 'pandas.read_csv' to read the data, the default data is in the same path as the code.
3. The analysis code is written as a function called 'proc_data()', and this function does not require any input parameters, using the correlation in the question as the return value.

#<INSERT>

answer = proc_data()
assert round(answer, 3) == 0.660


import pandas as pd

def proc_data():
    # Load the data
    file_path = 'epl_xg.csv'
    data = pd.read_csv(file_path)

    # Calculate the Pearson correlation coefficient between actual goals (G) and expected goals (NPxG)
    correlation_g_npxg = data['G'].corr(data['NPxG'])
    return correlation_g_npxg

There's a dataset named 'epl_xg.csv'. The first two rows of the data are as follows:
| Team        |   Games |   G |   GA |    xG |   xGA |   NPxG |   NPxGA |
|:------------|--------:|----:|-----:|------:|------:|-------:|--------:|
| Arsenal     |       8 |  19 |   10 | 10.41 | 10.95 |  10.41 |   10.95 |
| Bournemouth |       8 |  16 |   12 | 16.08 |  9.25 |  12.27 |    7.73 |

Question:
Please use data analysis techniques to find the correlation between the actual number of goals (G) and the expected number of goals (NPxG).

Your answer should meet the following requirements:
1. The data file is 'epl_xg.csv', strictly refer to the headers of the data and use Python code to answer the question.
2. Use 'pandas.read_csv' to read the data, assuming the data is in the same path as the code.
3. The analysis code should be a function named 'proc_data()', and this function doesn't need any input parameters. Use the correlation coefficient in the question as the return value.

#<INSERT>

answer = proc_data()
assert round(answer, 3) == 0.782


import pandas as pd

def proc_data():
    # 加载数据
    file_path = 'CGO.csv'
    data = pd.read_csv(file_path)

    # 计算每天收盘价和当日最高价之间的差值
    data['Difference'] = data['High'] - data['Close']

    # 计算平均差值
    average_difference = data['Difference'].mean()
    return average_difference

There is a dataset named 'CGO.csv', the first two rows of which are as follows:
| Date       |   Open |   High |   Low |   Close |   Volume |   Adj Close |
|:-----------|-------:|-------:|------:|--------:|---------:|------------:|
| 2015-08-07 |  13.21 |  13.27 | 12.81 |   12.86 |    19600 |       12.86 |
| 2015-08-06 |  13.22 |  13.42 | 13.04 |   13.31 |    77300 |       13.21 |

Question:
Please calculate the average difference between the highest price of the day and the daily closing price.

Answers need to meet the following requirements:
1. The data file is 'CGO.csv'. Please strictly refer to the header of the data and answer the question using python codes.
2. Use 'pandas.read_csv' to read the data. By default, the data is in the same path as the code.
3. Make the analysis code into a function called 'proc_data()', which does not require any input parameters, and use the average difference in the question as the return value.

#<INSERT>

answer = proc_data()
assert round(answer, 3) == 0.126


import pandas as pd

def proc_data():
    # Load the csv file
    df = pd.read_csv('locations.csv')

    # Find the listing_id with the maximum latitude value
    listing_id_most_north = df[df['latitude'] == df['latitude'].max()]['listing_id'].iloc[0]
    return listing_id_most_north

There is a dataset named 'locations.csv', the first two rows of the data are as follows:

|   Unnamed: 0 |   listing_id |   latitude |   longitude |
|-------------:|-------------:|-----------:|------------:|
|           10 |  7.21121e+06 |    40.7145 |    -73.9425 |
|        10000 |  7.15086e+06 |    40.7947 |    -73.9667 |

Question:
Which listing_id in the csv file is the furthest north?

Your answer needs to meet the following requirements:
1. The data file is 'locations.csv', please refer strictly to the header of the data, and use python code to answer the question.
2. Use 'pandas.read_csv' to read the data, assuming the data is in the same path as the code.
3. Write the analysis code into a function named 'proc_data()', which does not require any input parameters and returns the listing_id of the furthest north location.

#<INSERT>

answer = proc_data()
assert answer == 7035661


import pandas as pd

def proc_data():
    # Reload the dataset using the correct delimiter
    data = pd.read_csv('DatosEjemplo.csv', delimiter=';')

    # Calculate the correlation between math (MAT) and language (LENG) scores
    correlation = data['MAT'].corr(data['LENG'])

    return correlation

There is a dataset named 'DatosEjemplo.csv', the first two lines of the data are as follows:
|    |   Elaborativo |   MAT |   LENG |   CIENCIA |
|---:|--------------:|------:|-------:|----------:|
|  0 |             0 |   429 |    573 |       443 |
|  1 |             0 |   572 |    534 |       497 |

Question:
Please analyze the correlation between students' math and language scores in the dataset.

The answer needs to meet the following requirements:
1. The data file is 'DatosEjemplo.csv'. Please strictly refer to the headers of the data and use python code to answer the question.
2. Use 'pandas.read_csv' to read the data. The data is in the same path as the code by default, and the separator is ';'.
3. The analysis code is written as a function called 'proc_data()'. This function does not require any input parameters and uses the correlation coefficient in the question as the return value.

#<INSERT>

answer = proc_data()
assert round(answer, 3) == 0.365


import pandas as pd

def proc_data():
# Load the CSV file into a DataFrame
    data = pd.read_csv("submission_linear_regression.csv")

    # Check the first few rows of the data to understand its structure
    data.head()

    # Calculate the average SalePrice
    average_sale_price = data["SalePrice"].mean()

    if average_sale_price >= 100000:
        return 1

    return 0

The data set is named 'submission_linear_regression.csv', and the first two rows of data are as follows:
|   Id |   SalePrice |
|-----:|------------:|
| 1461 |      122372 |
| 1462 |      153920 |

Question:
Please determine whether the average house price in the data is higher than 100,000.

The answer needs to meet the following requirements:
1. The data file is 'submission_linear_regression.csv'. Please strictly refer to the data header and use Python code to answer the question.
2. Use 'pandas.read_csv' to read the data. By default, the data is in the same path as the code.
3. The analysis code is written as a function named 'proc_data()'. This function does not require any input parameters. If the average house price is higher than or equal to 100,000, return 1; otherwise, return 0.

#<INSERT>

answer = proc_data()
assert answer == 1


import pandas as pd

def proc_data():
    # 读取数据集
    fifa_data = pd.read_csv("fifa.csv")

    # 计算mins列的平均值
    average_mins = fifa_data[fifa_data['goal'] > 2]["mins"].mean()
    return average_mins

There is a dataset named 'fifa.csv', and the first two lines of the data are as follows:
| name              |   goal |   ass |   mins |   maches |   left |   right |
|:------------------|-------:|------:|-------:|---------:|-------:|--------:|
| Harry KANE        |      6 |     0 |    573 |        6 |      4 |       1 |
| Antoine GRIEZMANN |      4 |     2 |    570 |        7 |      0 |       0 |

Question:
According to this dataset, calculate the average playing time (mins) of all players who scored more than 2 goals.

The answer needs to meet the following requirements:
1. The data file is 'fifa.csv', please strictly refer to the data header, and use Python code to answer the question.
2. Use 'pandas.read_csv' to read the data. By default, the data is in the same path as the code.
3. Write the analysis code as a function called 'proc_data()', and this function does not need any input parameters. Use the average playing time in the question as the return value.

#<INSERT>

answer = proc_data()
assert round(answer, 3) == 451.615


#L2_B_52
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem import Descriptors

def solve(smiles):
    mol = Chem.MolFromSmiles(smiles)
    patt = Chem.MolFromSmarts('[C](=[O])[OH]')
    repl = Chem.MolFromSmiles('[C](=[O])[O][CH3]')
    rms = AllChem.ReplaceSubstructs(mol, patt, repl, replaceAll=True)
    prod = rms[0]
    Chem.SanitizeMol(prod)
    tpsa_before = Descriptors.TPSA(mol)
    tpsa_after = Descriptors.TPSA(prod)
    return round(tpsa_after - tpsa_before, 3)

Implement a complete Python function `solve(smiles)` with the input being the SMILES of a molecule. First, perform methyl-esterification of all carboxyl groups (smarts are [C](=[O])[OH]) in the molecule (the changed structure's smarts will be [C](=[O])[O][CH3]). This process can be achieved by modifying the molecular substructure using `AllChem.ReplaceSubstructs`. Next, call the `Descriptors.TPSA` function to calculate the TPSA values of the molecule before and after methyl-esterification, and return the change in TPSA after methyl-esterification, with the result rounded to three decimal places.

#<INSERT>

def check(solve):
    assert abs(solve("CCC(=O)O")) - 11.0 < 1e-5
    assert abs(solve("c1cc(C(=O)O)cc(C(=O)O)c1")) - 22.0 < 1e-5
    assert abs(solve("c1cc(C(=O)O)c(CC(=O)O)c(C(=O)O)c1")) - 33.0 < 1e-5

check(solve)


#L2_B_60
from rdkit import Chem

def solve(smiles):
    mol = Chem.MolFromSmiles(smiles)
    rings = mol.GetRingInfo().BondRings()

    ring_smi_set = set()
    for ring in rings:
        ring_mol = Chem.PathToSubmol(mol, ring)
        ring_smi = Chem.MolToSmiles(ring_mol)
        ring_smi_set.add(ring_smi)
    return ring_smi_set

Please write a complete Python function `solve(smiles)`, which takes a molecule's SMILES as input,
extracts all the rings from its structure (only singular rings are included,
if there are multiple rings with shared atoms, they are also separately extracted as multiple singular rings.
The extracted structure does not include substituents connected on the ring),
and saves the ring structure as SMILES, returning a collection of all extracted ring SMILES.
In RDKit, you can first use `mol.GetRingInfo().BondRings()` to get tuples of chemical bond indices of all rings.
Then, use the `Chem.PathToSubmol()` function for each ring,
passing in the molecule mol object and each ring's chemical bond index tuple.
Save the ring structure as a separate mol object and finally convert it to SMILES and store it in the set.

#<INSERT>

def check(solve):
    assert solve('CC(CC1N=Cc2c(F)cccc21)n1cccc1') == {'c1ccccc1', 'C1=NCcc1', 'c1ccnc1'}
    assert solve('CC(C)CC1C=Cc2c(F)cccc21') == {'C1=CCcc1', 'c1ccccc1'}
    assert solve('Cc1ccc2c3c(c(F)c(N)cc13)CC2C') == {'c1ccCC1', 'c1ccccc1'}

check(solve)


#L2_B_48
from rdkit import Chem

def solve(smiles, atom_idx1, atom_idx2):
    mol = Chem.MolFromSmiles(smiles)
    rwmol = Chem.RWMol(mol)
    rwmol.AddBond(atom_idx1, atom_idx2, Chem.BondType.SINGLE)
    Chem.SanitizeMol(rwmol)
    new_mol = rwmol.GetMol()
    new_smiles = Chem.MolToSmiles(new_mol)
    return new_smiles

Please write a complete Python function `solve(smiles, atom_idx1, atom_idx2)` that
takes a SMILES as input and specifies the indices of two atoms.
Add a single bond between these two atoms and return the modified molecule's SMILES.
You can convert the `mol` to an editable `rwmol` object using `Chem.RWMol()`,
and then use `rwmol.AddBond()` to add a single bond between the atoms (Chem.BondType.SINGLE).
After that, perform a `Chem.SanitizeMol()` operation on the molecule,
and finally obtain the edited `mol` object using `rwmol.GetMol()`,
which can then be converted to SMILES.

#<INSERT>

def check(solve):
    assert solve('CCCC', 1, 3) == 'CC1CC1'
    assert solve('NCCC(C)C', 0, 3) == 'CC1(C)CCN1'

check(solve)


import pandas as pd

def proc_data():
    # 读取CSV文件
    data = pd.read_csv("0880.csv", header=None)

    # 计算第二列数据的总和
    second_column_sum = data.iloc[:, 1].sum()

    return second_column_sum

There is a dataset named '0880.csv', the first two rows of the data are as follows:
|    |   0 |           1 |
|---:|----:|------------:|
|  0 |   0 | 7.21983e-14 |
|  1 |   1 | 0.660026    |

Question:
Please calculate the sum of the second column in the CSV file.

The answer needs to meet the following requirements:
1. The data file is '0880.csv', please strictly refer to the data header and use python code to answer the question.
2. Use 'pandas.read_csv' to read the data, the default data is in the same path as the code; note that the CSV file has no header.
3. The analysis code should be written as a function named 'proc_data()', and this function does not require any input parameters. Use the sum mentioned in the question as the return value.

#<INSERT>

answer = proc_data()
assert round(answer, 3) == 179155.655


#L2_B_49
from rdkit import Chem

def solve(smiles, atom_idx):
    mol = Chem.MolFromSmiles(smiles)
    rwmol = Chem.RWMol(mol)
    rwmol.ReplaceAtom(atom_idx, Chem.Atom(7))
    Chem.SanitizeMol(rwmol)
    new_mol = rwmol.GetMol()
    new_smiles = Chem.MolToSmiles(new_mol)
    return new_smiles

Please write a complete Python function `solve(smiles, atom_idx)`,
which takes a SMILES string as input and specifies the index of an atom,
and replaces the specified atom with nitrogen.
You can use Chem.RWMol() to convert the mol object to an editable rwmol object,
and then use rwmol.ReplaceAtom() to replace the atom with a nitrogen atom (Chem.Atom(7)).
After that, perform Chem.SanitizeMol() operation, and finally obtain the edited mol object with rwmol.GetMol().
Convert it back to a SMILES string in the end.

#<INSERT>

def check(solve):
    assert solve('CCCC', 2) == 'CCNC'
    assert solve('NCCC(C)C', 1) == 'CC(C)CNN'

check(solve)


#L2_A_43
from rdkit import Chem

def solve(smiles):
    mol = Chem.MolFromSmiles(smiles)
    for atom in mol.GetAtoms():
        atom.SetIsotope(0)
    new_smiles = Chem.MolToSmiles(mol)
    return new_smiles

Please write a complete Python function `solve(smiles)` that takes a SMILES string as input,
removes all isotope labels on atoms in the molecule, and returns a SMILES string without isotopes.
It is known that in RDKit, `atom.SetIsotope()` can be used to set the isotope of an atom,
and when setting the isotope to 0,
the isotope label will not appear on the atom when saved as a SMILES string.

#<INSERT>

def check(solve):
    assert solve('[17CH3]CC(C)O') == 'CCC(C)O'
    assert solve('[NH3+]CC([O-])CC(=O)[O-]') == '[NH3+]CC([O-])CC(=O)[O-]'
    assert solve('[18*]CCc1ccccc1') == '*CCc1ccccc1'

check(solve)


#L2_A_41
from rdkit import Chem

def solve(smiles):
    mol = Chem.MolFromSmiles(smiles)
    return len([atom for atom in mol.GetAtoms() if atom.GetAtomicNum() > 2])

Please write a complete Python function `solve(smiles)`
that takes a SMILES as input and counts the number of heavy atoms in the molecule.
Heavy atoms refer to atoms with an atomic number greater than 2
and can be determined by checking if atom.GetAtomicNum() > 2.

#<INSERT>

def check(solve):
    assert solve('[OH]C(C)CC') == 5
    assert solve('[NH3+]CC([O-])CC(=O)[O-]') == 8
    assert solve('c1ccccc1') == 6

check(solve)


#L2_A_45
from rdkit import Chem

def solve(smiles):
    mol = Chem.MolFromSmiles(smiles)
    mol = Chem.AddHs(mol)
    return mol.GetNumAtoms()

Please write a complete Python function `solve(smiles)` that takes a SMILES string as input
and counts the total number of atoms in the molecule, including hydrogen atoms.
The input structure may contain implicit hydrogens,
so you need to first add hydrogens using `Chem.AddHs()`,
and then count the total number of atoms using `mol.GetNumAtoms()`.

#<INSERT>

def check(solve):
    assert solve('CCC') == 11
    assert solve('CC(=O)C') == 10
    assert solve('NCCC=O') == 12

check(solve)


def sum2():
    ret = 0
    i = 1
    while i < 101:
        ret += i
        i += 1
    return ret

The following code attempts to calculate the sum from 1 to 100, but it has some bugs. Please fix them and write down the corrected code.

```python
def sum2():
    ret = 0
    i = 1
    while i < 100:
        ret += i
    return ret
```

Question: Here is the following question:

Find the largest perfect square number less than the nth Fibonacci number

And the following code:

```python
import math

def fibonacci(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        a, b = 0, 1
        for _ in range(2, n + 1):
            a, b = b, a + b
        return b

def max_square_number(n):
    fib = fibonacci(n)
    perfect_squares = [i**2 for i in range(1, int(math.sqrt(fib)))]
    max_square = max(filter(lambda x: x < fib, perfect_squares))
    return max_square
```

There is an error in this code. Please find it and modify it to correct the code. Please write out the modified code.

Answer:
```python
import math

def fibonacci(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        a, b = 0, 1
        for _ in range(2, n + 1):
            a, b = b, a + b
        return b

def max_square_number(n):
    fib = fibonacci(n)
    perfect_squares = [i**2 for i in range(1, int(math.sqrt(fib)) + 1)]
    max_square = max(filter(lambda x: x < fib, perfect_squares))
    return max_square
```

----------------

Question:
Please identify the bug in the following code snippet and provide the corrected code. Please write out the complete corrected code.

def add_binary(a: str, b: str) -> str:
    x, y = int(a, 2), int(b, 2)
    while y:
        answer = x ^ y
        carry = (x && y) << 1
        x, y = answer, carry
    return bin(x)[2:]

Answer:
```python
def add_binary(a: str, b: str) -> str:
    x, y = int(a, 2), int(b, 2)
    while y:
        answer = x ^ y
        carry = (x & y) << 1
        x, y = answer, carry
    return bin(x)[2:]
```

----------------


import numpy as np

class SVMClassifier:
    def __init__(self):
        self.weights = None
        self.bias = None

    def train(self, X, y, learning_rate=0.001, epochs=10000):
        # Converting to numpy array
        X = np.array(X)
        y = np.array(y)

        # Initializing weights and bias
        self.weights = np.zeros(len(X[0]))
        self.bias = 0

        # Training using a simple gradient descent approach
        for _ in range(epochs):
            for idx, x_i in enumerate(X):
                condition = y[idx] * (np.dot(x_i, self.weights) - self.bias) >= 1
                if condition:
                    # Update for correctly classified points
                    self.weights -= learning_rate * (2 * self.weights)
                else:
                    # Update for incorrectly classified points
                    self.weights -= learning_rate * (2 * self.weights - np.dot(x_i, y[idx]))
                    self.bias -= learning_rate * y[idx]

    def predict(self, X):
        # Prediction
        X = np.array(X)
        linear_output = np.dot(X, self.weights) - self.bias
        print(np.sign(linear_output))
        return np.sign(linear_output)

Please implement a Support Vector Machine classifier in Python. You can define a custom class for the Support Vector Machine as given below:

class SVMClassifier:
    def __init__(self):
        self.weights = None
        self.bias = None

    def train(self, X, y, learning_rate=0.001, epochs=10000):
        pass

    def predict(self, X):
        pass

Where X is the feature data and y is the label data. This class has a method called predict. When this method receives a data point as an argument, it can predict the class label of this data.

To simplify the problem, you can assume that X is a list of points on the XY plane, and Y is a list of integers, representing the labels of the corresponding points in X. For example, X=[[1, 2], [2, 1], [3, 3], [4, 2]], y=[1, 1, -1, -1]

Please note, you are prohibited from directly using any library functions and classes related to Support Vector Machines (SVM).

#<INSERT>

import numpy as np

def svm_classifier(X, y):
    """
    Create an enhanced SVM classifier without using any external SVM libraries.

    :param X: Feature data, list of points on the XY plane.
    :param y: Labels for the data points, a list of integers.
    :return: A trained SVM model with a predict method.
    """
    model = SVMClassifier()
    model.train(X, y)
    return model

X = [[1, 2], [2, 1], [3, 3], [4, 2]]
y = [1, 1, -1, -1]
model = svm_classifier(X, y)
predictions = [model.predict(np.reshape(x, (1, 2))) for x in X]
accuracy = sum(1 for p, y_true in zip(predictions, y) if p == y_true) / len(y)
assert accuracy >= 0.75, "Model accuracy is lower than 75%."


from collections import Counter
import numpy as np

def k_nearest_neighbors(X_train, y_train, X_test, k):
    """
    Perform k-nearest neighbors classification.

    :param X_train: Training data features.
    :param y_train: Training data labels.
    :param X_test: Test data features.
    :param k: Number of nearest neighbors to consider.
    :return: List of predicted labels for the test data.
    """

    def euclidean_distance(point1, point2):
        """Calculate the Euclidean distance between two points."""
        return np.sqrt(np.sum((np.array(point1) - np.array(point2)) ** 2))

    predictions = []

    for test_point in X_test:
        # Calculate distances from the current test point to all training points
        distances = [euclidean_distance(test_point, train_point) for train_point in X_train]

        # Sort distances and select the indices of the top k nearest neighbors
        k_indices = np.argsort(distances)[:k]

        # Extract the labels of the k nearest neighbors
        k_nearest_labels = [y_train[i] for i in k_indices]

        # Determine the most common label among the nearest neighbors
        most_common = Counter(k_nearest_labels).most_common(1)
        predictions.append(most_common[0][0])

    return predictions

Please implement a k-nearest neighbors classifier in Python. The function is defined as def k_nearest_neighbors(X_train, y_train, X_test, k), where X_train (list of lists) and y_train (list) are the training data and labels, X_test (list of lists) is the test data, and k is the number of nearest neighbors. The return value of the function is a list, representing the predicted labels for each sample in X_test.

#<INSERT>

X_train = [[1, 2], [2, 3], [3, 3]]
y_train = [0, 1, 1]
X_test = [[1, 1]]
k = 2
assert k_nearest_neighbors(X_train, y_train, X_test, k) == [0], "Incorrect prediction."


import numpy as np
def generate_regression_data(size, dim, err_std=0.1):
    assert dim>10
    X=np.random.randn(size, dim)
    beta = np.array([2]*5+[-2]*5 + [0]*(dim-10))
    eps = np.random.randn(size)*err_std
    y = X@beta + eps
    return X,y

def lasso_coordinate_descent(X, y, lambda_, max_iter=1000, tol=1e-4):
    n, p = X.shape
    beta = np.zeros(p)
    beta_old = np.zeros(p)

    for iteration in range(max_iter):
        for j in range(p):
            residual = beta[j] * X[:, j] + y - X@beta
            rho = X[:, j].dot(residual)

            if rho < -lambda_ / 2:
                beta[j] = (rho + lambda_ / 2) / (X[:, j] ** 2).sum()
            elif rho > lambda_ / 2:
                beta[j] = (rho - lambda_ / 2) / (X[:, j] ** 2).sum()
            else:
                beta[j] = 0

        # Check for convergence
        if np.sqrt(np.sum((beta - beta_old) ** 2)) < tol:
            break

        beta_old = np.copy(beta)

    return beta

Please write two Python functions to implement the following functions using the numpy library:
(1) The function generate_regression_data(size, dim, err_std) will return the required data (X,y). Here we assume y=Xb+e, where X is a size*dim random matrix, with each element coming from the standard normal distribution; b is a dim (dim>10) dimensional vector, the first 5 digits are 2, the 6-10 digits are -2, and the rest are 0. e is an independent and identically distributed random noise of size, with a standard deviation of err_std, and the default value is 0.1.
(2) The function lasso_coordinate_descent(X,y,lambda_, max_iter,tol) uses the coordinate descent method to solve the Lasso problem, and returns a numpy array b which represents the optimal solution to the Lasso problem. The input X is a size*dim dimensional matrix, y is a dim dimensional vector, lambda_ is a given scalar, max_iter indicates the maximum number of iterations of the optimization process, with a default value of 1000, tol indicates the error range of the L2 norm of b when judging convergence, and the default value is 1e-4.

Question: Please calculate the coefficient of the x^2 term after expanding the equation (x^3 + 1)^2 (x - 3) (x^2 + 3x + 2) in Python, and define the function 'solve' to tackle it.

Answer:
```python

from sympy import symbols, expand

# Define the function to solve for the coefficient of x^2 term
def solve():
    # Define symbols
    x = symbols('x')

    # Given expression
    expression = (x**3 + 1)**2 * (x - 3) * (x**2 + 3*x + 2)

    # Expand the expression
    expanded_expression = expand(expression)

    # Coefficient of x^2 term
    coeff_x2 = expanded_expression.coeff(x, 2)

    return coeff_x2

```

----------------

Question: Please calculate the multiplication of two matrices, define the function 'mul(A, B)' in python, input matrices A and B, and output their multiplication using numpy implementation.

Answer:
```python

import numpy as np

def mul(A, B):
    """
    Multiply two matrices A and B using NumPy.

    Parameters:
    A (numpy.ndarray): Matrix A
    B (numpy.ndarray): Matrix B

    Returns:
    numpy.ndarray: The result of multiplying matrix A by matrix B.
    """
    return np.dot(A, B)

```

----------------

#<INSERT>

np.random.seed(42)
X, y = generate_regression_data(1000,100)
lambda_=0.1
beta_estimated = lasso_coordinate_descent(X, y, lambda_)
assert all(1.9 < beta_estimated[i] < 2.1 for i in range(5))
assert all(-2.1 < beta_estimated[i] < -1.9 for i in range(5,10))
assert all(-0.1 < beta_estimated[i] < 0.1 for i in range(10,100))


import torch
import torch.nn as nn
import torch.nn.functional as F
import math

class MultiHeadSelfAttention(nn.Module):
    def __init__(self, n_head, dim, p_drop=0.1):
        super(MultiHeadSelfAttention, self).__init__()
        self.dim = dim
        self.n_head = n_head
        self.head_dim = dim // n_head
        assert self.head_dim * n_head == dim, "dim must be divisible by n_head"

        self.qkv = nn.Linear(dim, dim * 3)  # 生成Q, K, V
        self.dropout = nn.Dropout(p_drop)
        self.out = nn.Linear(dim, dim)

    def forward(self, x):
        B, T, C = x.shape
        qkv = self.qkv(x).reshape(B, T, 3, self.n_head, self.head_dim).permute(2, 0, 3, 1, 4)
        q, k, v = qkv[0], qkv[1], qkv[2]  # 分离查询、键、值

        # 计算注意力分数
        attn = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(self.head_dim))
        attn = F.softmax(attn, dim=-1)
        attn = self.dropout(attn)

        # 应用注意力机制
        weighted_avg = attn @ v
        weighted_avg = weighted_avg.transpose(1, 2).reshape(B, T, C)

        return self.out(weighted_avg)

Implement a Multi-Head Self Attention module used in a Transformer model using PyTorch.
Define a Module called MultiHeadSelfAttention:
1. During initialization, specify the number of heads n_head, the size of the dimensions dim, and the dropout ratio p_drop in order.
2. During forward, the input is a tensor with a shape of [batch_size, seq_len, dim], and the output is a tensor with the same shape.


def auc(data):
    # Sort the data by the predicted probability in descending order
    data_sorted = sorted(data, key=lambda x: x[0], reverse=True)

    # Calculate the number of positive and negative examples
    n_positives = sum(1 for score, label in data if label == 1)
    n_negatives = len(data) - n_positives

    # Initialize variables to calculate AUC
    auc_ret = 0.0
    n_tp = 0  # number of true positives
    n_fp = 0  # number of false positives

    # Calculate AUC using the trapezoidal rule
    for i in range(len(data_sorted)):
        # If the label is 1, it's a true positive
        if data_sorted[i][1] == 1:
            n_tp += 1
        # If the label is 0, it's a false positive
        else:
            n_fp += 1
            # Update AUC for each false positive by the fraction of true positives so far
            auc_ret += n_tp / n_positives

    # Normalize AUC by the total number of pairs
    auc_ret /= n_negatives
    return auc_ret

Given an array containing tuples of (prediction, label), where label = 0 indicates negative samples, label = 1 indicates positive samples, and prediction represents the probability that a machine learning model estimates this sample to be a positive sample.
Write a Python function auc that takes this array as input and returns the corresponding AUC. Use of third-party libraries is not allowed.


def linear_regression_gradient_descent(X, y, learning_rate, iterations):
    m, n = len(X), len(X[0])  # m为样本数，n为特征数
    X = [[1] + list(row) for row in X]  # 添加一列1作为截距的系数
    theta = [0] * (n + 1)  # 初始化参数（包含截距）

    # 梯度下降
    for _ in range(iterations):
        gradients = [0] * (n + 1)

        # 计算梯度
        for i in range(m):
            error = sum(theta[j] * X[i][j] for j in range(n + 1)) - y[i]
            for j in range(n + 1):
                gradients[j] += (error * X[i][j]) / m

        # 更新参数
        for j in range(n + 1):
            theta[j] -= learning_rate * gradients[j]

    # 第一个参数是截距，其余是系数
    intercept = theta[0]
    coefficients = theta[1:]

    return coefficients, intercept

Please implement a simple linear regression model using Python, using gradient descent. The function is defined as def linear_regression_gradient_descent(X, y, learning_rate, iterations), where X is the feature data (two-dimensional array or list), y is the target data (one-dimensional array or list), learning_rate is the learning rate, and iterations is the number of iterations for gradient descent.
The return value of the function is a tuple, containing the coefficients and intercept of the model.

#<INSERT>

import numpy as np

def least_squares(X, y):
    X_b = np.c_[np.ones((len(X), 1)), X]  # Add x0 = 1 to each instance
    theta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y)
    intercept = theta_best[0]
    coefficients = theta_best[1:]
    return coefficients, intercept

# Driver Code
X = [[1], [2], [3], [4]]
y = [2, 3, 5, 7]
learning_rate = 0.01
iterations = 10000

# Gradient Descent Linear Regression
coefficients_gd, intercept_gd = linear_regression_gradient_descent(X, y, learning_rate, iterations)
print(coefficients_gd, intercept_gd)

# Least Squares Linear Regression (for comparison)
coefficients_ls, intercept_ls = least_squares(X, y)
print(coefficients_ls, intercept_ls)

# Compare coefficients
for coef_gd, coef_ls in zip(coefficients_gd, coefficients_ls):
    assert abs(coef_gd - coef_ls) < 0.1, "Gradient Descent coefficient differs from Least Squares coefficient by more than 0.1"

# Compare intercepts
assert abs(intercept_gd - intercept_ls) < 0.1, "Gradient Descent intercept differs from Least Squares intercept by more than 0.1"


def multiply_sparse_matrices(matrix1, matrix2):
    """
    Multiply two sparse matrices.

    Args:
    - matrix1: Dictionary representing the first sparse matrix.
    - matrix2: Dictionary representing the second sparse matrix.

    Returns:
    - Dictionary representing the product sparse matrix.
    """
    result = {}
    for (i, k1), v1 in matrix1.items():
        for (k2, j), v2 in matrix2.items():
            if k1 == k2:
                if (i, j) not in result:
                    result[(i, j)] = 0
                result[(i, j)] += v1 * v2

    return {k: v for k, v in result.items() if v != 0}  # Remove zero elements

Create a Python function to perform the multiplication of two sparse matrices.
Sparse matrices are matrices in which most elements are zero. These can be represented efficiently in a format that only stores non-zero elements.
Assume the sparse matrices are represented as dictionaries, where each key is a tuple (row, column) and the corresponding value is the non-zero element.
Define the function as def multiply_sparse_matrices(matrix1, matrix2), where matrix1 and matrix2 are the two sparse matrices to be multiplied.
You should return the result as sparse representation.
Note the index of row/column startswith 0.

#<INSERT>

matrix1 = {(0, 1): 2, (1, 0): 3}
matrix2 = {(1, 0): 4, (0, 1): 5}
product_matrix = multiply_sparse_matrices(matrix1, matrix2)
assert product_matrix[(0, 0)] == 8
assert product_matrix[(1, 1)] == 15


from sympy import Matrix

def is_spanning_set_of_null_space_of_M(vector_set):
    M = Matrix([[1, 3, -2], [2, 1, -1], [-4, -2, 2]])
    # 计算 M 的零空间
    null_space = M.nullspace()

    input_vectors = [Matrix(v) for v in vector_set]

    # 检查每个输入向量是否在 M 的零空间中
    for v in input_vectors:
        if not (M * v).is_zero_matrix:
            return False

    combined_space = Matrix.hstack(*input_vectors)
    # 检查零空间中的向量是否都可以由输入向量的线性组合表示
    for ns_vec in null_space:
        # 使用 sympy 的线性求解器来判断是否可以由输入向量的线性组合表示
        try:
            _ = combined_space.LUsolve(ns_vec)
        except ValueError:
            return False

    return True

Write a Python function is_spanning_set_of_null_space_of_M(vector_set), the purpose of which is to determine whether the given vector set vector_set constitutes the generating set of the null space for a specific matrix M.
Here, matrix M is a known 3x3 real matrix, defined as M = [[1,3,-2], [2,1,-1],[-4,-2,2]].


def calculate_metrics(FN, TN, FP, TP):
    """
    Calculate the Recall, Precision, and Accuracy of a classifier.

    :param FN: False Negatives
    :param TN: True Negatives
    :param FP: False Positives
    :param TP: True Positives
    :return: A tuple containing Recall, Precision, and Accuracy
    """
    # Calculating Recall
    Recall = TP / (TP + FN) if (TP + FN) != 0 else 0

    # Calculating Precision
    Precision = TP / (TP + FP) if (TP + FP) != 0 else 0

    # Calculating Accuracy
    Accuracy = (TP + TN) / (TP + FP + FN + TN) if (TP + FP + FN + TN) != 0 else 0

    return Recall, Precision, Accuracy

Please implement a function in Python to calculate the Recall, Precision, Accuracy of a classifier. The function is defined as def calculate_metrics(FN, TN, FP, TP), where FN, TN, FP, TP represent the number of false negatives, true negatives, false positives, and true positives, respectively. The return value of the function should be a tuple consisting of the calculation results of Recall, Precision, and Accuracy.

#<INSERT>

# Test case 1
FN1, TN1, FP1, TP1 = 10, 50, 5, 35
recall1, precision1, accuracy1 = calculate_metrics(FN1, TN1, FP1, TP1)
assert recall1 == 35 / (35 + 10), "Recall calculation is incorrect."
assert precision1 == 35 / (35 + 5), "Precision calculation is incorrect."
assert accuracy1 == (50 + 35) / (10 + 50 + 5 + 35), "Accuracy calculation is incorrect."

# Test case 2
FN2, TN2, FP2, TP2 = 20, 80, 10, 40
recall2, precision2, accuracy2 = calculate_metrics(FN2, TN2, FP2, TP2)
assert recall2 == 40 / (40 + 20), "Recall calculation is incorrect for test case 2."
assert precision2 == 40 / (40 + 10), "Precision calculation is incorrect for test case 2."
assert accuracy2 == (80 + 40) / (20 + 80 + 10 + 40), "Accuracy calculation is incorrect for test case 2."


import math

def wasserstein_distance_normal(mean1, std1, mean2, std2):
    """
    Calculate the Wasserstein Distance between two normal distributions.

    Args:
    - mean1: Mean of the first normal distribution.
    - std1: Standard deviation of the first normal distribution.
    - mean2: Mean of the second normal distribution.
    - std2: Standard deviation of the second normal distribution.

    Returns:
    - Wasserstein Distance as a float.
    """
    return math.sqrt((mean1 - mean2) ** 2 + (std1 - std2) ** 2)

Develop a Python function to calculate the Wasserstein Distance (also known as the Earth Mover's Distance) between two normal (Gaussian) distributions. The Wasserstein Distance is a measure of the distance between two probability distributions. For normal distributions, it has a closed-form solution. Define the function as def wasserstein_distance_normal(mean1, std1, mean2, std2), where mean1 and std1 are the mean and standard deviation of the first normal distribution, and mean2 and std2 are those of the second distribution.

#<INSERT>

assert abs(wasserstein_distance_normal(0, 1, 2, 3) - 2.828427) < 1e-5
assert abs(wasserstein_distance_normal(0, 1, 2, 1) - 2) < 1e-5
assert abs(wasserstein_distance_normal(0, 1, 0, 1) - 0) < 1e-5


from scipy.cluster.hierarchy import linkage, cophenet
from scipy.spatial.distance import pdist
import numpy as np

def simulate_and_cluster(mu1,sigma1,mu2,sigma2,size1,size2):
    # generate two clusters: a with 100 points, b with 50:
    a = np.random.multivariate_normal(mu1, sigma1, size=[size1,])
    b = np.random.multivariate_normal(mu2, sigma2, size=[size2,])
    X = np.concatenate((a, b),)
    Z = linkage(X,'ward')
    c,_ = cophenet(Z, pdist(X))
    return c

Write a python function simulate_and_cluster(mu1,sigma1,mu2,sigma2,size1,size2) to implement the following function: it takes random numbers from the multivariate normal distribution N(mu1,sigma1) and N(mu2,sigma2) of size1 and size2 respectively, then uses the scipy library to perform ward hierarchical clustering with default parameters, and returns a scalar value representing the cophenetic correlation coefficient.


def solve(profit):
    # Setting up the profit thresholds and corresponding bonus rates
    thresholds = [100, 60, 40, 20, 10, 0]
    rates = [0.01, 0.015, 0.03, 0.05, 0.075, 0.1]

    bonus = 0
    for i in range(len(thresholds)):
        if profit > thresholds[i]:
            bonus += (profit - thresholds[i]) * rates[i]
            profit = thresholds[i]  # Update profit for the next threshold

    return bonus

The bonuses distributed by the company are based on profit sharing. When the profit (I) is less than or equal to 100,000 yuan, the bonus can be 10%;
If the profit is more than 100,000 yuan but less than 200,000 yuan, the part below 100,000 yuan is paid at a 10% rate, and the part above 100,000 yuan can be paid at a 7.5% rate;
When it is between 200,000 and 400,000 yuan, the part above 200,000 yuan can be paid at a 5% rate;
When it is between 400,000 and 600,000 yuan, the part above 400,000 yuan can be paid at a 3% rate;
When it is between 600,000 and 1 million yuan, the part above 600,000 yuan can be paid at a 1.5% rate;
When it is more than 1 million yuan, the part exceeding 1 million yuan is paid at a 1% rate;
Given the profit I in a given month, how much should the total bonus be in yuan?
Please use python to write code to calculate. Define a function named solve, which takes the given profit x as input, and returns a number representing the answer.


import math

def frobenius_norm_sparse_matrix(sparse_matrix):
    """
    Calculate the Frobenius norm of a sparse matrix.

    Args:
    - sparse_matrix: Dictionary representing the sparse matrix.

    Returns:
    - Frobenius norm as a float.
    """
    sum_of_squares = sum(value**2 for value in sparse_matrix.values())
    norm = math.sqrt(sum_of_squares)
    return norm

# Example usage
sparse_matrix = {(0, 1): 3, (2, 2): 4, (3, 3): 5}
norm = frobenius_norm_sparse_matrix(sparse_matrix)
print("Frobenius Norm of Sparse Matrix:", norm)

Implement the Frobenius norm in Python, which is defined as the square root of the sum of the absolute squares of its elements. Assume the sparse matrix is represented as a dictionary, with keys as tuples (row, column) representing the indices of non-zero elements, and values as the non-zero elements themselves. Define the function as def frobenius_norm_sparse_matrix(sparse_matrix).

#<INSERT>

assert abs(frobenius_norm_sparse_matrix({(0, 1): 3, (2, 2): 4, (3, 3): 5}) - 7.071068) < 1e-5
assert abs(frobenius_norm_sparse_matrix({(0, 2): 3, (2, 2): 4, (3, 3): 5}) - 7.071068) < 1e-5
assert abs(frobenius_norm_sparse_matrix({}) - 0) < 1e-5


def determinant(matrix):
    """
    Calculate the determinant of a matrix using recursive expansion by minors.
    """
    # Base case for 2x2 matrix
    if len(matrix) == 2:
        return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0]

    det = 0
    for c in range(len(matrix)):
        # Create a submatrix excluding the current row and column
        submatrix = [row[:c] + row[c+1:] for row in matrix[1:]]
        # Recursively expand along the first row
        det += matrix[0][c] * determinant(submatrix) * (-1) ** c
    return det

Please implement in Python to calculate the determinant of a matrix. The function is defined as def determinant(matrix), where matrix is the input matrix, which is a list data type. Please note that library functions cannot be called directly in the function implementation.


def is_eigenvalue(matrix, value):
    """
    Check if the given value is an eigenvalue of the matrix.
    """
    # Convert the matrix and value into a NumPy array for easier manipulation
    import numpy as np
    matrix = np.array(matrix)
    value = np.array(value)

    # Calculate the matrix minus lambda times the identity matrix
    identity = np.eye(len(matrix))
    modified_matrix = matrix - value * identity

    # Check if the determinant of (matrix - lambda * identity) is zero
    return np.linalg.det(modified_matrix) == 0

Please implement a function in Python to determine whether a certain value is an eigenvalue of a certain matrix. The function is defined as def is_eigenvalue(matrix, value), where matrix is a 2D list, and value is a number.

#<INSERT>

matrix = [[2, 0], [0, 1]]
value1 = 5
value2 = 1

assert(is_eigenvalue(matrix, value1) == False)
assert(is_eigenvalue(matrix, value2) == True)


import math

def solve_quad(a, b, c):
    if a == 0:
        if b == 0:
            return []
        return -c / b

    # Compute the discriminant
    D = b**2 - 4*a*c

    # Check if the discriminant is positive, zero or negative
    if D > 0:
        # Two real and distinct solutions
        x1 = (-b - math.sqrt(D)) / (2 * a)
        x2 = (-b + math.sqrt(D)) / (2 * a)
        return [x1, x2]
    elif D == 0:
        # Two real and identical solutions
        x = -b / (2 * a)
        return [x]
    else:
        # No real solution
        return []

Implement Python function `solve_quad(a, b, c)` that outputs a list of the real solutions of `ax^2 + bx + c = 0`. You are only allowed to use `math` package.

#<INSERT>

def check():
    solutions = [round(x, 8) for x in solve_quad(1, -3, 2)]
    assert len(solutions) == 2 and set(solutions) == {1.0, 2.0}
    solutions = [round(x, 8) for x in solve_quad(1, -2, 1)]
    assert len(solutions) == 1 and set(solutions) == {1.0}
    assert solve_quad(1, -3, 1) == []
    solutions = [round(x, 8) for x in solve_quad(0, 2, -1)]
    assert solutions == [0.5]


def lp_distance(arr1, arr2, p):
    """
    Compute the L^p distance between two arrays.

    :param arr1: First array
    :param arr2: Second array
    :param p: The order of the norm (p)
    :return: L^p distance
    """
    if len(arr1) != len(arr2):
        raise ValueError("Arrays must be of the same length")

    # Compute the L^p distance
    distance = sum(abs(a - b) ** p for a, b in zip(arr1, arr2)) ** (1 / p)
    return distance

Please implement a function in Python to calculate the L^p distance between two arrays. The function is defined as def lp_distance(arr1, arr2, p), where arr1 and arr2 are two arrays, and the value of p determines which p-norm to use.
Please note that in the function implementation, you cannot call library functions to calculate directly.


def solve():
    def find_x_y():
        for y_candidate in range(13):
            x_candidate = (1 - 7 * y_candidate) % 13
            if (3 * x_candidate + 2 * y_candidate) % 13 == 5:
                return x_candidate, y_candidate
        return None, None

    # Find x and y
    x, y = find_x_y()

    # If x and y were found, compute 5x + 3y modulo 13
    assert x is not None and y is not None
    return (5 * x + 3 * y) % 13

It's known that the positive integers x and y satisfy: 3x+2y = 5 (mod 13) and x + 7y = 1(mod 13).
Please write a Python function `solve()`, to find out the solution of N for: 5x+3y = N (mod 13), meaning to find out the modulo 13 residue of 5x+3y.


def sum_sparse_matrix(sparse_matrix):
    """
    Calculate the sum of all elements in a sparse matrix.

    Args:
    - sparse_matrix: List of tuples, each tuple represents (row_index, col_index, value) of non-zero elements.

    Returns:
    - Sum of all elements in the sparse matrix.
    """
    total_sum = sum(value for _, _, value in sparse_matrix)
    return total_sum

Develop a Python function to calculate the sum of all elements in a sparse matrix. A sparse matrix is a matrix in which most of the elements are zero. These matrices can be represented efficiently using data structures that store only the non-zero elements. Define the function as def sum_sparse_matrix(sparse_matrix), where sparse_matrix is a representation of a sparse matrix, such as a list of tuples with each tuple containing the row index, column index, and value of a non-zero element.


import numpy as np
def inverse_power_iteration(matrix, num_simulations):
    # 初始化随机向量
    b_k = np.random.rand(matrix.shape[1])

    for _ in range(num_simulations):
        # 解线性系统 Ax = b_k
        # 使用NumPy的linalg.solve来避免直接计算逆矩阵
        b_k1 = np.linalg.solve(matrix, b_k)

        # 计算范数
        b_k1_norm = np.linalg.norm(b_k1)

        # 归一化
        b_k = b_k1 / b_k1_norm

    # 最小特征值的估计是向量b_k1和b_k的比率
    return b_k1_norm

Please write a python function inverse_power_iteration(matrix,num_simulations) to calculate the smallest eigenvalue of a positive definite matrix. The function specifies the matrix as 'matrix' and the number of iterations as 'num_simulations', and it returns a scalar representing the smallest eigenvalue.

#<INSERT>
import numpy as np

def test_inverse_power_iteration():
    # 测试简单对角矩阵
    diagonal_matrix = np.diag([1, 2, 3])
    assert abs(inverse_power_iteration(diagonal_matrix, 100) - 1) < 1e-4

    # 测试收敛性
    matrix = np.array([[2, -1, 0], [-1, 2, -1], [0, -1, 2]])
    eigenvalue1 = inverse_power_iteration(matrix, 50)
    eigenvalue2 = inverse_power_iteration(matrix, 100)
    assert abs(eigenvalue1 - eigenvalue2) < 1e-4

# 运行测试
test_inverse_power_iteration()


import numpy as np

def circulant_matrix(first_row):
    """
    Construct a circulant matrix from the first row.
    """
    n = len(first_row)
    circ_matrix = np.zeros((n, n))

    for i in range(n):
        circ_matrix[i] = np.roll(first_row, -i)

    return circ_matrix

# Example usage
first_row = [1, 2, 3]
circ_matrix = circulant_matrix(first_row)

Please implement a function in Python, given the first row of the matrix, to generate a circulant matrix. The function is defined as def circulant_matrix(first_row), where first_row is a list, such as [3, 2, 1]. Then the circulant matrix generated from that row should be [[3.0, 2.0, 1.0], [2.0, 1.0, 3.0], [1.0, 3.0, 2.0]].

#<INSERT>

import numpy as np

first_row = [1, 2, 3]
circ_matrix = circulant_matrix(first_row)
if isinstance(circ_matrix, np.ndarray):
    assert(circ_matrix[0,0] == 1)
    assert(circ_matrix[0,1] == 2)
    assert(circ_matrix[0,2] == 3)
    assert(circ_matrix[1,0] == 2)
    assert(circ_matrix[1,1] == 3)
    assert(circ_matrix[1,2] == 1)
    assert(circ_matrix[2,0] == 3)
    assert(circ_matrix[2,1] == 1)
    assert(circ_matrix[2,2] == 2)
elif isinstance(circ_matrix, list):
    assert(circ_matrix[0][0] == 1)
    assert(circ_matrix[0][1] == 2)
    assert(circ_matrix[0][2] == 3)
    assert(circ_matrix[1][0] == 2)
    assert(circ_matrix[1][1] == 3)
    assert(circ_matrix[1][2] == 1)
    assert(circ_matrix[2][0] == 3)
    assert(circ_matrix[2][1] == 1)
    assert(circ_matrix[2][2] == 2)
else:
    raise TypeError(type(circ_matrix))


from shapely.geometry import LineString

def solve(segments):
    intersections = set()
    for i in range(len(segments)):
        for j in range(i + 1, len(segments)):
            line1 = LineString(segments[i])
            line2 = LineString(segments[j])
            if line1.intersects(line2):
                point = line1.intersection(line2)
                if "Point" == point.geom_type:
                    intersections.add((point.x, point.y))
    return len(intersections)

Given N line segments, return the number of their intersections. Solve with the shapely library, define a Python function solve, input is a list of line segments, output is the number of intersections.


def transpose_sparse_matrix(sparse_matrix):
    """
    Transpose a sparse matrix.

    Args:
    - sparse_matrix: Dictionary representing the sparse matrix.

    Returns:
    - Transposed sparse matrix as a dictionary.
    """
    transposed_matrix = {(col, row): value for (row, col), value in sparse_matrix.items()}
    return transposed_matrix

Develop a Python function to transpose a sparse matrix. Sparse matrices are matrices in which most of the elements are zero. These matrices can be efficiently represented by storing only the non-zero elements. In this task, assume the sparse matrix is represented as a dictionary, where keys are tuples representing the (row, column) indices of non-zero elements and values are the corresponding non-zero values. Define the function as def transpose_sparse_matrix(sparse_matrix), where sparse_matrix is the dictionary representation of a sparse matrix.

#<INSERT>

sparse_matrix = {(0, 1): 2, (1, 0): 3, (2, 2): 5}
transposed_matrix = transpose_sparse_matrix(sparse_matrix)

for (i, j), val in sparse_matrix.items():
    assert transposed_matrix[(j, i)] == val


import math

def solve(alpha, x, eps=1e-5):
    def bessel_term(n, alpha, x):
        return ((-1)**n / (math.factorial(n) * math.factorial(n + alpha)) *
                (x / 2)**(2 * n + alpha))

    sum_val = 0.0
    n = 0
    while True:
        term = bessel_term(n, alpha, x)
        sum_val += term
        n += 1
        if abs(term) < eps:
            break
    return sum_val

Define a function solve(alpha, x) in python to calculate the value of the Bessel function of the first kind J(alpha, x) given alpha and x, without invoking scipy, to reach an accuracy of 1e-5.

#<INSERT>

import scipy.special

for i in range(10):
    assert abs(scipy.special.jv(2, i) - solve(2, i)) < 1e-5
    assert abs(scipy.special.jv(1, i) - solve(1, i)) < 1e-5


import numpy as np

def power_iteration(matrix, num_simulations: int):
    # 随机选择一个初始向量
    b_k = np.random.rand(matrix.shape[1])

    for _ in range(num_simulations):
        # 计算矩阵乘以向量
        b_k1 = np.dot(matrix, b_k)

        # 计算范数
        b_k1_norm = np.linalg.norm(b_k1)

        # 归一化
        b_k = b_k1 / b_k1_norm

    return b_k1_norm

Please write a Python script to compute the principal eigenvalue of a matrix by the power iteration method. The function power_iteration(matrix, num_simulations) should be defined in Python for this purpose, where num_simulations is the number of iterations.

#<INSERT>

import numpy as np
def test_power_iteration():
    # 测试对角矩阵
    diagonal_matrix = np.diag([2, 3, 4])
    assert abs(power_iteration(diagonal_matrix, 100) - 4) < 1e-4
    # 测试收敛性
    matrix = np.array([[2, -12], [1, -5]])
    eigenvalue1 = power_iteration(matrix, 50)
    eigenvalue2 = power_iteration(matrix, 100)
    assert abs(eigenvalue1 - eigenvalue2) < 1e-4

# 运行测试
test_power_iteration()


from scipy.optimize import brentq
import numpy as np
from scipy.special import erf

def solve():
    def gelu(x):
        return 0.5 * x * (1 + erf(x / np.sqrt(2)))

    def linear(x):
        return x / 10

    def find_intersection(x):
        return gelu(x) - linear(x)

    root = brentq(find_intersection, -10.0, -0.001)
    return root, gelu(root)

Calculate the intersection point between the GeLU activation function and f(x) = x/10 when x < 0, and return the x and y values of the intersection point. Write Python code, define a function `solve()`, to return the result.


def can_form_triangle(a, b, c):
    # Check if any edge is zero or negative
    if a <= 0 or b <= 0 or c <= 0:
        return False

    # Check if any sum of two edges is less than or equal to the third edge
    if a + b <= c or a + c <= b or b + c <= a:
        return False

    # Check if the three edges can form a triangle
    return True

Implement Python function `can_form_triangle(a, b, c)` to determine whether edges of length `a`, `b`, `c` can form a triangle.

#<INSERT>

def check():
    assert not can_form_triangle(1, 2, 3)
    assert can_form_triangle(3, 4, 5)
    assert can_form_triangle(0.9, 0.9, 0.9)
    assert not can_form_triangle(5, 12, 18)
check()


from scipy.optimize import minimize_scalar
import numpy as np

def solve():
    # Define the function to minimize
    func = lambda x: np.sin(x) * np.exp(-0.1 * (x - 0.6)**2)

    # Find the minimum in the range [0, 10]
    result = minimize_scalar(func, bounds=(0, 10), method='bounded')

    return result.fun

Calculate the minimum value of $sin(x)exp[-0.1*(x - 0.6)^2]$ within the range [0, 10] using scipy. Define a Python function `solve()` to perform this task, and return a floating point number.


import numpy as np

def kernel_norm(matrix):
    """
    Calculate the kernel (nuclear) norm of a matrix.

    Args:
    - matrix: List of lists representing the matrix.

    Returns:
    - Kernel norm as a float.
    """
    U, s, V = np.linalg.svd(matrix)
    return np.sum(s)

Write a Python function to calculate the kernel norm of a matrix. The kernel norm (also known as the nuclear norm) is the sum of the singular values of the matrix. It's often used in machine learning and statistics, particularly in the context of regularization in certain optimization problems. Define the function as def kernel_norm(matrix), where matrix is a list of lists representing the matrix.


def is_fibonacci_number(n):
    """
    A number is a Fibonacci number if and only if one or both of
    (5 * n * n + 4) or (5 * n * n - 4) is a perfect square.
    """
    def is_perfect_square(x):
        s = int(x**0.5)
        return s*s == x

    return is_perfect_square(5 * n * n + 4) or is_perfect_square(5 * n * n - 4)

Given a positive integer, please write a Python code to determine whether it is a Fibonacci number, using the Python function is_fibonacci_number to solve it.

#<INSERT>

def check():
	assert is_fibonacci_number(1) is True
	assert is_fibonacci_number(2) is True
	assert is_fibonacci_number(3) is True
	assert is_fibonacci_number(5) is True
	assert is_fibonacci_number(8) is True
	assert is_fibonacci_number(13) is True
	assert is_fibonacci_number(14) is False
	assert is_fibonacci_number(15) is False
	assert is_fibonacci_number(16) is False

check()


import numpy as	np
from scipy.optimize import fmin_bfgs

def rosen(x):
   return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0) + sum((1-x)**2.0)

def find_min_rosen(x0):
   res = fmin_bfgs(rosen,x0)
   return res

Please write a Python function find_min_rosen(x0) that uses Scipy's optimizer, the L-BFGS algorithm, to solve for the minimum value of the Rosenbrock function given the initial value (numpy.array) x0. The Rosen function is defined as $$f(x)==\sum_i^{d-1}[100(x_{i+1}-x_i^2)^2 + (x_i-1)^2]$$. The function should return a numpy array representing the optimal solution to this optimization problem.

#<INSERT>

x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
res = find_min_rosen(x0)
assert all(np.abs(res[i]-1) < 1e-4 for i in range(len(x0)))


import shapely.geometry as sg

def solve(polygon1, polygon2):
    polygon1_shapely = sg.Polygon(polygon1)
    polygon2_shapely = sg.Polygon(polygon2)

    intersection = polygon1_shapely.intersection(polygon2_shapely)
    if intersection == None:
        return 0.0
    else:
        return intersection.area

Given two polygons, return their overlapping area, if they do not overlap, return 0. Use the shapely library to solve, define a Python function called solve, which takes as input two lists of vertices of polygons, and returns the overlapping area.


from sympy import symbols, Eq, solve

def f():
    total_parts = symbols('total_parts')

    equation = Eq(total_parts, (2/7) * total_parts + 1600 + 1/2 * ((2/7) * total_parts + 1600))

    solution = solve(equation, total_parts)

    return int(solution[0])

A workshop has three teams working on a batch of parts. The first team completed 2/7 of the total, the second team completed 1600 parts and the third team completed half of the total number of parts the first two teams completed. Please find out the total number of parts. Please solve this using python codes, with the function name `f()`, and return an integer.


def square_dist(p: dict) -> dict:
    square_p = {}
    for x, prob in p.items():
        square_x = x ** 2
        if square_x in square_p:
            square_p[square_x] += prob
        else:
            square_p[square_x] = prob
    return square_p

Implement Python function `square_dist(p: dict) -> dict` that takes a distribution `p` of random variable `X` as input and output the distribution of `X^2`.

#<INSERT>

def check():
    import numpy as np
    def _assert_equal(a, b):
        assert type(a) == type(b)
        if isinstance(a, (list, tuple)):
            assert len(a) == len(b)
            assert all([_assert_equal(ai, bi) for ai, bi in zip(a, b)])
        elif isinstance(a, dict):
            assert set(a.keys()) == set(b.keys())
            for k in a:
                _assert_equal(a[k], b[k])
        else:
            np.testing.assert_almost_equal(a, b, decimal=8)
    p1 = {-3: 0.1, -2: 0.2, -1: 0.1, 0: 0.2, 1: 0.1, 2: 0.2, 3: 0.1}
    _assert_equal(square_dist(p1), {9: 0.2, 4: 0.4, 1: 0.2, 0: 0.2})
    p2 = {0: 0.1, 1: 0.3, 2: 0.2, 3: 0.4}
    print(square_dist(p2))
check()


import shapely.geometry as sg

def solve(polygon1, polygon2):
    # 将多边形转换为 Shapely 对象
    polygon1_shapely = sg.Polygon(polygon1)
    polygon2_shapely = sg.Polygon(polygon2)

    # 判断两个多边形是否重叠
    return polygon1_shapely.intersects(polygon2_shapely)

Given two polygons, determine whether they overlap. Solve this with the shapely library, defining the Python function solve, input two vertex lists of the polygons, return a bool value indicating whether they overlap.


def is_symmetric(matrix):
    """
    Check if a square 2D array is symmetric.
    """
    n = len(matrix)
    for i in range(n):
        for j in range(n):
            if matrix[i][j] != matrix[j][i]:
                return False
    return True

Write a Python function to check if a square 2D array is symmetric. The function definition should be def is_symmetric(matrix), where matrix is a square 2D array.

#<INSERT>

matrix1 = [[1, 2, 3], [2, 5, 6], [3, 7, 9]]
matrix2 = [[1, 2, 3], [2, 5, 4], [3, 4, 9]]

is_symmetric_matrix1 = is_symmetric(matrix1)
is_symmetric_matrix2 = is_symmetric(matrix2)

assert(is_symmetric_matrix1 == False)
assert(is_symmetric_matrix2 == True)


import numpy as np

def marginal(m: np.ndarray):
    rows, cols = m.shape
    X = np.sum(m, axis=1)
    Y = np.sum(m, axis=0)
    return X / np.sum(X), Y / np.sum(Y)

Implement Python function `marginal(m: numpy.ndarray): numpy.ndarray`, such that give a matrix `m` representing the joint distribution of two random variables `X` and `Y`, where `m[i][j]=P(X=i, Y=j)`, return the marginal distribution of `X` and `Y` representing by two vectors.

#<INSERT>

def check():
    m = np.array([[0.1, 0.2, 0.3], [0.1, 0.1, 0.2]])
    X, Y = marginal(m)
    np.testing.assert_almost_equal(X, [0.6,0.4])
    np.testing.assert_almost_equal(Y, [0.2, 0.3, 0.5])
check()


from sympy import expand, symbols

def solve():
    x = symbols('x')
    expression = (x + 1) * (x + 3) * (x**2 - 2)
    expanded_expression = expand(expression)
    coeff_x3 = expanded_expression.as_coefficients_dict()[x**3]
    return coeff_x3

Translate the following content into English, requiring
1、Translate only the text, not the code or the contents of the table
2、Retain the original format
------

After expanding the expression (x+1)(x+3)(x^2-2), what is the coefficient of x^3. Write a Python code to solve this, define the function `solve()`, and return the result.


def abs_dist(p: dict) -> dict:
    abs_p = {}
    for x, prob in p.items():
        abs_x = abs(x)
        if abs_x in abs_p:
            abs_p[abs_x] += prob
        else:
            abs_p[abs_x] = prob
    return abs_p

Implement Python function `abs_dist(p: dict) -> dict` that takes a distribution `p` of random variable `X` as input and output the distribution of `|X|`.


from scipy.special import erf
from scipy.optimize import minimize_scalar
import numpy as np

def min_gelu():
    def gelu(x):
        return 0.5 * x * (1 + erf(x / np.sqrt(2)))
    ret = minimize_scalar(gelu)
    return ret.fun

Calculate the minimum value of the GeLU activation function. Implement it with python, define the function name as min_gelu, and return a floating point number representing the minimum value.


def average_matrix_columns(matrix):
    rows = len(matrix)
    cols = len(matrix[0])
    return [sum(matrix[i][j] for i in range(rows)) / rows for j in range(cols)]

Please write a Python program to calculate the average value of each column in a given matrix. The function should be named average_matrix_columns(matrix), where matrix is a two-dimensional list. The function should return a one-dimensional list containing the average value of each column.

#<INSERT>

def check_average_matrix_columns():
    assert average_matrix_columns([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [4.0, 5.0, 6.0]
    assert average_matrix_columns([[1, 2], [3, 4], [5, 6]]) == [3.0, 4.0]
    assert average_matrix_columns([[1]]) == [1.0]
    print("所有测试通过！")

check_average_matrix_columns()


import math

def newtons_method(f, df, x0, epsilon):
    x = x0
    fx = f(x)
    while abs(fx) > epsilon:
        x = x - fx / df(x)
        fx = f(x)
    return x

Implement Python function `newtons_method(f, df, x0, epsilon)` that outputs a solution of `f(x)=0` up to `epsilon` accuracy by Newton's method with initial guess `x0`.

#<INSERT>

def check():
    import numpy as np
    f = lambda x: (x - 2) * (x - 2)
    df = lambda x: 2 * (x - 2)
    np.testing.assert_almost_equal(newtons_method(f, df, 3, 1e-10), 2, decimal=5)
    f = lambda x: x ** 2 - 3 * x + 2
    df = lambda x: 2 * x - 3
    np.testing.assert_almost_equal(newtons_method(f, df, 5, 1e-10), 2, decimal=5)
    np.testing.assert_almost_equal(newtons_method(f, df, -2, 1e-10), 1, decimal=5)
check()


import math
def solve(x1, y1, x2, y2, x3, y3):
    return math.isclose((y2 - y1) * (x3 - x1), (y3 - y1) * (x2 - x1))

Given the coordinates of three points, determine whether they are collinear. Implement this feature using Python, define a function called solve, which takes six parameters x1, y1, x2, y2, x3, y3, and returns True or False, indicating whether these three points are collinear.


from sympy import *

def f():
    x = symbols('x')
    expr = sin(x*x)
    integral = integrate(expr, (x, -oo, oo))
    return float(integral.evalf())

Please use Python to calculate the definite integral of sin(x^2) from negative infinity to infinity. Write a function named f, which returns a value of type float.


A certain company produces the same product for two types of customers. The demand from customer A is x, with each unit selling at a price of 70-4x. Customer B has a demand of y, with each unit selling at a price of 150-15y. The production cost of the company for each product is 100+15(x+y). The question is, how much of x and y (the demands from companies A and B) allows the company to maximize its profit?

Define a Python function `solve_problem()` to solve this problem and return the maximum profit value.

#<INSERT>
assert abs(solve_problem() - 392.81) < 0.1


def get_matrix_trace(matrix):
    return sum(matrix[i][i] for i in range(len(matrix)))

Please write a Python program to calculate the trace of a given matrix. The function is named get_matrix_trace(matrix), where matrix is a two-dimensional list. The function should return a real number.

#<INSERT>

def check_trace():
    assert get_matrix_trace([[1, 2], [3, 4]]) == 5
    assert get_matrix_trace([[2, 0, 0], [0, 3, 0], [0, 0, 5]]) == 10
    assert get_matrix_trace([[1]]) == 1
    print("所有测试通过！")

check_trace()


import numpy as np

def solve(A):
    return np.linalg.eigvalsh(A)

Given a Hermite matrix, calculate its eigenvalues.

Define a function in Python called solve, which takes a Hermite matrix as input and returns a list of its eigenvalues. Use numpy to solve it.


from sympy import *

def f():
    x = symbols('x')
    return float(limit(sin(x)/x, x, 0))

Please use Python to calculate the limit of sin(x)/x as x approaches 0. Write a function with the name f, which should return a floating-point number.

#<INSERT>

assert(abs(f() - 1.0) < 1e-5)


import cmath

def solve(x, y):
    return abs(cmath.exp(x + y))

Define a function named 'solve' in Python, which takes two complex numbers x, y as input, and returns the modulus of exp(x + y).

#<INSERT>

import math
assert abs(solve(1+1j, 1-1j) - math.exp(2)) < 1e-5

assert abs(solve(1+2j, 3-4j) - 54.59815) < 1e-5


check_dict_case <- function(dict) {
    quit()
}

Please convert the following code to R with the function signature `check_dict_case <- function(dict)`.
Note:
1. Only implement the target function and import necessary packages; do not generate other code.

```python

def check_dict_case(dict):

    if len(dict.keys()) == 0:
        return False
    else:
        state = "start"
        for key in dict.keys():

            if isinstance(key, str) == False:
                state = "mixed"
                break
            if state == "start":
                if key.isupper():
                    state = "upper"
                elif key.islower():
                    state = "lower"
                else:
                    break
            elif (state == "upper" and not key.isupper()) or (state == "lower" and not key.islower()):
                    state = "mixed"
                    break
            else:
                break
        return state == "upper" or state == "lower"

```

#<INSERT>
test_humaneval <- function() {
    candidate <- check_dict_case
    stopifnot(isTRUE(all.equal(candidate(list('p' = 'pineapple', 'b' = 'banana')), TRUE)))
    stopifnot(isTRUE(all.equal(candidate(list('p' = 'pineapple', 'A' = 'banana', 'B' = 'banana')), FALSE)))
    stopifnot(isTRUE(all.equal(candidate(list('p' = 'pineapple', '5' = 'banana', 'a' = 'apple')), FALSE)))
    stopifnot(isTRUE(all.equal(candidate(list('Name' = 'John', 'Age' = '36', 'City' = 'Houston')), FALSE)))
    stopifnot(isTRUE(all.equal(candidate(list('STATE' = 'NC', 'ZIP' = '12345')), TRUE)))
    stopifnot(isTRUE(all.equal(candidate(list('fruit' = 'Orange', 'taste' = 'Sweet')), TRUE)))
    stopifnot(isTRUE(all.equal(candidate(list()), FALSE)))
}
test_humaneval()


Please convert the following code into R, with the function signature `encrypt <- function(s)`
Note:
1. Only implement the target function and import the necessary packages, do not generate any additional code

```python

def encrypt(s):

    d = 'abcdefghijklmnopqrstuvwxyz'
    out = ''
    for c in s:
        if c in d:
            out += d[(d.index(c)+2*2) % 26]
        else:
            out += c
    return out

```

#<INSERT>
test_humaneval <- function() {
    candidate <- encrypt
    stopifnot(isTRUE(all.equal(candidate('hi'), 'lm')))
    stopifnot(isTRUE(all.equal(candidate('asdfghjkl'), 'ewhjklnop')))
    stopifnot(isTRUE(all.equal(candidate('gf'), 'kj')))
    stopifnot(isTRUE(all.equal(candidate('et'), 'ix')))
    stopifnot(isTRUE(all.equal(candidate('faewfawefaewg'), 'jeiajeaijeiak')))
    stopifnot(isTRUE(all.equal(candidate('hellomyfriend'), 'lippsqcjvmirh')))
    stopifnot(isTRUE(all.equal(candidate('dxzdlmnilfuhmilufhlihufnmlimnufhlimnufhfucufh'), 'hbdhpqrmpjylqmpyjlpmlyjrqpmqryjlpmqryjljygyjl')))
    stopifnot(isTRUE(all.equal(candidate('a'), 'e')))
}
test_humaneval()


Please convert the following code to R with the function signature `add <- function(lst)`. Note:
1. Only implement the target function and import any necessary packages, do not generate other code.

#<INSERT>
test_humaneval <- function() {
    candidate <- add
    stopifnot(isTRUE(all.equal(candidate(c(4, 88)), 88)))
    stopifnot(isTRUE(all.equal(candidate(c(4, 5, 6, 7, 2, 122)), 122)))
    stopifnot(isTRUE(all.equal(candidate(c(4, 0, 6, 7)), 0)))
    stopifnot(isTRUE(all.equal(candidate(c(4, 4, 6, 8)), 12)))
}
test_humaneval()