python从入门到实践课本课后题

变量

2.1 简单消息

具体代码

1
2
3

message="hello songyaxiang"
print(message)

执行结果


2.2 多条简单消息

具体代码

1
2
3
4
5

message="hello songyaxiang"
print(message)
message="hello python"
print(message)

执行结果


2.3 个性化消息

具体代码

1
2
3

message="Eric"
print(f"hello {message},would you like to learn some Python today?")

执行结果


2.4 调整名字的大小写

具体代码

1
2
3
4
5

message="song_ya_xiang"
print(message.title())
print(message.upper())
print(message.lower())

执行结果


2.5 名言

具体代码

1
2
3

message='Albert Einstein once said,"A person who never made a mistake never tried anything new"' #单双引号混用
print(message)

执行结果


2.6 名言2

具体代码

1
2
3
4
5

famous_person="Albert"
#单双引号混用
message=f"{famous_person} "'Einstein once said,"A person who never made a mistake never tried anything new"'
print(message)

执行结果


2.7 剔除人名中的空白

具体代码

1
2
3
4
5
6
7
8
9
10

message=" songyaxiang " #左边一个空格 右边四个空格
print(f"\t{message}") #\t是四个空格
print(f"{message}\n") #\n是换行
#删除左边空格
print(message.lstrip())
#删除右边空格
print(message.rstrip())
#删除两边空格
print(message.strip())

执行结果


2.8 数字四则运算

具体代码

1
2
3
4
5
6
7
8

message=2
print(message) #试着输出message看看是不是2
print(f"加法的结果是:{message+4}") #2+4=6
print(f"减法的结果是:{message-4}") #2-4=-2
print(f"乘法的结果是:{message*4}") #2*4=8
print(f"除法的结果是:{message/4}") #2/4=0.5
print(f"乘方的结果是:{message**4}") #2的4次方=16

执行结果


2.9 最喜欢的数

具体代码

1
2
3
4

message=7777777
print(message) #试着输出message看看是不是7777777
print(f"我最喜欢的数是:{message}")

执行结果


列表基本内容

3.1 姓名

具体代码

1
2
3
4
5
6
7

names=['SongYaXiang','Python','Java','C++']
print(names) #输出列表会带中括号!!!
print(names[0]) #下标从0-3
print(names[1])
print(names[2])
print(names[3])

执行结果


3.2 问候语

具体代码

1
2
3
4
5
6

names=['SongYaXiang','Python','Java','C++']
print(f"{names[0]} hello!")
print(f"{names[1]} hello!")
print(f"{names[2]} hello!")
print(f"{names[3]} hello!")

执行结果


3.3 自己的列表

具体代码

1
2
3
4
5

tongxun=['car','biycle','airplane','trip','van']
print(f"I like {tongxun[0]}")
print(f"I like {tongxun[1]}")
print(f"I like {tongxun[2]}")

执行结果


3.4-3.7 嘉宾名单

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

jiabin=['宋亚翔','python','java','c++','c语言']
print(jiabin)
#为每一位嘉宾打印消息
print(f"{jiabin[0]} 欢迎您来!!")
print(f"{jiabin[1]} 欢迎您来!!")
print(f"{jiabin[2]} 欢迎您来!!")
print(f"{jiabin[3]} 欢迎您来!!")
print(f"{jiabin[4]} 欢迎您来!!")
print("----------修改(直接赋值)----------")
jiabin[0]='黎明' #宋亚翔不能来了 我们邀请了黎明来
print(jiabin)
print("----------开头添加insert()方法----------")
jiabin.insert(0,'王明')
print(jiabin)
print("----------中间添加insert()方法----------")
jiabin.insert(2,'王五')
print(jiabin)
print("----------末尾添加append()方法----------")
jiabin.append('赵四')
print(jiabin)
print("----------末尾删除del语句----------")
del jiabin[7]
print(jiabin)
print("----------删除pop()方法----------")
jiabin.pop(5)
print(jiabin)
print("----------删除指定值remove()方法----------")
jiabin.remove('python')
print(jiabin)

执行结果


3.8 放眼世界(排序/翻转)

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

lvyou=['南京','上海','北京','哈尔滨','西藏']
print(f"输出一下:{lvyou}")

print("-----使用sorted函数正向排序-----")
print(f"使用sorted函数暂时排序:{sorted(lvyou)}")
print(f"重新输出一下:{lvyou}")

print("-----使用sorted函数反向排序-----")
print(f"使用sorted函数暂时排序:{sorted(lvyou,reverse=True)}")
print(f"重新输出一下:{lvyou}")

print("-----使用reverse()方法翻转-----")
lvyou.reverse()
print(f"翻转一下:{lvyou}")
lvyou.reverse()
print(f"再翻转一下:{lvyou}")

print("-----使用sort()方法正向排序-----")
lvyou.sort()
print(lvyou)

执行结果


3.9 嘉宾长度

具体代码

1
2
3

jiabin=['宋亚翔','python','java','c++','c语言']
print(len(jiabin))

执行结果


列表进阶内容

4.1 比萨

具体代码

1
2
3
4
5

foods=['tomato','bacon','cheese']
for food in foods:
print(f"I like {food}!")
print("I really love pizza!")

执行结果


4.2 动物

具体代码

1
2
3
4
5
6

animals=['monkey','mouse','elephant']
for animal in animals:
print(animal)
print(f"A {animal} would make a great pet")
print("Any of these animals would make a great pet!")

执行结果


4.3 for循环输出1-20

具体代码

1
2
3

for value in range(1,21):
print(value)

执行结果


4.4 一百万

具体代码

1
2
3
4

numbers=list(range(1,1000001));
for value in numbers:
print(value)

执行结果


4.5 一百万求和

具体代码

1
2
3
4
5

numbers=list(range(1,1000001));
print(max(numbers))
print(min(numbers))
print(sum(numbers))

执行结果


4.6 循环打印奇数

具体代码

1
2
3

for value in range(1,21,2):
print(value)

执行结果


4.7 循环打印3的倍数

具体代码

1
2
3

for value in range(3,31,3):
print(value)

执行结果


4.8 循环打印某些数的立方

具体代码

1
2
3

for value in range(1,11):
print(value**3)

执行结果


4.9 立方解析(列表解析)

具体代码

1
2
3

s=[value**2 for value in range(1,11)];
print(s)

执行结果


4.10 切片

具体代码

1
2
3
4
5
6
7

jiabins=['宋亚翔','python','java','c++','c语言']
for jiabin in jiabins[0:3]:
print(jiabin)
print("--------------------")
for jiabin in jiabins[-3:]:
print(jiabin)

执行结果


4.11 你的比萨,我的比萨

具体代码

1
2
3
4
5
6
7
8
9
10
11
12

foods=['tomato','bacon','cheese']
friend_pizzas=foods[:] #复制副本
#两个列表都添加新的比萨
foods.append('abs')
friend_pizzas.append('bbb')
#循环遍历输出
for food in foods:
print(food)
print("\n")
for friend in friend_pizzas:
print(friend)

执行结果


4.13 自助餐

具体代码

1
2
3
4
5
6
7
8
9

foods=('aaa','bbb','ccc','ddd','eee')
for food in foods:
print(food)
# foods[0]='fff' #元组不允许修改
print("\n")
foods=('aaaa','bbbb','ccc','ddd','eee') #只能所有的重新赋值
for food in foods:
print(food)

执行结果


if语句

5.3 外星人颜色

具体代码

1
2
3
4
5
6

alien_color='green'
if alien_color == 'green':
print("是绿色,恭喜您获得五分!")
if alien_color == 'yellow':
print("是黄色,恭喜您获得五分!")

执行结果


5.4 外星人颜色2

具体代码

1
2
3
4
5
6

alien_color='green'
if alien_color == 'green':
print("是绿色,恭喜您获得5分!")
else :
print("不是绿色,恭喜您获得10分!")

执行结果


5.5 外星人颜色3

具体代码

1
2
3
4
5
6
7
8

alien_color='yellow'
if alien_color == 'green':
print("是绿色,恭喜您获得5分!")
elif alien_color == 'red':
print("是红色,恭喜您获得10分!")
else :
print("是其他颜色,恭喜您获得15分!")

执行结果


5.6 人生的不同阶段

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14

age=120
if age<2:
print("此人是婴儿")
elif age>2 and age <4 :
print("此人是幼儿")
elif age>4 and age<13 :
print("此人是儿童")
elif age>13 and age<20 :
print("此人是青少年")
elif age>20 and age<65 :
print("此人是成年人")
else :
print("此人是老年人")

执行结果


5.7 喜欢的水果

具体代码

1
2
3
4
5
6
7
8
9
10
11
12

favorite_fruits=['apple','orange','bananas',]
if 'apple' in favorite_fruits :
print("apple在此列表内!")
if 'oranges' in favorite_fruits :
print("oranges在此列表内!")
if 'orange' in favorite_fruits :
print("orange在此列表内!")
if 'bananas' in favorite_fruits :
print("bananas在此列表内!")
if 'applebet' in favorite_fruits :
print("applebet在此列表内!")

执行结果


5.8 以特殊方式跟管理员打招呼

具体代码

1
2
3
4
5
6
7

users=['admin','bbb','ccc','ddd','eee_dasd']
for user in users:
if user == 'admin' :
print("Hello admin,would you like to see a status report?")
else :
print(f"Hello {user},thank you for logging in again.")

执行结果


5.9 处理没有用户的情形

具体代码

1
2
3
4
5
6
7

users=['admin','bbb','ccc','ddd','eee_dasd']
for user in users:
if user == 'admin' :
print("Hello admin,would you like to see a status report?")
else :
print(f"Hello {user},thank you for logging in again.")

执行结果


5.10 检查用户名

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

current_users=['admin','John','CCC','ddd','EeE_dasd']
new_users=['aaa','bbb','JOHN','ddd','eee']
#创建当前用户副本
current_users_xiaoxie=current_users[:]
#将当前用户小写形式存储
i=0;
for user in current_users_xiaoxie:
current_users_xiaoxie[i]=user.lower() #转为小写
i=i+1

#输出小写副本文件
print("已经存在的用户小写形式为:")
print(current_users_xiaoxie)

#遍历查看是否注册过
for user in new_users:
if user.lower() in current_users_xiaoxie :
print(f"{user}注册过,请重新输入")
else :
print(f"{user}可以使用")

执行结果


5.11 序数

具体代码

1
2
3
4
5
6
7
8
9
10
11

numbers=['1','2','3','4','5','6','7','8','9'];
for number in numbers:
if number == '1' :
print("1st")
elif number == '2' :
print("2nd")
elif number == '3' :
print("3rd")
else :
print(f"{number}th")

执行结果


字典

6.1 人

具体代码

1
2
3
4

peoples={'frist_name':'宋','last_name':'亚翔','age':'23','city':'西安'}
for jian,zhi in peoples.items():
print(f"{jian}: {zhi}")

执行结果


6.2 喜欢的数

具体代码

1
2
3
4

peoples={'宋亚翔':'7','荔湾':'34636','王五':'23','赵四':'5498'}
for jian,zhi in peoples.items():
print(f"{jian}: {zhi}")

执行结果


6.3 词汇表

具体代码

1
2
3
4

peoples={'JAVA':'大二学的','C':'大一学的','C#':'大二学的','C++':'还没学的','Python':'正在学的'}
for jian,zhi in peoples.items():
print(f"{jian}: {zhi}")

执行结果


6.4 词汇表2

具体代码

1
2
3
4
5
6
7

peoples={'JAVA':'大二学的','C':'大一学的','C#':'大二学的','C++':'还没学的','Python':'正在学的'}
print(peoples)
#新添加两对键值对
peoples['机器学习'] = '研一学的'
peoples['深度学习'] = '研二学的'
print(peoples)

执行结果


6.5 河流

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13

rivers={'the Yangtze River':'China','Yellow River':'China','Nile':'Egypt'}
#打印对应河流和国家
for key,value in rivers.items():
print(f"The {key} runs through {value}")
print("\n")
#打印所有河流名称
for key in rivers.keys():
print(key)
print("\n")
#打印所有国家名称
for value in rivers.values():
print(value)

执行结果


6.6 调查

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13

favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
people={'jen','ww','syx','zs'}
for key in people:
if(key in favorite_languages):
print(f"{key}恭喜你!")
else :
print(f"{key}抱歉!")

