[Kesci] 预测分析 · 客户购买预测(AUC评估要使用predict_proba)

文章目录

    • 1. Baseline
    • 2. AUC评估要使用predict_proba
      • 2.1 导入工具包
      • 2.2 特征提取
      • 2.3 训练+模型选择
      • 2.4 网格/随机搜索 参数+提交
      • 2.5 测试结果
    • 3. 致谢

新人赛地址

1. Baseline

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import LabelBinarizer
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import FeatureUnion
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import cross_val_scoretrain = pd.read_csv("./train_set.csv")
test = pd.read_csv("./test_set.csv")
train.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 25317 entries, 0 to 25316
Data columns (total 18 columns):#   Column     Non-Null Count  Dtype 
---  ------     --------------  ----- 0   ID         25317 non-null  int64 1   age        25317 non-null  int64 2   job        25317 non-null  object3   marital    25317 non-null  object4   education  25317 non-null  object5   default    25317 non-null  object6   balance    25317 non-null  int64 7   housing    25317 non-null  object8   loan       25317 non-null  object9   contact    25317 non-null  object10  day        25317 non-null  int64 11  month      25317 non-null  object12  duration   25317 non-null  int64 13  campaign   25317 non-null  int64 14  pdays      25317 non-null  int64 15  previous   25317 non-null  int64 16  poutcome   25317 non-null  object17  y          25317 non-null  int64 
dtypes: int64(9), object(9)
memory usage: 3.5+ MB
NO字段名称数据类型字段描述
1IDInt客户唯一标识
2ageInt客户年龄
3jobString客户的职业
4maritalString婚姻状况
5educationString受教育水平
6defaultString是否有违约记录
7balanceInt每年账户的平均余额
8housingString是否有住房贷款
9loanString是否有个人贷款
10contactString与客户联系的沟通方式
11dayInt最后一次联系的时间(几号)
12monthString最后一次联系的时间(月份)
13durationInt最后一次联系的交流时长
14campaignInt在本次活动中,与该客户交流过的次数
15pdaysInt距离上次活动最后一次联系该客户,过去了多久(999表示没有联系过)
16previousInt在本次活动之前,与该客户交流过的次数
17poutcomeString上一次活动的结果
18yInt预测客户是否会订购定期存款业务
  • 相关系数
abs(train.corr()['y']).sort_values(ascending=False)
y           1.000000
ID          0.556627
duration    0.394746
pdays       0.107565
previous    0.088337
campaign    0.075173
balance     0.057564
day         0.031886
age         0.029916
Name: y, dtype: float64
  • 绘制数字特征分布图
s = (train.dtypes == 'object')
object_col = list(s[s].index)
object_col
num_col = list(set(train.columns) - set(object_col))plt.figure(figsize=(25,22))
for (i,col) in enumerate(num_col):plt.subplot(3,3,i+1)sns.distplot(train[col]) # kde=False 可不显示密度线plt.xlabel(col,size=20)
plt.show()  

在这里插入图片描述

  • 分析下训练集 y 标签的比例
len(train[train['y']==1])/len(train['y'])
0.11695698542481336

只有 11% 的人会购买

  • 新人赛,数据没有缺失的,直接用模型试试效果
