写在前面
机器学习是一个螺旋上升的过程,加强基础也是非常重要,加油
Python Round⑨
循环识别
while True:
s = input("请输入信息:")
if s == "Y" or s == "y":
break
ps:其实也没完全达到需求,只能输入单个词,不能对字符里面的 y 或 Y 进行识别
Calendar
import calendar
year = int(input("请输入年份:"))
table = calendar.calendar(year)
print(table)
首次接触 calendar 库,输入的年份要将其转换为 int 类型
调用 calendar 库,采用 calendar() 方法获取日历
内容替换
s = input("请输入绕口令:")
print(s.replace("兵","将"))
turtle
import turtle
from turtle import *
def curvemove():
for i in range(200):
right(1)
forward(1)
setup(600,600,400,400)
hideturtle()
turtle.pencolor('black')
turtle.fillcolor("red")
pensize(2)
begin_fill()
left(140)
forward(111.65)
curvemove()
left(120)
curvemove()
forward(111.65)
end_fill()
penup()
goto(-27, 85)
pendown()
done()
ps:看着多其实要填的也就是一个 pencolor 一个 fillcolor 而已
九九乘法表
fo = open("123.txt","w")
for i in range(1,10):
for n in range(1,i+1):
fo.write("{0}*{1} = {2} ".format(i,n,i*n))
fo.write("\n")
fo.close()
综合应用
先贴自己的代码:
把横着的诗词转为竖式:
fi = open("关山月.txt","r")
fo = open("关山月2.txt","w",encoding="utf-8")
a = fi.read()
a = a.split("。")
a.pop() # 不知为何最后会多一个空,用pop()方法删除
for i in a:
fo.write(i+"。")
fo.write("\n")
fi.close()
fo.close()
诗词反转
f3 = open("关山月2.txt","r",encoding="utf-8")
f4 = open("关山月-反转.txt","w",encoding="utf-8")
a = f3.read()
a = a.split("\n")
a.pop()
for i in a[::-1]:
f4.write(i)
f4.write("\n")
f3.close()
f4.close()
再来看看参考答案:
fi = open("关山月.txt","r")
fo = open("关山月-诗歌.txt","w")
txt = fi.read()
ls = txt.split("。")
fo.write("。\n".join(ls)) #这个思维值得学习
fi.close()
fo.close()
fi = open("关山月-诗歌.txt","r")
fo = open("关山月-反转.txt","w")
txt = fi.readlines()
txt.reverse()
for row in txt:
fo.write(row)
fi.close()
fo.close()
对于这种一行一行的直接 readlines() ,而后接一个 reverse() 确实比自己写的方便些
今天还看到一个花型代码,也记录下来,算是奖励自己坚持到第九轮的小彩蛋吧~
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import LinearLocator
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)
fig = plt.figure()
ax = fig.gca(projection='3d')
[x, t] = np.meshgrid(np.array(range(25)) / 24.0, np.arange(0, 575.5, 0.5) / 575 * 17 * np.pi - 2 * np.pi)
p = np.pi / 2 * np.exp(-t / (8 * np.pi))
u = 1 - (1 - np.mod(3.6 * t, 2 * np.pi) / np.pi) ** 4 / 2
y = 2 * (x ** 2 - x) ** 2 * np.sin(p)
r = u * (x * np.sin(p) + y * np.cos(p))
surf = ax.plot_surface(r * np.cos(t), r * np.sin(t), u * (x * np.cos(p) - y * np.sin(p)), \
rstride=1, cstride=1, cmap=cm.gist_heat, linewidth=0, antialiased=True)
plt.title('给自己的小花花', fontproperties=font)
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
plt.show()