执行结果


6.7 人们

具体代码

1
2
3
4
5
6
7

peoples_one={'frist_name':'宋','last_name':'亚翔','age':'23','city':'西安'}
peoples_two={'frist_name':'李','last_name':'五','age':'12','city':'武汉'}
peoples_three={'frist_name':'赵','last_name':'四','age':'22','city':'长沙'}
peoples=[peoples_one,peoples_two,peoples_three]
for people in peoples:
print(people)

执行结果


6.8 宠物

具体代码

1
2
3
4
5
6
7
8

#列表里面存储字典
peoples_one={'frist_name':'欢欢','last_name':'宋亚翔'}
peoples_two={'frist_name':'乐乐','last_name':'李五',}
peoples_three={'frist_name':'憨憨','last_name':'赵四'}
pets=[peoples_one,peoples_two,peoples_three]
for pet in pets:
print(pet)

执行结果


6.9 喜欢的地方

具体代码

1
2
3
4
5
6

#字典里面存储列表
syx_place=['上海','北京','哈尔滨']
favorite_places={'宋亚翔':syx_place,'王五':'武汉','赵四':'上海',}
for name,place in favorite_places.items():
print(f"{name}: {place}")

执行结果


6.10 喜欢的数2

具体代码

1
2
3
4
5
6
7

#字典里面存储列表
syx_number=['12','77','7777']
lz_number=['408','555']
peoples={'宋亚翔':syx_number,'荔湾':lz_number,'王五':'23','赵四':'5498'}
for jian,zhi in peoples.items():
print(f"{jian}: {zhi}")

执行结果


6.11 城市

具体代码

1
2
3
4
5
6
7
8

#字典里面存储字典
xian={'country':'china','population':'250.6w','fact':'陕西省省会'}
shanghai={'country':'china','population':'555.3w','fact':'中国的一线城市'}
beijing={'country':'china','population':'105.8w','fact':'中国的首都'}
cities={'xian':xian,'shanghai':shanghai,'beijing':beijing}
for city,xx in cities.items():
print(city,xx)

执行结果


while循环

7.1 汽车租赁

具体代码

1
2
3

message=input("请问您需要租赁什么样的汽车?")
print(message)

执行结果


7.2 餐馆订位

具体代码

1
2
3
4
5
6

message=input("请问您有几位用餐: ")
if int(message) > 8 :
print("现在没有空桌")
else :
print("现在有空桌")

执行结果


7.3 10的整数倍

具体代码

1
2
3
4
5
6

message=input("请输入1个数判断是否为10的整数倍: ")
if int(message)%10 == 0:
print("是10的整数倍!")
else :
print("不是10的整数倍!")

执行结果


7.4 比萨配料

具体代码

1
2
3
4
5

message=''
while message != 'quit' :
message=input("请输入需要添加的比萨配料:");
print(message)

执行结果


7.5 电影票

具体代码

1
2
3
4
5
6
7
8
9
10

price=''
while price != 0 :
price=input("请输入观看者年龄:");
if int(price) <= 3 :
print("免费")
elif int(price)> 3 and int(price) < 12 :
print("10美元")
else :
print("15美元")

执行结果


7.8 熟食店

具体代码

1
2
3
4
5
6
7
8

sandwich_orders=['aaa','bbb','ccc']
finished_sandwiches=[]
for sandwich in sandwich_orders:
print("I made your tuna sandwich")
finished_sandwiches.append(sandwich)

print(finished_sandwiches)

执行结果


7.9 五香烟熏牛肉卖完了

具体代码

1
2
3
4
5
6
7
8
9
10
11

sandwich_orders=['aaa','pastrami','bbb','ccc','pastrami','pastrami','pastrami']
print("删除前的列表:")
print(sandwich_orders)
print("熏牛肉已经卖完了!")
#要删除的变量名
current='pastrami'
while current in sandwich_orders :
sandwich_orders.remove(current)
print("删除后的列表:")
print(sandwich_orders)

执行结果


7.10 梦想的度假胜地

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14

#获取最终调查结果
result={}
#结束的标志符
flag=True
while flag:
name=input("请问您的姓名:")
respnse=input("请问您最想去的城市:")
result[name]=respnse #将姓名和所想去的城市存入字典
repeat=input("还有人参加吗yes/no?")
#如果没人参加了就设置flag为false
if repeat == 'no':
flag=False
print(result)

执行结果


函数

8.1 消息

具体代码

1
2
3
4
5

def display_message():
print("这是第八章,我们学习函数")

display_message()

执行结果


8.2 喜欢的图书

具体代码

1
2
3
4
5

def favorite_book(title):
print(f"这是我最喜欢的书: {title}")

favorite_book('python入门')

执行结果


8.3 T恤

具体代码

1
2
3
4
5
6
7
8
9

def make_shirt(type='python'):
if type=='python':
print("I love Python")
else:
print(f"I love {type}")

make_shirt()
make_shirt('JAVA')

执行结果


8.4 大号T恤

具体代码

1
2
3
4
5
6
7
8
9

def make_shirt(type='python'):
if type=='python':
print("I love Python")
else:
print(f"I love {type}")

make_shirt()
make_shirt('JAVA')

执行结果


8.5 城市

具体代码

1
2
3
4
5
6
7

def describe_city(city,country='中国'):
print(f"{city} is in {country}")

describe_city('北京')
describe_city('克里米亚','乌克兰')
describe_city('洛杉矶','美国')

执行结果


8.6 城市名

具体代码

1
2
3
4
5
6
7

def city_country(city,country):
print(f"{city},{country}")

city_country('北京','中国')
city_country('洛杉矶','美国')
city_country('东京','日本')

执行结果


8.7 专辑

具体代码

1
2
3
4
5
6
7
8
9
10
11

def make_album(name=None,zname=None):
zj={'name':name,'zname':zname}
return zj

a=make_album()
b=make_album('syx','aa')
c=make_album('sss','aa')
print(a)
print(b)
print(c)

执行结果


8.8 用户的专辑

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14

def make_album(name=None,zname=None):
zj={'name':name,'zname':zname}
return zj

name=''
a =''
while name!= quit:
name=input("输入歌手名称: ")
sname=input("输入专辑名: ")
if name =='quit':
break;
a=make_album(name,sname)
print(a)

执行结果


8.9 消息

具体代码

1
2
3
4
5
6
7

def show_messages(messages):
for message in messages:
print(message)

messages=['我第一','我才是第一','我不卷了']
show_messages(messages)

执行结果


8.10 发送消息

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

def show_messages(messages,sent):
print("这是show_messages函数:")
for message in messages:
print(message)
sent.append(message)

def send_messages(a,b):
print("这是send_messages函数:")
print("这是messages列表:")
for aa in a:
print(aa)
print("这是sent_messages列表:")
for bb in b:
print(bb)

messages=['我第一','我才是第一','我不卷了']
sent_messages=[]
#调用两个函数
show_messages(messages,sent_messages)
send_messages(messages,sent_messages)

执行结果


8.11 消息归档

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

def show_messages(messages,sent):
print("这是show_messages函数:")
for message in messages:
print(message)
sent.append(message)

def send_messages(a,b):
print("这是send_messages函数:")
print("这是messages列表:")
for aa in a:
print(aa)
print("这是sent_messages列表:")
for bb in b:
print(bb)

messages=['我第一','我才是第一','我不卷了']
sent_messages=[]
#调用两个函数
show_messages(messages,sent_messages)
copy=messages[:]
send_messages(copy,sent_messages)

执行结果


8.12 三明治

具体代码

1
2
3
4
5
6
7

def add_foods(foods):
print(f"现在添加了{foods}食材")

add_foods('maxisao')
add_foods('mamaniya')
add_foods('hanbaobao')

执行结果


8.13 用户简介

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14

def build_profile(first,last,**user_info):
"""创建一个字典,其中包含我们知道的有关用户的一切"""
user_info['first_name']=first
user_info['last_name']=last
return user_info

user_profile=build_profile('宋','亚翔',
location='西安',
field='计算机',
sex='男'
)

print(user_profile)

执行结果


8.14 汽车

具体代码

1
2
3
4
5
6
7
8

def car(people,size,**xinxi):
xinxi['制造商']=people
xinxi['型号']=size
return xinxi

result=car('宋亚翔','1',city='西安',price='100065')
print(result)

执行结果


9.1 餐馆

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

class Restaurant:
def __init__(self,restaurant_name,cuisine_type):
self.restaurant_name=restaurant_name
self.cuisine_type=cuisine_type

def describe_restaurant(self):
print("餐馆正在营业1")
print("餐馆正在营业2")

def open_restaurant(self):
print("餐馆正在营业3")

my_food = Restaurant('宋亚翔真香饭店',10)
print(my_food.restaurant_name)
print(my_food.cuisine_type)
my_food.describe_restaurant()
my_food.open_restaurant()

执行结果


9.2 三家餐馆

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

class Restaurant:
def __init__(self,restaurant_name,cuisine_type):
self.restaurant_name=restaurant_name
self.cuisine_type=cuisine_type

def describe_restaurant(self):
print(f"{self.restaurant_name}正在营业")

def open_restaurant(self):
print("餐馆正在营业")

my_food1 = Restaurant('宋亚翔真香饭店',10)
my_food2 = Restaurant('王努力马洗扫饭店',22)
my_food3 = Restaurant('狗都不吃饭店',13)
my_food1.describe_restaurant()
my_food2.describe_restaurant()
my_food3.describe_restaurant()

执行结果


9.3 用户

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

class user:
def __init__(self,first_name,last_name,sex,age):
self.first_name=first_name
self.last_name=last_name
self.sex=sex
self.age=age

def describe_user(self):
print(f"{self.first_name}{self.last_name}----性别为{self.sex} 年龄为:{self.age}")

def greet_user(self):
print(f"{self.first_name}先生欢迎你!")

user_one=user('宋','亚翔','男','23')
user_one.describe_user()
user_one.greet_user()
user_two=user('李','四','女','29')
user_two.describe_user()
user_two.greet_user()

执行结果


9.4 就餐人数

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

class Restaurant:
def __init__(self,restaurant_name,cuisine_type):
self.restaurant_name=restaurant_name
self.cuisine_type=cuisine_type
self.number_served=10 #指定默认值

def describe_restaurant(self):
print(f"{self.restaurant_name}餐馆正在营业!")
print("餐馆正在营业2")

def open_restaurant(self):
print(f"{self.restaurant_name}餐馆开门了!")

def set_number_served(self,number):
self.number_served=number

def increment_number_served(self,number):
self.number_served+=number

my_food = Restaurant('宋亚翔真香饭店',10)
#打印多少人就餐
my_food.open_restaurant()
my_food.describe_restaurant()
print(f"开始人数是:{my_food.number_served}")
my_food.set_number_served(100)
print(f"修改一次人数是:{my_food.number_served}")
my_food.increment_number_served(25)
print(f"递增一次人数是:{my_food.number_served}")

执行结果


9.5 尝试登录次数

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

class user:
def __init__(self,first_name,last_name,sex,age,login_attempts):
self.first_name=first_name
self.last_name=last_name
self.sex=sex
self.age=age
self.login_attempts=login_attempts

def describe_user(self):
print(f"{self.first_name}{self.last_name}----性别为{self.sex} 年龄为:{self.age}")

def greet_user(self):
print(f"{self.first_name}先生欢迎你!")

def increment_login_attempts(self):
self.login_attempts+=1

def reset_login_attempts(self):
self.login_attempts=0

users=user('宋','亚翔','男','23',77)
users.increment_login_attempts()
print(users.login_attempts)
users.increment_login_attempts()
print(users.login_attempts)
users.increment_login_attempts()
print(users.login_attempts)
users.increment_login_attempts()
print(users.login_attempts)
users.reset_login_attempts()
print(users.login_attempts)

执行结果


9.6 冰淇淋小店

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

#父类
class Restaurant:
def __init__(self,restaurant_name,cuisine_type):
self.restaurant_name=restaurant_name
self.cuisine_type=cuisine_type
self.number_served=10 #指定默认值

def describe_restaurant(self):
print(f"{self.restaurant_name}餐馆正在营业!")
print("餐馆正在营业2")

def open_restaurant(self):
print(f"{self.restaurant_name}餐馆开门了!")

def set_number_served(self,number):
self.number_served=number