X_train = train.drop(['ID','y'], axis=1)
X_test = test.drop(['ID'], axis=1)
y_train = train['y']
def num_cat_splitor(X_train):s = (X_train.dtypes == 'object')object_cols = list(s[s].index)num_cols = list(set(X_train.columns) - set(object_cols))return num_cols, object_cols
num_cols, object_cols = num_cat_splitor(X_train)
# 查看文字变量的种类
for col in object_col:print(col, sorted(train[col].unique()))print(col, sorted(test[col].unique()))
class DataFrameSelector(BaseEstimator, TransformerMixin):def __init__(self, attribute_names):self.attribute_names = attribute_namesdef fit(self, X, y=None):return selfdef transform(self, X):return X[self.attribute_names].valuesnum_pipeline = Pipeline([('selector', DataFrameSelector(num_cols)),#('imputer', SimpleImputer(strategy="median")),('std_scaler', StandardScaler()),])
cat_pipeline = Pipeline([('selector', DataFrameSelector(object_cols)),('cat_encoder', OneHotEncoder(sparse=False,handle_unknown='ignore')),])
full_pipeline = FeatureUnion(transformer_list=[("num_pipeline", num_pipeline),("cat_pipeline", cat_pipeline),])
X_prepared = full_pipeline.fit_transform(X_train)
from sklearn.ensemble import RandomForestClassifierprepare_select_and_predict_pipeline = Pipeline([('preparation', full_pipeline),('forst_reg', RandomForestClassifier(random_state=0))
])
param_grid = [{'forst_reg__n_estimators' : [50,100, 150, 200,250,300,330,350],'forst_reg__max_features':[45,50, 55, 65]
}]grid_search_prep = GridSearchCV(prepare_select_and_predict_pipeline, param_grid, cv=7,scoring='roc_auc', verbose=2, n_jobs=-1)
grid_search_prep.fit(X_train,y_train)
grid_search_prep.best_params_
final_model = grid_search_prep.best_estimator_
y_pred_test = final_model.predict(X_test) 
# AUC 评估准则,需要使用 predict_proba,这里错误!!!
result = pd.DataFrame()
result['ID'] = test['ID']
result['pred'] = y_pred_test
result.to_csv('buy_product_pred.csv',index=False)

排名结果
在这里插入图片描述

auc 得分:0.72439844

2. AUC评估要使用predict_proba

AUC 指标,在预测时,应该使用概率来预测,上面做法是错误的(未使用概率预测)。

  • 机器学习之分类器性能指标之ROC曲线、AUC值 https://www.cnblogs.com/dlml/p/4403482.html
  • 如何理解机器学习和统计中的AUC? https://www.zhihu.com/question/39840928
  • sklearn.metrics.roc_auc_score 介绍

AUC 评估模型的优点,在模型正负样本比例失衡的情况下,依然可以很好的评估模型

以下重新对代码进行优化

2.1 导入工具包

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.facecolor']=(1,1,1,1) # pycharm 绘图白底,看得清坐标
from sklearn.model_selection import train_test_split
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import LabelBinarizer
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import FeatureUnion
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import cross_val_scoretrain = pd.read_csv("./train_set.csv")
test = pd.read_csv("./test_set.csv")

2.2 特征提取

  • 查看文字特征的值
for col in object_col:print(col, sorted(train[col].unique()))print(col, sorted(test[col].unique()))
job ['admin.', 'blue-collar', 'entrepreneur', 'housemaid', 'management', 'retired', 'self-employed', 'services', 'student', 'technician', 'unemployed', 'unknown']
job ['admin.', 'blue-collar', 'entrepreneur', 'housemaid', 'management', 'retired', 'self-employed', 'services', 'student', 'technician', 'unemployed', 'unknown']
marital ['divorced', 'married', 'single']
marital ['divorced', 'married', 'single']
education ['primary', 'secondary', 'tertiary', 'unknown']
education ['primary', 'secondary', 'tertiary', 'unknown']
default ['no', 'yes']
default ['no', 'yes']
housing ['no', 'yes']
housing ['no', 'yes']
loan ['no', 'yes']
loan ['no', 'yes']
contact ['cellular', 'telephone', 'unknown']
contact ['cellular', 'telephone', 'unknown']
month ['apr', 'aug', 'dec', 'feb', 'jan', 'jul', 'jun', 'mar', 'may', 'nov', 'oct', 'sep']
month ['apr', 'aug', 'dec', 'feb', 'jan', 'jul', 'jun', 'mar', 'may', 'nov', 'oct', 'sep']
poutcome ['failure', 'other', 'success', 'unknown']
poutcome ['failure', 'other', 'success', 'unknown']
  • 二值特征转化为 0, 1
# 对 'default','housing','loan' 3列二值(yes,no)特征转为 0,1
def binaryFeature(data):data['default_']=0data['default_'][data['default']=='yes'] = 1data['housing_']=0data['housing_'][data['housing']=='yes'] = 1data['loan_']=0data['loan_'][data['loan']=='yes'] = 1return data.drop(['default','housing','loan'], axis=1)X_train = binaryFeature(train)
X_test = binaryFeature(test)
  • 训练集数据切分,用于本地测试
X_train = X_train.drop(['ID'], axis=1)
X_test = X_test.drop(['ID'], axis=1)# 将训练集拆分一些出来做验证, 分层抽样
from sklearn.model_selection import StratifiedShuffleSplit
splt = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=1)
for train_idx, vaild_idx in splt.split(X_train, X_train['y']):train_part = X_train.loc[train_idx]valid_part = X_train.loc[vaild_idx]# 训练集拆成两部分 本地测试
train_part_y = train_part['y']
valid_part_y = valid_part['y']
train_part = train_part.drop(['y'], axis=1)
valid_part = valid_part.drop(['y'], axis=1)
  • 特征处理管道
def num_cat_splitor(X_train):s = (X_train.dtypes == 'object')object_cols = list(s[s].index)num_cols = list(set(X_train.columns) - set(object_cols))return num_cols, object_colsnum_cols, object_cols = num_cat_splitor(X_train)
num_cols.remove('y')class DataFrameSelector(BaseEstimator, TransformerMixin):def __init__(self, attribute_names):self.attribute_names = attribute_namesdef fit(self, X, y=None):return selfdef transform(self, X):return X[self.attribute_names].valuesnum_pipeline = Pipeline([('selector', DataFrameSelector(num_cols)),
#         ('imputer', SimpleImputer(strategy="median")),
#         ('std_scaler', StandardScaler()),])
cat_pipeline = Pipeline([('selector', DataFrameSelector(object_cols)),('cat_encoder', OneHotEncoder(sparse=False, handle_unknown='ignore')),])
full_pipeline = FeatureUnion(transformer_list=[("num_pipeline", num_pipeline),("cat_pipeline", cat_pipeline),])

2.3 训练+模型选择

# 本地测试,选模型
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.metrics import roc_auc_scorerf = RandomForestClassifier()
knn = KNeighborsClassifier()
lr = LogisticRegression()
svc = SVC(probability=True)
gbdt = GradientBoostingClassifier()models = [knn, lr, svc, rf, gbdt]
param_grid_list = [# knn[{'model__n_neighbors' : [5,15,35,50,100],'model__leaf_size' : [10,20,30,40,50]}],# lr[{'model__penalty' : ['l1', 'l2'],'model__C' : [0.2, 0.5, 1, 1.2, 1.5],'model__max_iter' : [10000]}],# svc[{'model__C' : [0.2, 0.5, 1, 1.2],'model__kernel' : ['rbf']}],# rf[{#     'preparation__num_pipeline__imputer__strategy': ['mean', 'median', 'most_frequent'],'model__n_estimators' : [200,250,300,330,350],'model__max_features' : [20,30,40,50],'model__max_depth' : [5,7]}],# gbdt[{'model__learning_rate' : [0.1, 0.5],'model__n_estimators' : [130, 200, 300],'model__max_features' : ['sqrt'],'model__max_depth' : [5,7],'model__min_samples_split' : [500,1000,1200],'model__min_samples_leaf' : [60, 100],'model__subsample' : [0.8, 1]}],
]for i, model in enumerate(models):pipe = Pipeline([('preparation', full_pipeline),('model', model)])grid_search = GridSearchCV(pipe, param_grid_list[i], cv=3,scoring='roc_auc', verbose=2, n_jobs=-1)grid_search.fit(train_part, train_part_y)print(grid_search.best_params_)final_model = grid_search.best_estimator_pred = final_model.predict_proba(valid_part)[:,1] # roc 必须使用概率预测print("auc score: ", roc_auc_score(valid_part_y, pred))
  • 注意 AUC 评分标准 要使用predict_proba方法 !!!
Fitting 3 folds for each of 25 candidates, totalling 75 fits
{'model__leaf_size': 20, 'model__n_neighbors': 50}
auc score:  0.8212256518034133
Fitting 3 folds for each of 10 candidates, totalling 30 fits
{'model__C': 1.2, 'model__max_iter': 10000, 'model__penalty': 'l2'}
auc score:  0.9011510812019533
Fitting 3 folds for each of 4 candidates, totalling 12 fits
{'model__C': 0.2, 'model__kernel': 'rbf'}
auc score:  0.7192431208601267
Fitting 3 folds for each of 40 candidates, totalling 120 fits
{'model__max_depth': 7, 'model__max_features': 20, 'model__n_estimators': 350}
auc score:  0.913398647137746
Fitting 3 folds for each of 144 candidates, totalling 432 fits
{'model__learning_rate': 0.1, 'model__max_depth': 7, 'model__max_features': 'sqrt', 'model__min_samples_leaf': 60, 'model__min_samples_split': 500, 'model__n_estimators': 300, 'model__subsample': 1}
auc score:  0.9299485084368806

可以看见 GBDT 梯度提升下降树模型表现最好

2.4 网格/随机搜索 参数+提交

微调参数列表,使用全部的训练数据训练,使用 RF 和 GBDT 模型 对测试集进行预测

  • 网格搜索
# 全量训练,网格搜索,提交
y_train = X_train['y']
X_train_ = X_train.drop(['y'], axis=1)select_model = [rf, gbdt]
param_grid_list = [# rf[{#     'preparation__num_pipeline__imputer__strategy': ['mean', 'median', 'most_frequent'],'model__n_estimators' : [250,300,350,400],'model__max_features' : [7,8,10,15,20],'model__max_depth' : [7,9,10,11]}],# gbdt[{'model__learning_rate' : [0.03, 0.05, 0.1],'model__n_estimators' : [200, 300, 350],'model__max_features' : ['sqrt'],'model__max_depth' : [7,9,11],'model__min_samples_split' : [300, 400, 500],'model__min_samples_leaf' : [50,60,70],'model__subsample' : [0.8, 1, 1.2]}],
]for i, model in enumerate(select_model):pipe = Pipeline([('preparation', full_pipeline),('model', model)])grid_search = GridSearchCV(pipe, param_grid_list[i], cv=3,scoring='roc_auc', verbose=2, n_jobs=-1)grid_search.fit(X_train_, y_train)print(grid_search.best_params_)final_model = grid_search.best_estimator_pred = final_model.predict_proba(X_test)[:,1] # roc 必须使用概率预测print(model,'\n finished!')result = pd.DataFrame()result['ID'] = test['ID']result['pred'] = predresult.to_csv('{}_pred.csv'.format(i), index=False)
Fitting 3 folds for each of 80 candidates, totalling 240 fits
{'model__max_depth': 11, 'model__max_features': 15, 'model__n_estimators': 400}
RandomForestClassifier() finished!
Fitting 3 folds for each of 729 candidates, totalling 2187 fits
{'model__learning_rate': 0.05, 'model__max_depth': 11, 'model__max_features': 'sqrt', 
'model__min_samples_leaf': 50, 'model__min_samples_split': 500, 
'model__n_estimators': 300, 'model__subsample': 1}
GradientBoostingClassifier() finished!
  • 随机搜索
# 随机搜索参数
y_train = X_train['y']
X_train_ = X_train.drop(['y'], axis=1)from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint
select_model = [rf, gbdt]
param_distribs = [# rf[{#     'preparation__num_pipeline__imputer__strategy': ['mean', 'median', 'most_frequent'],'model__n_estimators' : randint(low=250, high=500),'model__max_features' : randint(low=10, high=30),'model__max_depth' : randint(low=8, high=20)}],# gbdt[{'model__learning_rate' : np.linspace(0.01, 0.1, 10),'model__n_estimators' : randint(low=250, high=500),'model__max_features' : ['sqrt'],'model__max_depth' : randint(low=8, high=20),'model__min_samples_split' : randint(low=400, high=1000),'model__min_samples_leaf' : randint(low=40, high=80),'model__subsample' : np.linspace(0.5, 1.5, 10)}],
]for i, model in enumerate(select_model):pipe = Pipeline([('preparation', full_pipeline),('model', model)])rand_search = RandomizedSearchCV(pipe, param_distributions=param_distribs[i], cv=3,n_iter=20,scoring='roc_auc', verbose=2, n_jobs=-1)rand_search.fit(X_train_, y_train)print(rand_search.best_params_)final_model = rand_search.best_estimator_pred = final_model.predict_proba(X_test)[:,1] # roc 必须使用概率预测print(model,'\n finished!')result = pd.DataFrame()result['ID'] = test['ID']result['pred'] = predresult.to_csv('{}_pred.csv'.format(i), index=False)
Fitting 3 folds for each of 20 candidates, totalling 60 fits
{'model__max_depth': 18, 'model__max_features': 13, 'model__n_estimators': 481}
RandomForestClassifier() finished!
Fitting 3 folds for each of 20 candidates, totalling 60 fits
{'model__learning_rate': 0.05000000000000001, 'model__max_depth': 15, 'model__max_features': 'sqrt', 
'model__min_samples_leaf': 68, 'model__min_samples_split': 905, 
'model__n_estimators': 362, 'model__subsample': 0.9444444444444444}
GradientBoostingClassifier() finished!

2.5 测试结果

RF 模型得分:0.9229160811692528
RF提交结果
在这里插入图片描述
在这里插入图片描述

GBDT 模型得分:0.9332932318964199
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

第二期排名,暂列第8
在这里插入图片描述
在这里插入图片描述

3. 致谢

感谢徐师兄一直以来的指点和帮助!
欢迎大家一起分享练习心得,一起继续加油!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/474259.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python中装饰器的参数与返回值

def itcast1(fun): def inner(*args, **kwargs): print("itcast1 start") # args -> 元组数据() #kwargs -> 字典数据{} #result用来接收被装饰函数的返回值 result fun(*args, **kwargs) print("itcast1 end") return result return inner itcast1…

键盘接口和七段数码管的控制实验

一、实验目的 1. 学习4X4键盘的与CPU的接口原理 2. 掌握键盘芯片HD7279的使用&#xff0c;及8位数码管的显示方法&#xff1b; 二、实验内容 1. 通过4X4按键完成在数码管上的各种显示功能&#xff0c;以及LCD上显示。 三、实验设备 EL-ARM-830教学实验箱&#xff0c;P…

奇葩的UI引用LayoutInflater.from问题

今收到BUG一枚&#xff0c;一个页面的EditText的风格变为了系统默认&#xff08;系统经过定制&#xff0c;风格和普通的不同&#xff09; 经检查xml无任何不妥&#xff0c;最终问题出在LayoutInflater.from上。 如果LayoutInflater.from&#xff08;XXActivity.this&#xff09…

LeetCode 939. 最小面积矩形(哈希)

文章目录1. 题目2. 解题1. 题目 给定在 xy 平面上的一组点&#xff0c;确定由这些点组成的矩形的最小面积&#xff0c;其中矩形的边平行于 x 轴和 y 轴。 如果没有任何矩形&#xff0c;就返回 0。 示例 1&#xff1a; 输入&#xff1a;[[1,1],[1,3],[3,1],[3,3],[2,2]] 输出…

python中的wraps函数

使⽤装饰器时&#xff0c;有⼀些细节需要被注意。 例如&#xff0c;被装饰后的函数其实已经是另外⼀个函数了&#xff08;函数名等函数属性会发⽣改变&#xff09;。添加后由于函数名和函数的doc发⽣了改变&#xff0c;对测试结果有一定影响&#xff01; import functools de…

python中向类中动态添加新特性及删除属性方法

class Foo(object): pass obj Foo() # 添加对象属性(对象名追加对象属性&#xff09; obj.a 100 # print(obj.a) # 添加类属性&#xff08;类名称追加类属性&#xff09; Foo.b 200 # print(Foo.b) # print(obj.b) # 添加对象方法 def obj_fun(self): print(self.a) # …

图片效果集合(js、jquery或html5)

1.jQuery HTML5 幻灯片使用支持HTML5的浏览器会有特殊效果&#xff0c;即切换图片时颜色的改变文章&#xff1a;http://keleyi.com/a/bjac/b8i3xdui.htm效果&#xff1a;http://keleyi.com/keleyi/phtml/html5/1.htm 2. jQuery图片延迟加载一开始不加载实图&#xff0c;只用灰图…

LeetCode 1131. 绝对值表达式的最大值(数学 绝对值展开)

文章目录1. 题目2. 解题1. 题目 给你两个长度相等的整数数组&#xff0c;返回下面表达式的最大值&#xff1a; |arr1[i] - arr1[j]| |arr2[i] - arr2[j]| |i - j|其中下标 i&#xff0c;j 满足 0 < i, j < arr1.length。 示例 1&#xff1a; 输入&#xff1a;arr1 …

基于uCOSII的LCD驱动实验

实验目的 掌握在 UCOsH操作系统下编写应用程序 的基本方法 实验内容 在移植好的UCOsII项 目中添加串口、LCD、 键盘的驱动程序 学习在UCOSII下 ,多应用任务的简单编程实例 实验设备 EL-RAM-860教 学 实验 箱 ,PentiumII以上 的 PC机 ,仿 真 调试 电缆 ,串 口直 连 电 缆 。 PC操…

python中的__slots__

为了达到限制的⽬的&#xff0c;Python允许在定义class的时候&#xff0c;定义一个特殊的 __slots__变量&#xff0c;来限制该class实例能添加的属性&#xff1a; class Foo(object): __slots__ ("a", "b") # 限制动态使用对象名添加东西&#xff08;属性…

LeetCode 659. 分割数组为连续子序列(哈希)

文章目录1. 题目2. 解题1. 题目 给你一个按升序排序的整数数组 num&#xff08;可能包含重复数字&#xff09;&#xff0c;请你将它们分割成一个或多个子序列&#xff0c;其中每个子序列都由连续整数组成且长度至少为 3 。 如果可以完成上述分割&#xff0c;则返回 true &…

autotools入门笔记(二)——创建和使用静态库、动态库

带有静态库或者动态库的工程的构建过程与上一节&#xff08;&#xff09;只包含一个源文件的工程的构建过程是类似的。只是对于复杂的工程&#xff0c;如果包含多个还有源文件的目录时&#xff0c;需要对每个包含源文件的目录执行构建过程&#xff0c;另外创建和使用库文件时需…

等价类测试与决策表测试

问题&#xff1a;输入年月日year、month、day&#xff0c;其中年份的有效取值范围为[1818,2018]&#xff0c;请输出输入日期的前一天&#xff0c;例如输入2018年9月18日&#xff0c;输出为2018年9月17日。若输入日期非法&#xff0c;例如输入2013年2月30日&#xff0c;则输出“…

python中的私有化

1、xx: 公有变量2、_x: 单前置下划线,私有化属性或方法&#xff0c;from somemodule import * 禁止导入,类对象和子类可以访问。3、__xx&#xff1a;双前置下划线,避免与子类中的属性命名冲突&#xff0c;无法在外部直接访问(名字重整所以访问不到&#xff09;4、__xx__:双…

LeetCode 1520. 最多的不重叠子字符串(贪心)

文章目录1. 题目2. 解题1. 题目 给你一个只包含小写字母的字符串 s &#xff0c;你需要找到 s 中最多数目的非空子字符串&#xff0c;满足如下条件&#xff1a; 这些字符串之间互不重叠&#xff0c;也就是说对于任意两个子字符串 s[i…j] 和 s[k…l] &#xff0c;要么 j <…

一个网页设计师应该考虑的9件事

1、永远都不要停止学习新的东西 在一个领域的趋势很容易成为过去&#xff0c;一个网页设计师应该不断尝试跟上最新的方法。从标志设计到用户界面&#xff0c;你应该寻找各种样品&#xff0c;并看看什么是新的&#xff0c;什么不是。此外&#xff0c;即使自己是不是对你有用&…

边界值测试

问题描述——找零钱最佳组合&#xff1a; 假设商店货品价格(R)皆不大于100元&#xff08;且为整数&#xff09;&#xff0c;若顾客付款在100元内(P)&#xff0c;求找给顾客之最少货币个&#xff08;张&#xff09;数&#xff1f;&#xff08;货币面值50元(N50)&#xff0c;10元…

python中的@property(get与set作用

class Bank(object): def__init__(self): self.__money 100 property defmoney(self): returnself.__money #raise AttributeError("该属性不支持读取操作") # 如果只提供了读取操作&#xff0c;而不提供设置操作的&#xff0c;这样的属性叫做只读属性 money.sette…

LeetCode 679. 24 点游戏(回溯)

文章目录1. 题目2. 解题1. 题目 你有 4 张写有 1 到 9 数字的牌。你需要判断是否能通过 *&#xff0c;/&#xff0c;&#xff0c;-&#xff0c;(&#xff0c;) 的运算得到 24。 示例 1: 输入: [4, 1, 8, 7] 输出: True 解释: (8-4) * (7-1) 24示例 2: 输入: [1, 2, 1, 2] 输…

C++ Primer 有感(重载操作符)

1.用于内置类型的操作符&#xff0c;其含义不能改变。也不能为任何内置类型定义额外的新的操作符。&#xff08;重载操作符必须具有至少一个类类型或枚举类型的操作数。这条规则强制重载操作符不能重新定义用于内置类型对象的操作符的含义&#xff09;2.重载操作符&#xff0c;…