1.通讯录
number={
'hushiruo':'1234567',
'huangyujie':'87654321',
'xueqing':'66666666'
}
2.平方
a_list = [1,2,3,4,5]
squared_list = [0 for i in range(5)]
for i in range(5):
squared_list[i] = a_list[i]**2
print(squared_list)
[1, 4, 9, 16, 25]
3.类
class cat:
#属性
color = ''
jump = 0
#构造
def __init__(self, c, j):
self.color = c
self.jump = j
cc = cat('red',2)
print(cc.color)
print(cc.jump)
red
2
4.函数式
item = [1,2,3]
squared = list(map(lambda x: x**2, item))
print(squared)
[1, 4, 9]
5.一元二次方程
import math
def solve_equ(b,c):
val1 = b/2.0
val2 = val1**2
val3 = val2+c
val4 = math.sqrt(val3)
root1 = val4-val1
root2 = -val4-val1
return root1,root2
print(solve_equ(10,39))
(3.0, -13.0)
6.PI
import random
import math
def draw(inner_points,outer_points):
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(5, 5))
inner_x = [x[0] for x in inner_points]
inner_y = [x[1] for x in inner_points]
outer_x = [x[0] for x in outer_points]
outer_y = [x[1] for x in outer_points]
ax.scatter(inner_x, inner_y, color="r",s=1)
ax.scatter(outer_x, outer_y, color="g",s=1)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
import numpy as np
theta = np.linspace(0, 2*np.pi, 100)
r = 1
x1 = r*np.cos(theta)
x2 = r*np.sin(theta)
ax.plot(x1, x2,color='black')
plt.show()
def MonPi(number):
N2 = number
N1 = 0.
inner_points = []
outer_points = []
for i in range(N2):
x = random.random()
y = random.random()
if x*x+y*y<=1:
N1+=1
inner_points.append([x,y])
else:
outer_points.append([x,y])
print("Monte PI:",4*N1/N2)
draw(inner_points,outer_points)
def TaylorPi(k):
sum,odd = 0,True
for i in range(1,k):
sum += 1/(2*i-1) if odd==True else -1/(2*i-1)
odd = not odd
print("Taylor PI:",sum*4)
MonPi(30000)
TaylorPi(100000)
Monte PI: 3.138933333333333
Taylor PI: 3.1416026536897204
7.画图
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0, 3*np.pi, 0.1)
s = np.sin(t)
c = np.cos(t)
plt.subplot(2,1,1)
plt.plot(t,s)
plt.title('Sine')
plt.subplot(2,1,2)
plt.plot(t,c)
plt.title('Cosine')
plt.show()
8.GUI
from tkinter import *