def increment_number_served(self,number):
self.number_served+=number

#子类
class IceCreamStand(Restaurant):
def __init__(self,restaurant_name,cuisine_type,flavors):
super().__init__(restaurant_name,cuisine_type) #一定是super()方法 并且没有self
self.flavors=flavors

def xianshi(self):
print(f"冰激凌有:{self.flavors}")

#列表表示冰淇淋的口味
flavor=['草莓','蓝莓','香蕉']
ice =IceCreamStand('宋亚翔','桶装',flavor)
ice.xianshi()

执行结果


9.7 管理员

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

class user:
def __init__(self,first_name,last_name,sex,age,login_attempts):
self.first_name=first_name
self.last_name=last_name
self.sex=sex
self.age=age
self.login_attempts=login_attempts

def describe_user(self):
print(f"{self.first_name}{self.last_name}----性别为{self.sex} 年龄为:{self.age}")

def greet_user(self):
print(f"{self.first_name}先生欢迎你!")

def increment_login_attempts(self):
self.login_attempts+=1

def reset_login_attempts(self):
self.login_attempts=0

class Admin(user):
def __init__(self,first_name,last_name,sex,age,login_attempts,privileges):
super().__init__(first_name,last_name,sex,age,login_attempts)
self.privileges=privileges

def show_privileges(self):
print(f"管理员权限有:{self.privileges}")

privilege=["update","delete","add"]
admin = Admin('宋','亚翔','男','23',22,privilege)
admin.show_privileges()

执行结果


9.8 权限

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

class user:
def __init__(self,first_name,last_name,sex,age,login_attempts):
self.first_name=first_name
self.last_name=last_name
self.sex=sex
self.age=age
self.login_attempts=login_attempts

def describe_user(self):
print(f"{self.first_name}{self.last_name}----性别为{self.sex} 年龄为:{self.age}")

def greet_user(self):
print(f"{self.first_name}先生欢迎你!")

def increment_login_attempts(self):
self.login_attempts+=1

def reset_login_attempts(self):
self.login_attempts=0

class Admin(user):
def __init__(self,first_name,last_name,sex,age,login_attempts,privileges):
super().__init__(first_name,last_name,sex,age,login_attempts)
self.privileges=Privileges(pris) #这里通过privileges实例 ----> 属性

class Privileges:
def __init__(self,privileges):
self.privleges=privileges

def show_privileges(self):
print(f"管理员权限有:{self.privleges}")

pris=['update','delete','add']
ppp=Privileges(pris)
admin=Admin('宋','亚翔','男','23',44,ppp)
#相当于Privileges(pris)实例 然后调用展示
admin.privileges.show_privileges()

执行结果


9.13 骰子

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

from random import randint
class Die:
def __init__(self,sides=6):
self.sides=sides

def roll_die(self):
print(randint(1,self.sides))

die=Die(6)
die.roll_die()
die=Die(6)
die.roll_die()
die=Die(6)
die.roll_die()
die=Die(6)
die.roll_die()
die=Die(6)
die.roll_die()
die=Die(6)
die.roll_die()

执行结果


9.14 彩票

具体代码

1
2
3
4
5

from random import sample
lottery=['1','2','3','4','5','6','7','8','9','10','a','b','c','d','e']
result=sample(lottery,4)
print(result)

执行结果


9.15 彩票分析

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13

from random import sample
lottery=['1','2','3','4','5','6','7','8','9','10','a','b','c','d','e']
result=sample(lottery,4)
print(f"中大奖的序列是:{result}")
current=[]
sum=0
while result!=current:
current=sample(lottery,4)
print(f"当前随机的序列是:{current}")
sum+=1

print(f"一共要{sum}多次才可以中大奖!")

执行结果


文件和异常

10.1 python学习笔记

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

#.txt文件和.py文件在一个目录里面!!!

#1.全文读取
with open('learning_python.txt',encoding='utf-8') as files:
contents=files.read()
print(contents)

#2.逐行读取
with open('learning_python.txt',encoding='utf-8') as files:
for file in files:
print(file.strip()) #去除print打印多余空行

#3.使用列表读取
with open('learning_python.txt',encoding='utf-8') as files:
lines=files.readlines()
#with语句外
for line in lines:
print(line.strip()) #去除print打印多余空行

执行结果


10.2 C语言学习笔记

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14

#1.一行一行修改
with open('learning_python.txt',encoding='utf-8') as files:
lines=files.readlines()

for line in lines:
line=line.replace('Python','JAVA')
print(line.strip()) #删除print打印多余空格

#2.整段文直接修改
with open('learning_python.txt',encoding='utf-8') as files:
lines=files.read()
lines=lines.replace('Python','JAVA')
print(lines)

执行结果


10.3 访客

具体代码

1
2
3
4
5
6

#1.open()里面写是w 写入模式
#2.使用write()写入文件
with open('learning_python.txt','w',encoding='utf-8') as files:
writes=input("请输入用户名:")
files.write(writes)

执行结果


10.4 访客名单

具体代码

1
2
3
4
5
6
7

with open('learning_python.txt','w',encoding='utf-8') as files:
writes=''
while writes != 'quit':
writes=input("请输入用户名:") #输入用户名
print(f"{writes}欢迎您!") #打印问候语
files.write(f"{writes}\n") #自己在f字符串里面加\n换行

执行结果


10.5 调查

具体代码

1
2
3
4
5
6
7

with open('learning_python.txt','w',encoding='utf-8') as files:
writes=''
while writes != 'quit':
print("为什么您喜欢编程?")
writes=input("请输入原因:") #输入用户名
files.write(f"{writes}\n") #自己在f字符串里面加\n换行

执行结果


机器学习

机器学习计划

学习思路

1
2
3
4
5
6
1.用书
西瓜书(机器学习)
python机器学习(蜥蜴书)
2.视频
b站浙大教授带你全面解读机器学习西瓜书!
黑马程序员3天机器学习入门

参考视频pdf文件

参考笔记


机器学习简介

相关关系

应用领域

1
2
3
4

1.传统预测:店铺销量预测/量化投资/广告推荐/企业客户分类/sql语句安全监测分类
2.图像识别:人脸识别/街道交通标志检测
3.自然语言处理:文本分类/情感分析/自动聊天

相关概念

数据集(特征值+目标值)

常见三类问题

1
2
3
1.**分类问题**:给一堆小猫小狗 --> 分类是小狗还是小猫
2.**回归问题**:给一堆房价和地理位置等信息 --> 得到连续的房价数据
3.**聚类问题**:给一堆属性信息 --> 合成在一起

算法分类

1
2
3
4
5
1.监督学习(**预测**):输入数据有特征有标签(有标准答案)---分类和回归
1.1 分类: k-近邻算法/贝叶斯分类/决策树与随机森林/逻辑回归/神经网络
1.2 回归: 线性回归/岭回归
2.无监督学习:输入数据有特征无标签(无标准答案)---聚类
2.1 聚类: k-means

开发流程


特征工程

数据集

可用数据集

1
2
3
4
5
6
7
8
9
10
11
12
1. Kaggle:https://www.kaggle.com/datasets
1.1 数据量巨大
1.2 真实数据
1.3 80万科学家
1.4 大数据竞赛平台
2. UCI:http://archive.ics.uci.edu/ml/
2.1 数据量几十万
2.2 涵盖科学/生活/经济等领域
2.3 收录360个数据集
3. scikit-learn:https://scikit-learn.org/stable/
3.1 数据量较小
3.2 方便学习

sklearn数据集

sklearn数据集内容

1
2
3
1.分类/聚类/回归
2.特征工程
3.模型选择/调优

sklearn获取流行数据集(datasets)

1
2
3
4
5
1.sklearn.datasets  --- 加载获取流行数据集
1.1 datasets.load_*() ---获取小规模数据集
数据包含在datasets里
1.2 datasets.fetch_*(data_home=None) ---获取大规模数据集
需要从网络上下载,函数的第一个参数是data_home,表示数据集下载的目录,默认是 ~/scikit_learn_data/

sklearn小数据集(load)

1
2
3
4
5
6
7
from sklearn import datasets
iris=datasets.load_iris()
print(iris)
----------------------------------
from sklearn import datasets
boston=datasets.load_boston()
print(boston)

sklearn大数据集(fetch)

1
2
3
from sklearn import datasets
newgroup=datasets.fetch_20newsgroups()
print(newgroup)

sklearn返回值(字典格式)

以鸢尾花为例(iris)

1
2
3
4
5
6
7
#load和fetch均返回数据类型是datasets.base.Bunch(字典格式)

1.data:特征数据数组(特征值)
2.target:标签数组(目标值)
3.DESCR:数据描述
4.feature_names:特征名
5.target_names:目标名

数据集划分

1
2
3
4
5
6
数据集划分:
1.训练数据: 用于训练/构建模型
2.测试数据: 用于评估模型是否有效
数据集划分比例:
训练集: 70% 80% 75%
测试集: 30% 20% 30%

数据集划分API(model_selection)

1
2
3
4
5
sklearn.model_selection.train_test_split(arrays,*option)
1.x: 特征值
2.y: 目标值
3.test_size: 测试集大小(一般是float/默认是0.25)
4.random_state: 随机数种子(相同种子采样结果相同)

使用鸢尾花数据集:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from sklearn import datasets
from sklearn.model_selection import train_test_split

iris=datasets.load_iris()

#训练集特征值x_train
#测试集特征值x_test
#训练集目标值y_train
#测试集目标值y_test
x_train,x_test,y_train,y_test=train_test_split(iris.data,iris.target,random_state=22) #随机数种子是22 测试集大小默认是0.25
print(f"训练集特征值x_train: {x_train}")
print(f"测试集特征值x_test: {x_test}")
print(f"训练集目标值y_train: {y_train}")
print(f"测试集目标值y_test: {y_test}")


特征工程介绍

特征提取(sklearn.feature_extraction)

  • 任意数据(文本/图像) –> 数字特征(机器学习)

特征提取分类

1
2
3
1.字典特征提取(特征离散化) 
2.文本特征提取
3.图像特征提取(深度学习)

字典特征提取(DictVectorizer类)

1
2
3
4
#有三个方法:
1.fit_transform(X): 输入一个字典返回稀疏矩阵
2.inverse_transform(X): 输入一个稀疏数组/数组返回原始数据格式
3.get_feature_names(): 返回类别名称

以城市为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
from sklearn.feature_extraction import DictVectorizer
#对字典类型数据进行特征抽取
data = [{'city': '北京','temperature':100}, {'city': '上海','temperature':60}, {'city': '深圳','temperature':30}]
#1.实例化一个转换器类
transfer=DictVectorizer(sparse=False) #sparse默认是True打开的是稀疏矩阵
#2.调用fit_transform()方法抽取特征
data_new=transfer.fit_transform(data)
#获得特征名称
print(transfer.get_feature_names())
#获得特征
print(data_new) #sparse默认是True打开的是稀疏矩阵
#反转最初的数据格式
print(f"原来的数据格式是:{transfer.inverse_transform(data_new)}")

文本特征提取(CountVectorizer类统计特征词出现个数)

1
2
3
4
#有三个方法:
1.fit_transform(X): 输入一个文本/文本字符串返回稀疏矩阵
2.inverse_transform(X): 输入一个稀疏数组/数组返回原始数据格式
3.get_feature_names(): 返回类别名称

以英文段落为例:

1
2
3
4
5
6
7
8
9
10
11
from sklearn.feature_extraction.text import CountVectorizer
#准备数据
data =["life is short,i like like python", "life is too long,i dislike python"]
#1.实例化一个转换器
count=CountVectorizer()
#2.调用fit_transfrom()方法获取数据
data_new=count.fit_transform(data)
print(count.get_feature_names_out()) #get_feature_names已经过期了!!!
#二维数组要用toarray()方法展示出来 没有sparse=False这个设置!!!
print(data_new.toarray())
print(count.inverse_transform(data_new))

文本特征提取(TfidfVectorier类+jieba库的cut方法分词)

jieba库的cut方法

以中文段落为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from sklearn.feature_extraction.text import CountVectorizer
import jieba
#准备数据
data=["一种还是一种今天很残酷,明天更残酷,后天很美好,但绝对大部分是死在明天晚上,所以 每个人不要放弃今天。",
"我们看到的从很远星系来的光是在几百万年之前发出的,这样当我们看到宇宙时,我们是在 看它的过去。",
"如果只用一种方式了解某样事物,你就不会真正了解它。了解事物真正含义的秘密取决于如 何将其与我们所了解的事物相联系。"]

#1.将中文文本分词
data_new=[]
for sent in data:
data_new.append(" ".join(list(jieba.cut(sent)))) #使用jieba库的cut分词方法!!!
#2.调用fit_transform()方法
transfer=CountVectorizer(stop_words=["一种","哈哈"]) #禁用词--- 分词的时候不把他们当做特征词!!!
data_final=transfer.fit_transform(data_new)
print(f"特征名称:\n {transfer.get_feature_names_out()}")
print(f"data_new内容:\n{data_final.toarray()}")


TfidfVectorier类

1
2
3
4
5
6
1.TF-IDF思想:某个词/短语在一篇文章中出现概率高,并且在其他文章中很少出现,则认为有很好的区分度,适合用来分类
2.TF-IDF作用:用于评估对于一个文件/语料库文件的重要程度
3.TF-IDF公式:
TF(词频): 词语在文件中出现频率
IDF(逆向文档频率): log[总文件数目/文件数目]10
tfidf=TF*IDF

以中文段落为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from sklearn.feature_extraction.text import TfidfVectorizer
import jieba
#准备数据
data=["一种还是一种今天很残酷,明天更残酷,后天很美好,但绝对大部分是死在明天晚上,所以 每个人不要放弃今天。",
"我们看到的从很远星系来的光是在几百万年之前发出的,这样当我们看到宇宙时,我们是在 看它的过去。",
"如果只用一种方式了解某样事物,你就不会真正了解它。了解事物真正含义的秘密取决于如 何将其与我们所了解的事物相联系。"]
#1.将中文文本分词
data_new=[]
for sent in data:
data_new.append(" ".join(list(jieba.cut(sent))))
#2.调用fit_transform()方法
transfer=TfidfVectorizer() #禁用词--- 分词的时候不把他们当做特征词!!!
data_final=transfer.fit_transform(data_new)
print(f"特征名称:\n {transfer.get_feature_names_out()}")
print(f"data_new内容:\n{data_final.toarray()}")


特征预处理(sklearn.preprocessing)

1
2
3
4
特征预处理:特征数据 --(转换函数)--> 特征数据[更加适合算法模型]	
特征预处理:
1.归一化(传统精确小数据场景): MinMaxScaler ----最大值最小值是变化并且容易受到异常点影响 ---> 鲁棒性较差
2.标准化(嘈杂大数据场景): StandardScaler ----

归一化(MinMaxScaler)

归一化推导公式:

1
2
3
4
5
6
7
8
9
10
11
import pandas as pd
from sklearn.preprocessing import MinMaxScaler #标准化
#1.获取数据
data=pd.read_csv("dating.txt") #文档在.py文件所在目录
data=data.iloc[:,:3]
print(data)
#2.实例化一个转换器类
transfer=MinMaxScaler(feature_range=[0,1]) #默认归一化在0-1
#3.调用fit_transform()
data_new=transfer.fit_transform(data)
print(data_new)

标准化(StandardScaler)

标准化推导公式:

1
2
3
4
5
6
7
8
9
10
11
12
import pandas as pd
from sklearn.preprocessing import StandardScaler #统一化
#1.获取数据
data=pd.read_csv("dating.txt") #文档在.py文件所在目录
print(data)
#2.实例化一个转换器类
transfer=StandardScaler()
#3.调用fit_transform()
data_new=transfer.fit_transform(data[['milage','Liters','Consumtime']])
print("标准化的结果:\n", data_new)
print("每一列特征的平均值:\n", transfer.mean_)
print("每一列特征的方差:\n", transfer.var_)


特征降维

1
2
3
4
5
6
7
8
9
10
11
12
13
14
概念:
在某些限定条件下,降低随机变量(特征)个数 ---> 一组“不相关”主变量

分类:
1.特征选择
1.1 嵌入式 Embeded
决策树
正则化
深度学习
1.2 过滤式 Filter
方差选择法:低方差特征过滤
相关系数:特征与特征之间的相关过程
1.3 包裹式
2.主成分分析

特征选择

低方差特征过滤(varianceThreshold)

1
2
3
4
5
6
1.删除低方差的一些特征,再结合方差的大小来考虑这个方式的角度
2. API:
sklearn.feature_selection.VarianceThreshold(threshold = 0.0) --删除所有低方差特征
Variance.fit_transform(X):
X是numpy array格式的数据[行,列]
返回值:删除训练集差异低于threshold的特征(默认是删除所有样本中具有相同值的特征)

筛选某些股票的指标特征

1
2
3
4
5
6
7
8
9
10
import pandas as pd
from sklearn.feature_selection import VarianceThreshold
#1.获取数据
data=pd.read_csv("factor_returns.csv")
data=data.iloc[:,1:-2]
#2.实例化转换器类
transfer=VarianceThreshold(threshold=10) //特征方差选10
#3.调用fit_transform
data_new=transfer.fit_transform(data)
print(data_new)

相关系数过滤(scipy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1.皮尔逊相关系数:反映变量之间相关关系密切程度的统计指标
相关系数(r):-1到1之间
1.1 r>0表示正相关
1.2 r<0表示负相关
1.3 |r|=1表示两变量之间完全相关
1.4 r=0表示两变量之间无相关
1.5 0<|r|<1表示两变量存在一定程度相关,且越接近1之间的线性关系越密切,接近0之间表示线性相关越弱
1.6 |r|<0.4低度相关,0.4≤|r|<0.7显著性相关,0.7≤|r|<1高度线性相关

2. from scipy.stats import pearsonr
X: 特征值x,
Y: 特征值y,返回值是[特征值相关,特征值]

3.特征之间相关性很高:
3.1 选其中一个
3.2 加权求和 每个占比多少
3.3 主成分分析

主成分分析(PCA降维保留信息)

1
2
3
4
5
6
7
1.API:通过矩阵运算得到一个合适的直线->主成分分析的结果
sklearn.decomposition.PCA(n_components=None)
n_components:
小数:表示保留百分之多少的信息
整数:减少到多少特征
PCA.fit_transform(X是numpy array格式数据)
返回值:转换后指定维度的array

举例使用

1
2
3
4
5
6
7
8
9
from sklearn.decomposition import PCA
#1.获取数据
data=[[2,8,4,5],
[6,3,0,8],
[5,4,9,1]]
#2.实例化转换器类
transfer=PCA(n_components=2) #转换后有2个维度(2个特征)
data_new=transfer.fit_transform(data)
print(data_new)

instacart降维案例

问题分析

1
2
3
4
5
6
7
8
<探究用户对物品类别的喜好细分>
2.order_products_prior.csv订单与商品信息: order_id,product_id,add_to_cart_order,reordered
products.csv商品信息: product_id,product_name,aisle_id,department_id
orders.csv用户的订单信息: order_id,user_id,eval_set,order_number.....
aisles.csv商品所属物品类别: aisle_id,aisle
2. 得到四个csv文件 ----> 需要将user_id和aisle放在同一个表中
3. 找到user_id和aisle ----> 交叉表和透视表
4. 特征冗余过多 ---->PCA降维

具体实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import pandas as pd
from sklearn.decomposition import PCA
#1.获取数据(记得放在代码当前位置文件夹下)
data1=pd.read_csv("order_products__prior.csv")
data2=pd.read_csv("products.csv")
data3=pd.read_csv("orders.csv")
data4=pd.read_csv("aisles.csv")

#2.合并表 merge()函数
table1=pd.merge(data4,data2,on=["aisle_id","aisle_id"])
table2=pd.merge(table1,data1,on=["product_id","product_id"])
table3=pd.merge(table2,data3,on=["order_id","order_id"])

#3.交叉表 crosstab()函数
table=pd.crosstab(table3["user_id"],table3["aisle"])

#4.PCA降维 PCA()函数
transfer=PCA(n_components=0.95) #保留百分之95的数据
data_new=transfer.fit_transform(table) #降维
print(data_new) #输出PCA降维后的数据


sklearn转换器和估计器

1
2
3
4
5
6
7
8
9
 1.特征工程的步骤:
1.1 实例化(实例化的是一个转换器类(Transformer))
1.2 调用fit_transform(对于文档简历分类词频矩阵,不能同时调用)

2.转换器:特征工程的接口
2.1 转换器的形式:
2.1.1 fit_transform
2.1.2 fit
2.1.3 transform

转换器(fit_transform)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler #引入特征预处理中的标准化

#特征预处理
##1.归一化(MinMaxScaler)
##2.标准化(StandardScaler)

std1=StandardScaler()
a=[[1,2,3],[4,5,6]]
print(std1.fit_transform(a))

std2=StandardScaler()
print(std2.fit(a))
print(std2.transform(a))

估计器(estimator)

1
2
3
4
5
6
7
8
9
 1.估计器的步骤:
1.1 实例化一个estimator
1.2 调用estimator.fit(x_train,y_train)计算 --> 调用完毕,模型生成
1.3 模型评估:
1.3.1 直接对比真实值和预测值:
y_predict=estimator.predict(x_test)
y_test==y_predict
1.3.2 计算准确率:
accuracy=estimator.score(x_test,y_test)

估计器的分类:

K-近邻算法(sklearn.neighbors.KNeighborsClassifier)

1
2
3
4
5
1.核心思想: 你的"邻居"来推断你的类别
2.距离公式: 欧式距离 / 明可夫斯基距离
3.API: sklearn.neighbors.KNeighborsClassifier(n_neighbors=5,algorithm='auto')
3.1 n_neighbors: (默认整数类型为5) -->通过k_neighbors查询默认使用的邻居数
3.2 algorithm: 可选用于计算最近邻居的算法[auto/ball_tree/kd_tree/brute]

模型选择与调优(sklearn.model_selection.GridSearchCV)

1
2
3
4
5
6
7
8
9
10
11
12
1.交叉验证(cross validation):为了让被评估的模型更加准确可信
1.1将拿到的训练数据更加细化:
训练集:训练集+验证集
测试集:测试集
2.超参数搜索-网格搜索(Grid Search):
2.1 超参数:有很多参数是需要手动指定的(如k-近邻算法中的K值)
2.2 API: sklearn.model_selection.GridSearchCV(estimator,param_grid=None,cv=None)
2.2.1 estimator:估计器对象
2.2.2 param_grid:估计器参数(dict) --> 一般是取字典{"n_neighbors":[1,3,5]}
2.2.3 cv:指定几折交叉验证(训练集中训练集和验证集的划分有几次,然后得出平均值)
2.2.4 fit():输入训练数据
2.2.5 score():准确率

电影类型分析

鸢尾花分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler #引入特征预处理中的标准化
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
#用KNN算法对鸢尾花进行分类
#1.获取数据
iris=load_iris()

#2.划分数据集
x_train,x_test,y_train,y_test=train_test_split(iris.data,iris.target,random_state=6)

#3.特征工程(标准化)
transfer=StandardScaler()
x_train=transfer.fit_transform(x_train)
x_test=transfer.transform(x_test)

#4.KNN算法预估器
estimator=KNeighborsClassifier(n_neighbors=3)
estimator.fit(x_train,y_train)

#5.模型评估
##方法一:直接对比真实值和预测值
y_predict=estimator.predict(x_test)
print(y_test==y_predict)
##方法二:计算准确率
score=estimator.score(x_test,y_test)
print("准确率为:",score)

鸢尾花分析(添加网格搜索和交叉验证)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler #引入特征预处理中的标准化
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV
#用KNN算法对鸢尾花进行分类
#1.获取数据
iris=load_iris()

#2.划分数据集
x_train,x_test,y_train,y_test=train_test_split(iris.data,iris.target,random_state=6)

#3.特征工程(标准化)
transfer=StandardScaler()
x_train=transfer.fit_transform(x_train)
x_test=transfer.transform(x_test)

#4.KNN算法预估器
estimator=KNeighborsClassifier()

##加入网格搜索和交叉验证
param_dict={"n_neighbors":[1,3,5,7,9,11]}
estimator=GridSearchCV(estimator,param_grid=param_dict,cv=10)

estimator.fit(x_train,y_train)

#5.模型评估
##方法一:直接对比真实值和预测值
y_predict=estimator.predict(x_test)
print(y_test==y_predict)
##方法二:计算准确率
score=estimator.score(x_test,y_test)
print("准确率为:",score)

#6.获取结果分析
print("最佳参数:",estimator.best_params_)
print("最佳结果:",estimator.best_score_)
print("最佳估计器:",estimator.best_estimator_)
print("交叉验证的结果:",estimator.cv_results_)

预测facebook签到位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler #引入特征预处理中的标准化
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV
#Facebook预测签到位置

##1.获取数据
data=pd.read_csv("train.csv")

##2.数据处理(获取特征值和目标值)
###2.1 缩小数据范围 2<x<2.5 1.0<y<1.5
###2.2 改变time时间 年月日时分秒
###2.3 过滤签到次数少的地点
data=data.query("x<2.5&x>2&y>1.0&y<1.5")
time_value=pd.to_datetime(data["time"],unit="s")
data=pd.DatetimeIndex(time_value)

place_count=data.groupby("place_id")
data_final=data[data["place_id"].isin(place_count[place_count>3].index.values)]
##3.特征工程
x=data_final[["x","y","accuracy","day","weekday","hour"]]
y=data_final["place_id"]
x_train,x_test,y_train,y_test=train_test_split(x,y)

##4.KNN算法预估器
estimator=KNeighborsClassifier()

###加入网格搜索和交叉验证
param_dict={"n_neighbors":[1,3,5,7,9,11]}
estimator=GridSearchCV(estimator,param_grid=param_dict,cv=10)

estimator.fit(x_train,y_train)

##5.模型评估
###方法一:直接对比真实值和预测值
y_predict=estimator.predict(x_test)
print(y_test==y_predict)
###方法二:计算准确率
score=estimator.score(x_test,y_test)
print("准确率为:",score)

##6.获取结果分析
print("最佳参数:",estimator.best_params_)
print("最佳结果:",estimator.best_score_)
print("最佳估计器:",estimator.best_estimator_)
print("交叉验证的结果:",estimator.cv_results_)

朴素贝叶斯算法(sklearn.naive_bayes.MultinomialNB(alpha=1.0))

条件概率与联合概率

贝叶斯公式

拉普拉斯平滑系数(防止计算出的分类概率为0)

文本分类分析(新闻分类)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler #引入特征预处理中的标准化
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.naive_bayes import MultinomialNB
from sklearn.datasets import fetch_20newsgroups #引入新闻数据集
from sklearn.feature_extraction.text import TfidfVectorizer #文本提取的库
#1.获取数据
news=fetch_20newsgroups(subset="all")
#2.划分数据集
x_train,x_test,y_train,y_test=train_test_split(news.data,news.target)
#3.特征工程
transfer=TfidfVectorizer()
##3.1文本特征提取
x_train=transfer.fit_transform(x_train)
x_test=transfer.transform(x_test)
#4.朴素贝叶斯预估器流程
estimator=MultinomialNB()
estimator.fit(x_train,y_train)
#5.模型评估
##方法一:直接对比真实值和预测值
y_predict=estimator.predict(x_test)
print(y_test==y_predict)
##方法二:计算准确率
score=estimator.score(x_test,y_test)
print("准确率为:",score)

决策树(sklearn.tree.DecisionTreeClassifier)

信息论基础

1
2
3
4
5
6
1.信息:
香农:消除随机不定性的东西
例:小明 年龄未知 "我今年18岁了" (我可以通过说的这句话推断出年龄,消除了不知道的年龄)--就是信息
小华 "小明明年19岁" (因为小明的话已经推断出年龄,所以这句话不算消除) --不是信息
2.信息的衡量(信息商/信息熵)
3.信息增益[g(D,A)]=信息熵[H(D)]-条件熵[H(D|A)]

决策树划分依据(3种)

1
2
3
1. ID3  信息增益(最大的准则)
2. C4.5 信息增益比(最大的准则)
3. CART 分类树:基尼系数(最小的准则) 在sklearn中可以选择划分的默认原则

决策树的实现

1
2
3
4
5
sklearn.tree.DecisionTreeClassifier(criterion='gini',max_depth=None,random_state=None)
1.决策树分类器
2.criterion: 默认是gini系数(也可以选择信息增益的熵entropy)
3.2.
4.random_state: 随机数种子

鸢尾花预测

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler #引入特征预处理中的标准化
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer #文本提取的库
from sklearn.tree import DecisionTreeClassifier #决策树
from sklearn.datasets import load_iris #传入鸢尾花数据集
#1.获取数据
iris=load_iris()
#2.划分数据集
x_train,x_test,y_train,y_test=train_test_split(iris.data,iris.target,random_state=22)
#4.决策树预估器流程
estimator=DecisionTreeClassifier(criterion='entropy') #设置为数据增益
estimator.fit(x_train,y_train)
#5.模型评估
##方法一:直接对比真实值和预测值
y_predict=estimator.predict(x_test)
print(y_test==y_predict)
##方法二:计算准确率
score=estimator.score(x_test,y_test)
print("准确率为:",score)

决策树可视化(sklearn.tree.export_graphviz()导出DOT格式)

1
2
3
4
5
6
7
sklearn.tree.export_graphviz()该函数能够导出DOT格式
1.决策树可视化
2.estimator: 预估器对象
3.out_file: 输出名称
4.feature_names:特征的名字

得到dot文件之后复制内容去http://webgraphviz.com/执行

泰坦尼克号乘客生存预测

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler #引入特征预处理中的标准化
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction import DictVectorizer #缺失值处理
from sklearn.feature_extraction.text import TfidfVectorizer #文本提取的库
from sklearn.tree import DecisionTreeClassifier #决策树
from sklearn.tree import export_graphviz #决策树可视化
#1.获取数据
titanic=pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt')
##1.1数据处理
x=titanic[['pclass','age','sex']]
y=titanic['survived']
##1.2缺失值处理(将特征当中有类别的特征进行字典特征抽取)
x['age'].fillna(x['age'].mean(),inplace=True)
dict=DictVectorizer(sparse=False)
x=dict.fit_transform(x.to_dict(orient="records"))
#2.划分数据集
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3)
#3.决策树预估器流程
estimator=DecisionTreeClassifier(max_depth=5) #设置为数据增益
estimator.fit(x_train,y_train)
#4.模型评估
score=estimator.score(x_test,y_test)
print("准确率为:",score)

随机森林(sklearn.ensemble.RandomForestClassifier)

1
2
3
4
5
6
7
8
9
10
11
12
13
1.随机森林: 一个包含多个决策树的分类器(输出的类型是通过个别树输出的类别的众数决定)
2.随机:
2.1 训练集随机: bootstrap随机有放回抽样
2.2 特征随机: 从M个特征中随机抽取m个特征(很像降维)

3.API: sklearn.ensemble.RandomForestClassifier
3.1 随机森林分类器
3.2 n_estimators: 几个估计器
3.3 criterion: 默认gini系数,(也可以使用信息增益的熵entropy)
3.4 max_depth: 树的深度
3.5 bootstrap: 是否设置随机有放回抽样
3.6 random_state:
3.7 min_samples_split:

回归问题

线性回归

线性回归定义

1
2
3
4
5
6
7
8
9
1.基本概念:通过回归方程(函数)对一个/多个自变量(特征值)和因变量(目标值)之间关系进行建模的一种分析方式
2.线性模型(回归方程):特征值和目标值之间建立一个关系
3.线性模型分类:
3.1 线性关系
3.1.1 直线关系: 单特征与目标值的关系
3.1.2 平面关系: 两个特征与目标值的关系
3.2 非线性关系
3.2.1 自变量一次: y=ax1+bx2+cx3+....+b (最多是x的一次方)
3.2.2 参数一次: y=ax1+bx2^2+cx3^3+...+b (a1/b/c等等都是一次)

线性回归通用公式:

最小二乘法(损失函数)

最小二乘法公式:

优化方法之正规方程(直接求解sklearn.linear_model.LinearRegression)

1
2
3
4
 sklearn.linear_model.LinearRegression(fit_intercept=True)
1.fit_intercept: 是否计算偏置
2.LinearRegression.coef_: 回归系数
3.LinearRegression.intercept_: 偏置

优化方法之梯度下降(不断试错sklearn.linear_model.SGDRegressor)

1
2
3
4
5
6
7
8
9
10
 sklearn.linear_model.SGDRegressor(loss="squared_loss",fit_intercept=True,learing_rate='invscaling',eta0=0.01)
1.SGDRegressor类实现了随机梯度下降学习(支持不同的loss函数和正则化惩罚项来拟合线性回归模型)
2.loss: 默认是普通最小二乘法squared_loss
3.fit_intercept: 是否计算偏置
4.learing_rate: 学习率填充
4.1 constant(常数值的学习率): eta=eta0
4.2 optimal(默认): eta=1.0/(alpha=*(t+t0))
4.3 invscaling: eta=eta0/pow(t,power_t) [power_t=0.25存在父类当中]
4.4 SGDRegressor.coef_: 回归系数
4.5 SGDRegressor.intercept_: 偏置

波士顿房价预测(正规方程和梯度下降对比)

正则方程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import numpy as np
import pandas as pd
from sklearn.datasets import load_boston #导入波士顿数据集
from sklearn.model_selection import train_test_split #划分数据集
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
#1.获取数据集
boston=load_boston()
#2.划分数据集
x_train,x_test,y_train,y_test=train_test_split(boston.data,boston.target,random_state=22)
#3.标准化
transfer=StandardScaler()
x_train=transfer.fit_transform(x_train) #训练集
x_test=transfer.transform(x_test) #测试集
#4.决策树预估器流程
estimator=LinearRegression()
estimator.fit(x_train,y_train)
##得出模型
print("权重系数为:",estimator.coef_)
print("偏置为:",estimator.intercept_)

梯度下降

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import numpy as np
import pandas as pd
from sklearn.datasets import load_boston #导入波士顿数据集
from sklearn.model_selection import train_test_split #划分数据集
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model.stochastic_gradient import SGDRegressor
#1.获取数据集
boston=load_boston()
#2.划分数据集
x_train,x_test,y_train,y_test=train_test_split(boston.data,boston.target,random_state=22)
#3.标准化
transfer=StandardScaler()
x_train=transfer.fit_transform(x_train) #训练集
x_test=transfer.transform(x_test) #测试集
#4.决策树预估器流程
estimator=SGDRegressor()
estimator.fit(x_train,y_train)
##得出模型
print("权重系数为:",estimator.coef_)
print("偏置为:",estimator.intercept_)

两者对比

回归性能评估(sklearn.metrics.mean_squared_error)

回归性能评估公式:

1
2
3
4
5
6
7
8
9
10
11
12
	1.API: sklearn.metrics.mean_squared_error(y_true,y_pred)
1.1 均方误差回归损失
1.2 y_true: 真实值
1.3 y_pred: 预测值

#在之前的基础上:
from sklearn.metrics import mean_squared_error
#5.模型评估
y_predict=estimator.predict(x_test)
print("预测房价:",y_predict)
error=mean_squared_error(y_test,y_predict)
print("梯度下降的-均方误差为:",error)

刚才的波士顿房价上进行预测:

梯度下降优化方法(GD/SGD/SAG)

1
2
3
4
5
1.GD(原始的):计算所有样本的值才能够得到梯度(计算量大)

2.SGD(随机梯度下降):一次迭代只考虑一个训练样本

3.SAG(随机平均梯度法):提高收敛速度(SGDRegressor和岭回归以及逻辑回归中都会有SAG优化)

欠拟合与过拟合()

1
2
3
4
5
6
7
8
 训练集很合理,测试集不行
1.欠拟合:一个假设在训练数据上不能够获得比其他假设更好的拟合,测试集上不能很好拟合(学的特征太少)
1.1 原因:学习的特征过少
1.2 解决方法:增加数据的特征数量

2.过拟合:一个假设在训练数据上能够获得比其他假设更好的拟合,测试集上不能很好拟合(学的特征太多)
2.1 原因:原始特征过多,存在一些嘈杂特征,模型过于复杂
2.2 解决方法:正则化

正则化

1
2
3
1. L1正则化:可以使得其中一些w的值直接为0,删除这个特征的影响  (LASSO回归)

2. L2正则化:可以使得其中一些w都很小,都接近0,削弱某个特征的影响 (Ridge回归)

岭回归(带L2正则化的线性回归)

1
2
3
4
5
6
1.API: sklearn.linear_model.Ridge(alpha=1.0,fit_intercept=True,solver="auto",normalize=False)
1.1 alpha: 正则化力度 (0-1 1-10)
1.2 solver: 会根据数据自动选择优化方法(如果数据集和特征都较大会使用SAG随机平均梯度法)
1.3 normalize: 数据是否进行标准化
1.4 Ridge.coef_: 回归权重
1.5 Ridge.intercept_: 回归偏置

波士顿房价预测(岭回归Ridge)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import numpy as np
import pandas as pd
from sklearn.datasets import load_boston #导入波士顿数据集
from sklearn.model_selection import train_test_split #划分数据集
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
#1.获取数据集
boston=load_boston()
#2.划分数据集
x_train,x_test,y_train,y_test=train_test_split(boston.data,boston.target,random_state=22)
#3.标准化
transfer=StandardScaler()
x_train=transfer.fit_transform(x_train) #训练集
x_test=transfer.transform(x_test) #测试集
#4.决策树预估器流程
estimator=Ridge()
estimator.fit(x_train,y_train)
##得出模型
print("权重系数为:",estimator.coef_)
print("偏置为:",estimator.intercept_)

分类算法

逻辑回归

逻辑回归概念

sigmoid函数

逻辑回归过程

流程:

逻辑回归损失(对数似然损失)

对数似然损失:

综合完整损失函数:

逻辑回归损失优化(梯度下降)

1
减少损失函数的值 --> 更新逻辑回归前面对应算法的权重参数 --> 提升原本属于1类别的概率,降低原本属于0类别的概率

逻辑回归API(sklearn.linear_model.LogisticRegression)

1
2
3
4
1. sklearn.linear_model.LogisticRegression(solver='liblinear',penalty='l2',c=1.0)
1.1 solver: 优化求解方式(默认开源的liblinear库实现,内部使用了坐标轴下降法来迭代优化损失函数)
1.2 penalty: 正则化的种类(l1和l2(默认))
1.3 c: 正则化力度

癌症分类

数据描述:

1
2
3
4
5
6
7
8
9
10
11
12
1.原始数据:https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/
2.数据分析:
2.1 一共699条样本,共11列数据(第一列id,后9列分别是与肿瘤相关的医学特征,最后一列表示肿瘤类型的数值)
2.2 包含16个缺失值(用?标出)

3.流程分析:
3.1 获取数据(读取时加上names)
3.2 数据处理(处理缺失值)
3.3 数据集划分
3.4 特征工程(无量纲化处理-标准化)
3.5 逻辑回归预估器
3.6 模型评估

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
#3.1 获取数据(读取时加上names)
path="https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data"
column_name = ['Sample code number', 'Clump Thickness', 'Uniformity of Cell Size', 'Uniformity of Cell Shape', 'Marginal Adhesion', 'Single Epithelial Cell Size', 'Bare Nuclei', 'Bland Chromatin', 'Normal Nucleoli', 'Mitoses', 'Class']
data=pd.read_csv(path,names=column_name)
print(data)
#3.2 数据处理(处理缺失值)
data=data.replace(to_replace='?',value=np.nan) #将所有缺失值用NaN替换?
data=data.dropna() #删掉所有NaN值
#3.3 数据集划分
x=data[column_name[1:10]]
y=data[column_name[10]]
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3)
#3.4 特征工程(无量纲化处理-标准化)
std=StandardScaler()
x_train=std.fit_transform(x_train)
x_test=std.transform(x_test)
#3.5 逻辑回归预估器
lr=LogisticRegression()
lr.fit(x_train,y_train)
#3.6 模型评估
print("得出来的权重:",lr.coef_)
print("预测的类别:",lr.predict(x_test))
print("预测的准确率:",lr.score(x_test,y_test))

分类的评估方法(sklearn.metrics.classification_report)

混淆矩阵

混淆矩阵:

精确率(Precision)与召回率(Recall)

精确率:

召回率:

F1-score

分类评估预测API

1
2
3
4
5
6
1.sklearn.metrics.classification_report(y_true,y_pred,labels=[],target_names=None)
1.1 y_true: 真实目标值
1.2 y_pred: 估计器预测目标值
1.3 labels: 指定类别对应的数字
1.4 target_names: 目标类别名称
1.5 return: 每个类别精准率与召回率

上面基础上加入分类评估

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
#3.1 获取数据(读取时加上names)
path="https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data"
column_name = ['Sample code number', 'Clump Thickness', 'Uniformity of Cell Size', 'Uniformity of Cell Shape', 'Marginal Adhesion', 'Single Epithelial Cell Size', 'Bare Nuclei', 'Bland Chromatin', 'Normal Nucleoli', 'Mitoses', 'Class']
data=pd.read_csv(path,names=column_name)
#3.2 数据处理(处理缺失值)
data=data.replace(to_replace='?',value=np.nan)
data=data.dropna()
#3.3 数据集划分
x=data[column_name[1:10]]
y=data[column_name[10]]
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3)
#3.4 特征工程(无量纲化处理-标准化)
std=StandardScaler()
x_train=std.fit_transform(x_train)
x_test=std.transform(x_test)
#3.5 逻辑回归预估器
lr=LogisticRegression()
lr.fit(x_train,y_train)
print("得出来的权重:",lr.coef_)
print("预测的类别:",lr.predict(x_test))
print("预测的准确率:",lr.score(x_test,y_test))

#3.6 模型评估
print("精确率和召回率为:",classification_report(y_test,lr.predict(x_test),labels=[2,4],target_names=['良性','恶性']))

TPR和FPR

ROC曲线

通过FPR和TPR来构成:

AUC指标(sklearn.metrics.roc_auc_score)

1
2
3
4
5
6
7
8
1.AUC的概率意义: 随机取一对正负样本,正样本得分>负样本的概率
2.AUC取值范围: 0.5-1(取值越高越好,说明TPR高)
2.1 0.5<AUC<1: 优于随机猜测
2.2 AUC=1:完美分类器(不管怎么设定阈值都能完美预测)
3.API: sklearn.metrics.roc_auc_score(y_true,y_score)
3.1 计算ROC曲线面积(AUC值)
3.2 y_true: 每个样本的真实类别(必须为0/1)
3.3 y_score: 每个样本预测的概率值

上面基础上加入auc指标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.metrics import roc_auc_score
#3.1 获取数据(读取时加上names)
path="https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data"
column_name = ['Sample code number', 'Clump Thickness', 'Uniformity of Cell Size', 'Uniformity of Cell Shape', 'Marginal Adhesion', 'Single Epithelial Cell Size', 'Bare Nuclei', 'Bland Chromatin', 'Normal Nucleoli', 'Mitoses', 'Class']
data=pd.read_csv(path,names=column_name)
#3.2 数据处理(处理缺失值)
data=data.replace(to_replace='?',value=np.nan)
data=data.dropna()
#3.3 数据集划分
x=data[column_name[1:10]]
y=data[column_name[10]]
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3)
#3.4 特征工程(无量纲化处理-标准化)
std=StandardScaler()
x_train=std.fit_transform(x_train)
x_test=std.transform(x_test)
#3.5 逻辑回归预估器
lr=LogisticRegression()
lr.fit(x_train,y_train)
print("得出来的权重:",lr.coef_)
print("预测的类别:",lr.predict(x_test))
print("预测的准确率:",lr.score(x_test,y_test))

#3.6 模型评估
print("精确率和召回率为:",classification_report(y_test,lr.predict(x_test),labels=[2,4],target_names=['良性','恶性']))
y_test=np.where(y_test>2.5,1,0) #将2和4转换为0和1用于auc的参数
print("auc",roc_auc_score(y_test,lr.predict(x_test)))

模型保存和加载(sklearn.externals.joblib)

sklearn模型API

1
2
3
1.sklearn.externals.joblib
1.1 保存: joblib.dump(estimator,'test.pkl') #后缀为pkl文件
1.2 加载: estimator=joblib.load('test.pkl')

无监督学习

1
2
1.聚类: K-means算法(K均值聚类)
2.降维: PCA

K-means算法(sklearn.cluster.KMeans)

四步骤示意图

1
2
3
4
1、随机设置K个特征空间内的点作为初始的聚类中心
2、对于其他每个点计算到K个中心的距离,未知的点选择最近的一个聚类中心点作为标记类别
3、接着对着标记的聚类中心之后,重新计算出每个聚类的新中心点(平均值)
4、如果计算得出的新中心点与原中心点一样,那么结束,否则重新进行第二步过程

K-means算法API

1
2
3
4
5
1.API: sklearn.cluster.KMeans(n_clusters=8,init='k-means++')
1.1 k-means聚类
1.2 n_clusters: 开始聚类中心的数量(几个堆)
1.3 init: 初始方法
1.4 labels_:默认标记的类型(可以和真实值比较)

对Instacart Market用户聚类

1
2
3
4
5
6
	1.降维后的数据
2.k-means聚类
3.聚类结果显示
km=KMeans(n_clusters=4)
km.fit(data)
pre=km.predict(data)

Kmeans性能评估指标(sklearn.metrics.silhouette_score)

轮廓系数

1
2
3
4
1.很像高级语言程序里面的"高内聚低耦合"
2.轮廓系数介于[-1,1]
3.b_i >> a_i : 轮廓系数趋近于1 效果很好
4.b_i << a_i : 轮廓系数趋近于-1 效果不好

轮廓系数API

1
2
3
4
sklearn.metrics.silhouette_score(X,labels)
1.计算所有样本的平均轮廓系数
2.X:特征值
3.labels:被聚类标记的目标值

python

初识python

1
2

python安装以及环境配置参考https://www.bilibili.com/video/BV1wD4y1o7AS?p=3&spm_id_from=pageDriver

第一个输出

1
2
3
4
1.文件-新建-新建项目
2.选择项目右键新建-文件名为first.py
3.书写print("hello world");
4.点击空白位置右键run first


输出(print)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

#输出数字
print(520);
print(98.5);

#输出字符串
print("123s");
print('123as');

#输出含有运算符的表达式
print(3+1); #输出4

#输出到文件中
fp=open('D:/test.txt','a+'); #输出到d盘下面
print('helloworld',file=fp); #输出内容为 helloworld
fp.close();

#不进行换行输出(输出内容在一行) --用逗号隔开
print('hello','world','Python');

输出其他内容

输出到文件里面


转义字符和原字符(r/R+字符串)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

print('--1.转行(分行)-------------');
print('hello\nworld');

print('--2.制表(四个字符为一个)-------------');
print('hello\tworld');
print('helloooo\tworld'); #四个字符是一个\t

print('--3.回车功能(覆盖符号之前的所有内容)---');
print('hello\rworld'); #hello输入之后回车world会把hello挤掉

print('--4.退一个格功能--------------');
print('hello\bworld');

print('--5.将字符串里面的单引号不被识别为转义字符---------------------------');
print('老师说:\'给我考满分\'');

print('--不希望转义字符起作用,使用原字符(字符串前面加r/R)------');
print(r'hello\nworld');
print(r'hello\nworld\\'); #注意:最后两个是\\ √
print(r'hello\nworld\'); #注意:最后一个字符不能是\ ×


标识符和保留字

1
类似于java和c语言

后续

1
2

俺买了python从入门到实践,看书去了!

B册编程题

第1章 认识c语言

1.1 计算长方形面积和周长

具体代码

1
2
3
4
5
6
7
8
9
10
11
12

#include <stdio.h>
int main(){
double x,y;
double c,s;
scanf("%lf,%lf",&x,&y); //逗号隔开输入长x和宽y
c=2*x+2*y; //周长
s=x*y; //面积
printf("周长是%.5f\n",c);
printf("面积是%.5f\n",s);
return 0;
}

执行结果


1.2 计算两者取余(%)和整除(/)

具体代码

1
2
3
4
5
6
7
8
9

#include <stdio.h>
int main(){
int a,b;
scanf("%d %d",&a,&b); //题目要求输入两个整数
printf("整除结果是%d\n",a/b); //因为都是整数 所以结果也是整数
printf("取余结果是%d\n",a%b); //因为都是整数 所以结果也是整数
return 0;
}

执行结果


1.3 分割浮点数的整数和小数部分

具体代码

1
2
3
4
5
6
7
8
9
10
11
12

#include <stdio.h>
int main(){
double a;
double xiao=0;
scanf("%lf",&a); //输入一个浮点数a
int n=(int)(a); //强转为int就是整数部分
xiao=a-n; //然后用原始数据-整数部分
printf("整数部分是%d\n",n);
printf("小数部分是%f\n",xiao);
return 0;
}

执行结果


1.4 大小写互换

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13

#include <stdio.h>
int main(){
char n;
char n1;
scanf("%c",&n);
n1=n-32; //小写转大写需要减少32
printf("大写对应的ASCII码为:%d\n",n1);
printf("小写对应的ASCII码为:%d\n",n);
printf("大写的字符为:%c\n",n1);
printf("小写的字符为:%c\n",n);
return 0;
}

执行结果


1.5 华室温度转摄氏温度

具体代码

1
2
3
4
5
6
7
8
9
10

#include <stdio.h>
int main(){
double hua; //华氏温度
double she; //摄氏温度
scanf("%lf",&hua); //输入华氏温度
she=5*(hua-32)/9.0; //公式
printf("%f",she); //使用默认格式长度输出
return 0;
}

执行结果


第2章 顺序结构

2.1 输入圆半径,得到半径相关数据

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

#include <stdio.h>
#define PI 3.1415926
int main(){
double r;
double zc,mj,tj;
scanf("%lf",&r); //输入格式lf 老忘记
printf("输入的圆的半径为%.3f\n",r);
zc=2*PI*r; //周长是2*πr
mj=PI*r*r; //面积是π*r*r
tj=(PI*r*r*r*4)/3; //体积是三分之四的π*r*r*r
printf("原的周长是:%.3f\n",zc);
printf("原的面积是:%.3f\n",mj);
printf("原的体积是:%.3f\n",tj);
return 0;
}

执行结果


2.2 成绩信息统计

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

#include <stdio.h>
int main(){
double c1,c2,c3,c4; //四门课
double ag; //四门课平均值
//题目要求输入四门课成绩
printf("请输入四门课成绩,并间隔逗号:\n");
scanf("%lf,%lf,%lf,%lf",&c1,&c2,&c3,&c4);
ag=(c1+c2+c3+c4)/4; //计算平均值
printf("第一门课成绩c1为:%.2f\n",c1);
printf("第二门课成绩c2为:%.2f\n",c2);
printf("第三门课成绩c3为:%.2f\n",c3);
printf("第四门课成绩c4为:%.2f\n",c4);
printf("平均值为%.2f",ag); //题目要求保留两位小数
return 0;
}

执行结果


c语言课本题目

第一章 初识c语言

例1.1 屏幕输出一行信息

具体代码

1
2
3
4
5
6

#include <stdio.h>
int main(){
printf("hello world");
return 0;
}

执行结果


例1.2 求两个整数之和

具体代码

1
2
3
4
5
6
7
8
9
10

#include <stdio.h>
int main(){
int a,b,sum;
a=123;
b=456;
sum=a+b;
printf("sum 之和是:%d\n",sum);
return 0;
}

执行结果


例1.3 求最大值

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

#include <stdio.h>
int main(){
int a,b,sum;
int da(int a,int b); //一定要定义方法 而且里面要有数据类型
scanf("%d,%d",&a,&b); ///scanf输入
sum=da(a,b); //调用方法返回max给sum
printf("两个之中最大的是:%d\n",sum);
return 0;
}

int da(int a,int b){
int max; //存储最后的最大值
if(a>b){
max=a; //a大
}else{
max=b; //b大
}
return max;
}

执行结果


习题5 输出*****图形

具体代码

1
2
3
4
5
6
7
8
9

#include <stdio.h>
int main(){
printf("*****\n");
printf(" *****\n");
printf(" *****\n");
printf(" *****\n");
return 0;
}

执行结果


第二章 算法

例2.1 求1到5乘积

具体代码

1
2
3
4
5
6
7
8
9
10

#include <stdio.h>
int main(){
int sum=1;
for(int i=1;i<=5;i++){ //循环乘1*2*3*4*5
sum*=i;
}
printf("%d",sum); //输出结果
return 0;
}

执行结果


例2.3 判断闰年

具体代码

1
2
3
4
5
6
7
8
9
10

#include <stdio.h>
int main(){
for(int i=2000;i<=2500;i++){
if(i%400==0||(i%4==0&&i%100!=0)){ //符合条件输出
printf("%d ",i);
}
}
return 0;
}

执行结果


例2.4 求1-(1/2)+(1/3)-(1/4)到-(1/100)

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

#include <stdio.h>
int main(){
double sum=0; //得到最后结果
double temp=0; //获取每次的值
for(int i=1;i<=100;i++){ //相加100次
temp=1.0/i; //一定是1.0 不然就是整除为0了
if(i%2==0){
temp=temp*(-1); //奇数都是负的
}
sum+=temp; //每次相加
}
printf("%.10f",sum); //输出小数点后10位
return 0;
}

执行结果


例2.5 判断素数

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

#include <stdio.h>
int main(){
int n;
scanf("%d",&n); //输入一个整数
if(n>=3){
for(int i=2;i<n;i++){ //从2开始依次
if(n%i!=0){ //如果不能被整除就不是素数
printf("%d",n);
break;
}else{
break; //如果可以被整除那就不是
}
}

}
else{
printf("输入的数字不比3大,输入错误请重新输入!");
}

return 0;
}

执行结果


第三章 顺序程序设计

例3.1 温度转换

具体代码

1
2
3
4
5
6
7
8
9
10

#include <stdio.h>
int main(){
double n; //华氏法
double res; //转换结果
scanf("%lf",&n); //一定是lf
res=5.0*(n-32)/9; //转化公式
printf("%f\n",res); //输出结果
return 0;
}

执行结果


例3.3 大小写转换

具体代码

1
2
3
4
5
6
7
8

#include <stdio.h>
int main(){
char a;
a='A'; //赋值
a=a+32; //大写+32=小写
printf("%c\n",a);
}

执行结果


例3.4 求三角形面积(海伦公式)

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

#include <stdio.h>
#include <Math.h> //后面要用sqrt开根号的函数
int main(){
double a; //边1
double b; //边2
double c; //边3
double s; //海伦公式里面的s
double res; //获取最终结果
scanf("%lf,%lf,%lf",&a,&b,&c); //输入三边
s=(a+b+c)/2;
res=sqrt(s*(s-a)*(s-b)*(s-c)); //海伦公式
printf("%.5f",res);
return 0;
}

执行结果


例3.5 求一元二次方程的根

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#include <stdio.h>
#include <Math.h>
int main(){
int a; //x2的系数
int b; //x的系数
int c; //常数的系数
double temp;
double res1;
double res2;
scanf("%d,%d,%d",&a,&b,&c); //输入一定要用逗号隔开
temp=b*b-4*a*c;
res1=(-b+sqrt(temp))/(2.0*a);
res2=(-b-sqrt(temp))/(2.0*a);
printf("%7.2f",res1);
printf("%7.2f",res2);
return 0;
}

执行结果


例3.9 输入三个字符,然后putchar输出

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

#include <stdio.h>
#include <Math.h>
int main(){
char a='B';
char b='O';
char c='Y';
printf("输入新的之前%c%c%c\n",a,b,c);
scanf("%c",&a);
printf("输入新的之后");
putchar(a); //putchar输出单个字符
putchar(b);
putchar(c);
return 0;
}

执行结果


例3.10 输入大写字母输出小写

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

#include <stdio.h>
#include <Math.h>
int main(){
char a='B';
char b='O';
char c='Y';
printf("输入新的之前%c%c%c\n",a,b,c);
scanf("%c",&a);
printf("输入新的之后");
putchar(a); //putchar输出单个字符
putchar(b);
putchar(c);
return 0;
}

执行结果


习题3.4 输入不同类型的c1和c2字符

1.输入字符类型范围内c1和c2

具体代码

1
2
3
4
5
6
7
8
9
10
11

#include <stdio.h>
#include <Math.h>
int main(){
char c1,c2;
c1=97; //char范围是-127到128
c2=98;
printf("c1=%c,c2=%c\n",c1,c2);
printf("c1=%d,c2=%d\n",c1,c2);
return 0;
}

执行结果

2.输入字符类型范围外c1和c2

具体代码

1
2
3
4
5
6
7
8
9
10
11

#include <stdio.h>
#include <Math.h>
int main(){
char c1,c2;
c1=197; //char范围是-127到128 所以输入的是范围外
c2=198;
printf("c1=%c,c2=%c\n",c1,c2);
printf("c1=%d,c2=%d\n",c1,c2);
return 0;
}

执行结果

3.输入整数类型范围内c1和c2

具体代码

1
2
3
4
5
6
7
8
9
10
11

#include <stdio.h>
#include <Math.h>
int main(){
int c1,c2; //整数类型c1和c2
c1=97;
c2=98;
printf("c1=%c,c2=%c\n",c1,c2); //整数类型赋给字符类型 可能存在截取
printf("c1=%d,c2=%d\n",c1,c2); //本来输入的就是int类型 所以就输出原样
return 0;
}

执行结果


习题3.5 多种类型输入和输出

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

#include <stdio.h>
#include <Math.h>
int main(){
int a,b;
float x,y;
char c1,c2;
scanf("a=%db=%d",&a,&b);
scanf("%f%e",&x,&y);
scanf("%c%c",&c1,&c2);
printf("a=%d,b=%d",a,b);
printf("x=%f,y=%e",x,y);
printf("a=%c,b=%c",c1,c2);
return 0;
}

执行结果


习题3.6 China译成密码

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

#include <stdio.h>
int main(){
char c1,c2,c3,c4,c5; //定义五个字符
c1='C'; //给五个字符赋初值
c2='h';
c3='i';
c4='n';
c5='a';
c1=c1+4; //直接加4就行
c2=c2+4;
c3=c3+4;
c4=c4+4;
c5=c5+4;
putchar(c1); //使用输出单个字符函数输出
putchar(c2);
putchar(c3);
putchar(c4);
putchar(c5);
printf("\n");
printf("%c",c1); //使用printf输出
printf("%c",c2);
printf("%c",c3);
printf("%c",c4);
printf("%c",c5);
return 0;
}

执行结果


第4章 选择结构程序设计

例4.2 输入两个数排序

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14

#include <stdio.h>
int main(){
double a,b; //要排序的a和b
double t; //中间变量
scanf("%lf,%lf",&a,&b);
if(a<b){ //两个数交换 一定要有个中间变量t
t=a;
a=b;
b=t;
}
printf("最大的是%.5f,最小的是%.5f\n",a,b);
return 0;
}

执行结果


例4.3 输入三个数排序

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

#include <stdio.h>
int main(){
double a,b,c; //要排序的三个数
double t; //中间变量
scanf("%lf,%lf,%lf",&a,&b,&c); //double要用lf输入
if(a>b){ //b小 放前面
t=a;
a=b;
b=t;
}
if(a>c){ //说明a<b 如果c小 交换a和c
t=a;
a=c;
c=t;
}
if(b>c){ //前面都不符合说明a是最小的 要比较b和c
t=b;
b=c;
c=t;
}
printf("%.5f,%.5f,%.5f\n",a,b,c);
return 0;
}

执行结果


例4.4 大小写转换

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13

#include <stdio.h>
int main(){
char a;
scanf("%c",&a); //a=getchar();
if(a>='A'&&a<='Z'){ //大写转小写
a=a+32;
}else{ //小写不用转换

}
printf("%c\n",a);
return 0;
}

执行结果


例4.5 分段函数

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

//1.简单的if语句
#include <stdio.h>
int main(){
int x,y; //
scanf("%d",&x); //输入x 对应输出y
if(x<0){
y=-1;
}
if(x=0){
y=0;
}
if(x>0){
y=1;
}
printf("%d",y); //输出对应y
return 0;
}

执行结果


例4.6 按照等级输出成绩

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

#include <stdio.h>
int main(){
char grade;
scanf("%c",&grade); //输入分数
switch(grade)
{
case 'A':printf("85-100分\n");break;
case 'B':printf("70-84分\n");break;
case 'C':printf("60-69分\n");break;
case 'D':printf("<60分\n");break;
default:printf("重新输入成绩等级!");
}
return 0;
}

执行结果


例4.7 switch语句处理菜单命令

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

#include <stdio.h>
int main(){
void action1(int a,int b); //声明两个函数
void action2(int a,int b);
char ch; //要判断的字符
int a=15;
int b=23;
ch=getchar(); //输入一个字符
switch(ch)
{
case 'A':
case 'a':action1(a,b);break; //A和a同时跳转action1方法
case 'B':
case 'b':action2(a,b);break; //B和b同时跳转action1方法
default:printf("不符合题意,重新登陆!");
}
return 0;
}

void action1(int a,int b){
printf("执行action1方法之后结果是%d\n",a+b); //加法
}

void action2(int a,int b){
printf("执行action2方法之后结果是%d\n",a*b); //乘法
}

执行结果


习题4.4 输出三个数最大数

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

#include <stdio.h>
int main(){
int a,b,c;
int t; //作为中间值
scanf("%d,%d,%d",&a,&b,&c); //输入三个整数
if(a>b){ //a大 往后放
t=a;
a=b;
b=t;
}
if(a>c){ //a<b 看看a和c的大小
//a大 往后放 这样的话就是 c<a<b
t=a;
a=c;
c=t;
}
if(b>c){ //a<b a<c 但是b和c的大小要排序
//b>c>a 要把b和c换一下
t=b;
b=c;
c=t;
}
printf("三个数中最大的是:%d",c);
return 0;
}

执行结果


习题4.5 输出平方根

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14

#include <stdio.h>
#include <math.h> //使用sqrt函数
int main(){
int a;
int res;
scanf("%d",&a); //输入一个<1000的正数
if(a>=1000){
printf("输入有误,请重新输入!!!");
}
res=(int)sqrt(a); //强转为int 这样输出整数部分
printf("平方根为:%d",res);
return 0;
}

执行结果


习题4.5 分段函数输出y值

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

#include <stdio.h>
int main(){
int x,y;
scanf("%d",&x); //输入整数x
if(x<1){
y=x;
}else if(x>=1&&x<10){
y=2*x-1;
}else if(x>=10){
y=3*x-11;
}
printf("输入的x值是:%d\n",x);
printf("对应的y值是:%d",y);
return 0;
}

执行结果


习题4.9 拆每位数字

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

#include <stdio.h>
int main(){
int x;
scanf("%d",&x); //输入一个整数
int n=0;
int ge=0; //统计多少位
while(x!=0){ //每一位都拆完就结束
n=x%10; //取出每一位
printf("第%d位是%d\n",ge+1,n);
ge++;
x=x/10;
}
printf("一共是%d位",ge); //输出多少位
return 0;
}

执行结果


习题4.11 输入4个整数按序输出

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

#include<stdio.h>
int main()
{
int a,b,c,d,t;
scanf("%d,%d,%d,%d",&a,&b,&c,&d);
if(a>b){
t=a;
a=b;
b=t;
}
if(a>c){
t=a;
a=c;
c=t;
}
if(a>d){
t=a;
a=d;
d=t;
}
if(b>c){
t=b;
b=c;
c=t;
}
if(b>d){
t=b;
b=d;
d=t;
}
if(c>d){
t=c;
c=d;
d=t;
}
printf("%d,%d,%d,%d\n",a,b,c,d); //输出四个数字
return 0;
}

执行结果


第5章 循环结构程序设计

例5.8 斐波拉契数列

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

#include<stdio.h>
int main()
{
int a,b,c;
int flag=2; //记录是第几个数
a=1;
b=1;
printf("第1位的数字是:%d\n",a); //先输出前两个数
printf("第2位的数字是:%d\n",b);
for(int i=1;i<39;i++){ //循环40次
c=a+b; //当前值是前两者之和
flag++; //成功计算一次+1
printf("第%d位的数字是:%d\n",flag,c);
//替换新的a和b
a=b; //递推方式
b=c;
}
return 0;
}

执行结果


例5.10 100-200之内素数

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

#include<stdio.h>
#include<math.h> //要用sqrt函数
int main()
{
//求100-200所有素数
for(int i=100;i<200;i++){
int k=sqrt(i); //开根号
int flag=0; //标志位
for(int j=2;j<=k;j++){ //从2-k就可以
if(i%j==0){
flag=1; //能被整除就不是素数设置为1
}
}
if(flag==0){
printf("%d\n",i); //flag没变就是素数
}
}

return 0;
}

执行结果


习题5.3 求最大公约数和最小公倍数

具体代码

1
2


执行结果


习题5.4 分析字符串组成

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

#include<stdio.h>
int main()
{
int a=0; //统计英文字母个数
int b=0; //统计空格个数
int c=0; //统计数字个数
int d=0; //统计其他字符个数
char temp; //c语言没有字符串string类 所以用char输入
while((temp=getchar())!='\n'){ //换行键就结束
if((temp>='a'&&temp<='z')||(temp>='A'&&temp<='Z')){
a++;
}else if(temp>='0'&&temp<='9'){
c++;
}else if(temp==' '){
b++;
}else {
d++;
}
}
printf("英文字符的个数是:%d\n",a); //输出对应个数
printf("空格字符的个数是:%d\n",b);
printf("数字的个数是:%d\n",c);
printf("其他字符的个数是:%d\n",d);
return 0;
}

执行结果


习题5.8 水仙花数

具体代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

#include<stdio.h>
int main()
{
//水仙花数只能在3位数中出现
for(int i=100;i<999;i++){
int a=i/100; // 假以187为例 187/100=1
int b=i/10%10; // 187/10=18 18%10=8
int c=i%10; // 187%10=7
if(a*a*a+b*b*b+c*c*c==i){ //每位的立方次==原数
printf("%d\n",i);
}
}
return 0;
}

执行结果


初试code

记录前言

距离22考研还有260多天了,复习一切正常!写下这篇博客记录研究生初试专业课代码,用于思路整理和复习回顾。

复习大纲

蓝桥杯国赛

平方十位数

题目

分析

1. 其实就是找最大的平方十位数
2. 从开方最大数倒序找开发最小数中符合平方并且每一位只用过一次的数字
    2.1 最大的数就是10000000000-1 所以平方开始循环从10000(100000*100000=10000000000)开始
    2.2 最小的数就是100000000  所以开方从根号1000000000(31,622.77660168379≈31623)开始

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

public class Main {
public static void main(String[] args) {
for(long i=100000;i>32000;i--){
long temp=i*i; //找10位的平方数
String s=String.valueOf(temp); //将temp转字符串
boolean flag=true; //设置布尔值 如果不符合题意就退出
for(int j=0;j<10;j++){
if(s.indexOf(""+j)==-1){ //如果0-9不重复的使用 那么就不会有-1出现(每个数字都出现过)
flag=false;
break; //不符合就退出
}
}
if(flag){ //符合题意就弹出i*i=temp
System.out.println(temp);
break;
}
}

}
}

结果


三角形面积(海伦公式)

题目

分析

1. 通过把三角形凑成正方形,利用差计算结果
2. 海伦公式:
    2.1 s=(a+b+c)/2   (必须先计算出a和b和c)
    2.2 area=sqrt(s*(s-a)*(s-b)*(s-c));

代码

1
2
3
4
5
6
7
8
9
10
11
12

// 海伦公式
public class Main {
public static void main(String[] args) {
double a = Math.sqrt((6.4 - 2.3) * (6.4 - 2.3) + (3.1 - 2.5) * (3.1 - 2.5)); //分别计算三个边的长度
double b = Math.sqrt((5.1 - 2.3) * (5.1 - 2.3) + (7.2 - 2.5) * (7.2 - 2.5));
double c = Math.sqrt((6.4 - 5.1) * (6.4 - 5.1) + (7.2 - 3.1) * (7.2 - 3.1));
double s = (a + b + c) / 2.0; //计算s
double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
System.out.println(area);
}
}

结果


最大乘积(dfs)

题目

分析

1. 一定是结果

代码

1
2


结果


Linux系统目录结构

Linux系统目录结构

层次:


规范路径(栈stack)

题目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

Unix 风格的文件系统中:
一个点(.):当前目录本身
两个点(..):将目录切换到上一级(指向父目录)

1.必须始终以斜杠 / 开头,并且两个目录名之间必须只有一个斜杠 /。
2.最后一个目录名(如果存在)不能以 / 结尾。
3.必须是表示绝对路径的最短字符串。

示例 1:
输入:"/home/"
输出:"/home"
解释:注意,最后一个目录名后面没有斜杠。

示例 2:
输入:"/../"
输出:"/"
解释:从根目录向上一级是不可行的,因为根是你可以到达的最高级。

示例 3:
输入:"/home//foo/"
输出:"/home/foo"
解释:在规范路径中,多个连续斜杠需要用一个斜杠替换。

示例 4:
输入:"/a/./b/../../c/"
输出:"/c"

示例 5:
输入:"/a/../../b/../c//.//"
输出:"/c"

示例 6:
输入:"/a//bc/d//././/.."
输出:"/a/b/c"

分析

1.主要考察的是栈,所以定义一个辅助栈Stack
2.把字符串以"/"为分隔符分割成数组,此时数组有"路径"、""、"."、".."这四种情况;
3.遍历数组
    3.1 s[i].equals("..")&&stack.isEmpty()就出栈pop();
    3.2 !s[i].equals("")&&!s[i].equals(".")&&!s[i].equals(".."),即s[i]是路径就入栈;
4.如果栈空,直接返回"/"
  如果栈非空,使用StringBuffer连接栈元素

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

public class Main{
public static void main(String[] args){
Scanner input=new Scanner(System.in);
String s=input.next(); //输入字符串
System.out.println(simplifyPath(s)); //调用方法返回结果
}

public static String simplifyPath(String s){
int len=s.length(); //获取字符串长度
String[] str=s.split("/"); //根据/生成字符串数组
StringBuilder sb=new StringBuilder(); //最终转字符串
Stack<String> stack=new Stack<>(); //生成stack栈

for(int i=0;i<str.length;i++){
if(str[i].equals("..")&&!stack.isEmpty()){
stack.pop(); //如果是..就返回父目录 就要出栈
}else if(!str[i].equals("")&&!str[i].equals(".")&&!str[i].equals("..")){
stack.push(str[i]); //如果是路径 /abc中的abc就要入栈
}
}
if(stack.isEmpty()){
return "/"; //如果最终没有目录 就要返回/
}
for(int i=0;i<stack.size();i++){
sb.append("/"+stack.get(i)); //sb拼接即可
}
return sb.toString(); //转字符串
}

}

实现结果


LeetCode链表

删除排序链表的重复元素(改变指向)

题目

分析

1. 新建current链表指向head,方便后面移动
2. 只要当前节点值和下一个结点值相同就指向跳过下一个节点
3. 只要不相同就正常挪到下个节点判断

代码

1
2
3
4
5
6
7
8
9
10
11
12

public static ListNode deleteDuplicates(ListNode head) {
ListNode current = head; //要判断的链表给current
while (current != null && current.next != null) { //没到结尾
if (current.next.val == current.val) { //当前节点和下一个结点值相同
current.next = current.next.next; //直接跳过下一个节点
} else {
current = current.next; //不相同的话挪下一个结点判断
}
}
return head; //最后返回head即可
}

二进制链表转整数(倒序累积)

题目

分析

1. 使用while循环测试出多少个节点(数组方便给大小)
2. 使用while循环将每一位给数组
3. 倒序将二进制累计!!

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ListNode head1=new ListNode(1);
ListNode head2=new ListNode(0);
ListNode head3=new ListNode(1);
head1.next=head2; //生成三个节点 然后相连
head2.next=head3;
System.out.println(getDecimalValue(head1)); //调用方法返回结果
}

public static int getDecimalValue(ListNode head) {
int res=0;
int flag=0; //统计有几个节点
ListNode temp=head;
while(temp!=null){
flag++; //+1
temp=temp.next; //节点往后遍历
}

temp=head; //重新指向head
int[] a=new int[flag]; //存每一位
int t=0; //控制a数组下标
while(temp!=null){
a[t++]=temp.val; //记录当前值
temp=temp.next; //节点往后遍历
}
System.out.println("a数组"+Arrays.toString(a));

int zs=0; //控制每一位数字乘2的倍数
for(int i=a.length-1;i>=0;i--){
System.out.println("a[i]是:"+a[i]+" 当前倍数乘的是:"+Math.pow(2,zs));
res+=a[i]*Math.pow(2,zs);
zs++;
}
return res;
}

}

结果


,