python简单练习

快速排序

请添加图片描述

import random

ls=[random.randint(1,100)for i in range(10)]
print(ls)
def quicksort(seq):
    if len(seq) < 1:
        return seq
    else:
        base = seq[0]
        left = [elem for elem in seq[1:] if elem < base]
        right = [elem for elem in seq[1:] if elem > base]
        return quicksort(left) + [base] + quicksort(right)
seq = ls
print("排序后:")
print(quicksort(seq))

冒泡排序

def bubble_sort(nums):

    for i in range(len(nums) - 1):  # 这个循环负责设置冒泡排序进行的次数
        for j in range(len(nums) - i - 1):   
            if nums[j] > nums[j + 1]:
                nums[j], nums[j + 1] = nums[j + 1], nums[j]

    return nums

起泡排序

请添加图片描述

import random

ls=[random.randint(1,100)for i in range(10)]
print(ls)
for i in range(len(ls) - 1):  # 这个循环负责设置冒泡排序进行的次数(比如说n个数,则只要进行n-1次冒泡,就可以把这个n个数排序好,对吧)
    for j in range(len(ls) - i - 1):
        if ls[j] > ls[j + 1]:
            ls[j], ls[j + 1] = ls[j + 1], ls[j]
print("排序后:")
print(ls)
    

顺序查找

def Sesearch(array,n):
    for i in range(len(array)):
        if array[i]==n:
            return i
    return False
array = [2,39,21,56,6,79,90]
print(Sesearch(array,21))

1加到100

a=1
sum=1
while a<100:
    a=a+1
    sum=sum+a
print(sum)
sum = 0
n = eval(input("请输入n的值:n="))
for a in range(n):
    sum = sum + (a+1)
print("sum=",sum)

键值对

d1={'name':'齐德隆','age':34,'place':'深圳'}
print(d1['name'],d1['age'],d1['place'])

词云

#GovRptWordCloudv1.py
import jieba
import wordcloud
f = open("新时代中国特色社会主义.txt", "r", encoding="utf-8")
t = f.read()
f.close()
ls = jieba.lcut(t)
txt = " ".join(ls)
w = wordcloud.WordCloud( \
        width = 1000, height = 700,\
        background_color = "white",
        font_path = "msyh.ttc"
        )
w.generate(txt)
w.to_file("grwordcloud123.png")
#GovRptWordCloudv2.py
import jieba
import wordcloud
from scipy.misc import imread
mask = imread("chinamap.jpg")
excludes = { }
f = open("新时代中国特色社会主义.txt", "r", encoding="utf-8")
t = f.read()
f.close()
ls = jieba.lcut(t)
txt = " ".join(ls)
w = wordcloud.WordCloud(\
    width = 1000, height = 700,\
    background_color = "white",
    font_path = "msyh.ttc", mask = mask
    )
w.generate(txt)
w.to_file("grwordcloudm.png")

效果
在这里插入图片描述

叠边九边形

#TwoRoundDraw.py
import turtle as t
t.pensize(2)
for i in range(9):
    t.fd(150)
    t.left(80)
t.done()

在这里插入图片描述

风车

#WindWheel.py
import turtle as t
t.pensize(2)
for i in range(4):
    t.seth(90*i)
    t.fd(150)
    t.right(90)
    t.circle(-150, 45)
    t.goto(0,0)
t.done()

在这里插入图片描述

霍兰德人格分析

#HollandRadarDraw
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family']='SimHei'
radar_labels = np.array(['研究型(I)','艺术型(A)','社会型(S)',\
                         '企业型(E)','常规型(C)','现实型(R)'])#雷达标签 nAttr = 6
data = np.array([[0.40, 0.32, 0.35, 0.30, 0.30, 0.88],
                 [0.85, 0.35, 0.30, 0.40, 0.40, 0.30],
                 [0.43, 0.89, 0.30, 0.28, 0.22, 0.30],
                 [0.30, 0.25, 0.48, 0.85, 0.45, 0.40],
                 [0.20, 0.38, 0.87, 0.45, 0.32, 0.28],
                 [0.34, 0.31, 0.38, 0.40, 0.92, 0.28]]) #数据值
data_labels = ('艺术家', '实验员', '工程师', '推销员', '社会工作者','记事员')
angles = np.linspace(0, 2*np.pi, nAttr, endpoint=False)
data = np.concatenate((data, [data[0]]))
angles = np.concatenate((angles, [angles[0]]))
fig = plt.figure(facecolor="white")
plt.subplot(111, polar=True)
plt.plot(angles,data,'o-', linewidth=1, alpha=0.2)
plt.fill(angles,data, alpha=0.25)
plt.thetagrids(angles*180/np.pi, radar_labels,frac = 1.2)
plt.figtext(0.52, 0.95, '霍兰德人格分析', ha='center', size=20)
legend = plt.legend(data_labels, loc=(0.94, 0.80), labelspacing=0.1)
plt.setp(legend.get_texts(), fontsize='large')
plt.grid(True)
plt.savefig('holland_radar.jpg')
plt.show()

数字转换

temp = "零一二三四五六七八九"
s = input()
for c in s:
    print(temp[eval(c)],end = "")

天天向上

天天向上1

#DayDayUpQ1.py
dayup = pow(1.001, 365)
daydown = pow(0.999, 365)
print("向上:{:.2f},向下:{:.2f}".format(dayup, daydown))

天天向上2

#DayDayUpQ2.py
dayfactor = 0.005
dayup = pow(1+dayfactor, 365)
daydown = pow(1-dayfactor, 365)
print("向上:{:.2f},向下:{:.2f}".format(dayup, daydown))

天天向上3

#DayDayUpQ3.py
dayup = 1.0
dayfactor = 0.01
for i in range(365):
    if i % 7 in [6,0]:
        dayup = dayup*(1-dayfactor)
    else:
        dayup = dayup*(1+dayfactor)
print("工作日的力量:{:.2f} ".format(dayup))

天天向上4

#DayDayUpQ4.py
def dayUP(df):
    dayup = 1
    for i in range(365):
        if i % 7 in [6,0]:
            dayup = dayup*(1 - 0.01)
        else:
            dayup = dayup*(1 + df)
    return dayup
dayfactor = 0.01
while dayUP(dayfactor) < 37.78:
    dayfactor += 0.001
print("工作日的努力参数是:{:.3f} ".format(dayfactor))

文本进度条

文本进度条 简单的开始

#TextProBarV1.py
import time
scale = 10
print("------执行开始------")
for i in range(scale+1):
    a = '*' * i
    b = '.' * (scale - i)
    c = (i/scale)*100
    print("{:^3.0f}%[{}->{}]".format(c,a,b))
    time.sleep(0.1)
print("------执行结束------")

文本进度条 单行动态刷新

#TextProBarV2.py
import time
for i in range(101):
    print("\r{:3}%".format(i), end="")
    time.sleep(0.1)

文本进度条 实例完整效果

#TextProBarV3.py
import time
scale = 50
print("执行开始".center(scale//2, "-"))
start = time.perf_counter()
for i in range(scale+1):
    a = '*' * i
    b = '.' * (scale - i)
    c = (i/scale)*100
    dur = time.perf_counter() - start
    print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,dur),end='')
    time.sleep(0.1)
    print("\n"+"执行结束".center(scale//2,'-'))

绘制图像

笑脸绘制

#PythonDraw.py
import turtle
turtle.setup(650, 650, 100, 100)
turtle.penup()
turtle.fd(-300)
turtle.pendown()
turtle.pensize(25)
turtle.pencolor("yellow")
turtle.seth(-90)
turtle.circle(300)

turtle.penup()
turtle.goto(-100,200)
turtle.pendown()
turtle.pencolor("black")
#m
turtle.seth(130)
turtle.circle(100, 80)

turtle.penup()
turtle.goto(50,200)
turtle.pendown()

turtle.seth(360-130)
turtle.circle(100, -80)
#y
turtle.penup()
turtle.goto(-150,150)
turtle.pendown()

turtle.pensize(5)
turtle.seth(90)
turtle.circle(10)

turtle.penup()
turtle.goto(50,150)
turtle.pendown()

turtle.seth(90)
turtle.circle(10)
#z
turtle.penup()
turtle.goto(-200,50)
turtle.pendown()
turtle.pensize(10)

turtle.seth(0)
turtle.fd(300)
turtle.left(90)
turtle.circle(150,-180)

turtle.penup()
turtle.goto(-180,50)
turtle.pendown()
turtle.pensize(5)
turtle.fd(75)

turtle.penup()
turtle.goto(-160,50)
turtle.pendown()
turtle.fd(95)

turtle.penup()
turtle.goto(-130,50)
turtle.pendown()
turtle.fd(120)

turtle.penup()
turtle.goto(-100,50)
turtle.pendown()
turtle.fd(140)

turtle.penup()
turtle.goto(-70,50)
turtle.pendown()
turtle.fd(150)

turtle.penup()
turtle.goto(-40,50)
turtle.pendown()
turtle.fd(150)

turtle.penup()
turtle.goto(-10,50)
turtle.pendown()
turtle.fd(145)

turtle.penup()
turtle.goto(20,50)
turtle.pendown()
turtle.fd(127)

turtle.penup()
turtle.goto(50,50)
turtle.pendown()
turtle.fd(105)

turtle.penup()
turtle.goto(80,50)
turtle.pendown()
turtle.fd(75)

turtle.pensize(3)
turtle.penup()
turtle.goto(230,210)
turtle.pendown()
turtle.fd(165)

turtle.penup()
turtle.goto(250,200)
turtle.pendown()
turtle.fd(145)

turtle.penup()
turtle.goto(270,195)
turtle.pendown()
turtle.fd(145)

turtle.done()

在这里插入图片描述

多值输入

number,name=eval(input("请输入学号和姓名【逗号隔开】:"))
Temp=input("请输入:")
if Temp in "number":
    print(name)
elif Temp in "name":
    print(number)

圆周率计算

公式法

#CalPiV1.py
pi = 0
N = 100
for k in range(N):
    pi += 1/pow(16,k)*(4/(8*k+1) - 2/(8*k+4) - 1/(8*k+5) - 1/(8*k+6) )
print("圆周率值是: {}".format(pi))

蒙特卡罗方法

#CalPiV2.py
from random import random
from time import perf_counter
DARTS = 1000*1000
hits = 0.0
start = perf_counter()
for i in range(1, DARTS+1):
    x, y = random(), random()
    dist = pow(x ** 2 + y ** 2, 0.5)
    if dist <= 1.0:
        hits = hits + 1
pi = 4 * (hits/DARTS)
print("圆周率值是: {}".format(pi))
print("运行时间是: {:.5f}s".format(perf_counter() - start))

自动轨迹绘制

#AutoTraceDraw.py
import turtle as t
t.title('自动轨迹绘制')
t.setup(800, 600, 0, 0)
t.pencolor("red")
t.pensize(5)
#数据读取
datals = []
f = open("data.txt")
for line in f:
    line = line.replace("\n","")
    datals.append(list(map(eval, line.split(","))))
f.close()
#自动绘制
for i in range(len(datals)):
    t.pencolor(datals[i][3],datals[i][4],datals[i][5])
    t.fd(datals[i][0])
    if datals[i][1]:
        t.rt(datals[i][2])
    else:
        t.lt(datals[i][2])

在这里插入图片描述

BMI

#CalBMIv1.py
height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
bmi = weight / pow(height, 2)
print("BMI 数值为:{:.2f}".format(bmi))
who = ""
if bmi < 18.5:
    who = "偏瘦"
elif 18.5 <= bmi < 25:
    who = "正常"
elif 25 <= bmi < 30:
    who = "偏胖"
else:
    who = "肥胖"
print("BMI 指标为:国际'{0}'".format(who))
#CalBMIv2.py
height, weight = eval(input("请输入身高(米)和体重\(公斤)[逗号隔开]: "))
bmi = weight / pow(height, 2)
print("BMI 数值为:{:.2f}".format(bmi))
nat = ""
if bmi < 18.5:
    nat = "偏瘦"
elif 18.5 <= bmi < 24:
    nat = "正常"
elif 24 <= bmi < 28:
    nat = "偏胖"
else:
    nat = "肥胖"
print("BMI 指标为:国内'{0}'".format(nat))

(国际、国内)

#CalBMIv3.py
height, weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]: "))
bmi = weight / pow(height, 2)
print("BMI 数值为:{:.2f}".format(bmi))
who, nat = "", ""
if bmi < 18.5:
    who, nat = "偏瘦", "偏瘦"
elif 18.5 <= bmi < 24:
    who, nat = "正常", "正常"
elif 24 <= bmi < 25:
    who, nat = "正常", "偏胖"
elif 25 <= bmi < 28:
    who, nat = "偏胖", "偏胖"
elif 28 <= bmi < 30:
    who, nat = "偏胖", "肥胖"
else:
    who, nat = "肥胖", "肥胖"
print("BMI 指标为:国际'{0}', 国内'{1}'".format(who, nat))

计算圆面积

#CalCircle.py
r = 25
area = 3.1415*r*r
print(area)
print("{:.2f}".format(area))

jieba测试

import jieba
a=jieba.lcut("中国是一个伟大的国家")
print(a)

M OP N

TempStr = input()
print('{:.2f}'.format(eval(TempStr)))

python蟒蛇绘制

#PythonDraw.py
import turtle
turtle.setup(650, 350, 200, 200)
turtle.penup()
turtle.fd(-250)
turtle.pendown()
turtle.pensize(25)
turtle.pencolor("purple")
turtle.seth(-40)
for i in range(4):
    turtle.circle(40, 80)
    turtle.circle(-40, 80)
turtle.circle(40, 80/2)
turtle.fd(40)
turtle.circle(16, 180)
turtle.fd(40 * 2/3)
turtle.done()

在这里插入图片描述

python循环测试

for c in "Python123":
    print(c,end=" ")

RMB,USD互转

a = input()
if a[0:3] == "RMB":
    U = (eval(a[3:]))/6.78
    print("USD{:.2f}".format(U))
elif a[0:3] == "USD":
    R = (eval(a[3:]))*6.78
    print("RMB{:.2f}".format(R))

starDraw

from turtle import *
color('yellow','red')
begin_fill()
for i in range(5):
    fd(300)
    rt(144)
end_fill()
done()

在这里插入图片描述

查找

students = [
  {'number': '1', 'name': '小明'},
  {'number': '2', 'name': '小红'},
  {'number': '3', 'name': '小张'},
  {'number': '4', 'name': '小刘'},
]
print(students)

while True:
  oper1 = input('输入操作(1按学号查找,2按姓名查找,0退出):')

  selected_students = []
  if oper1 == '1':
    number_str = input('请输入查找的学号:')
    print('number_str', number_str)
    for student in students:
      if student['number'] == number_str: 
        selected_students.append(student)
    if len(selected_students) > 0:
      print(selected_students)
    else:
      print('没有符合条件的学生')
  elif oper1 == '2':
    name_str = input('请输入查找的姓名:')
    print('name_str', name_str)
    for student in students:
      if student['name'] == name_str: 
        selected_students.append(student)

    if len(selected_students) > 0:
      print(selected_students)
    else:
      print('没有符合条件的学生')
  elif oper1 == '0':
    print('退出')
    break
  else:
    print('您的输入不对,请重新输入')
    continue

同切圆绘制

import turtle
turtle.pensize(2)
turtle.circle(10)
turtle.circle(40)
turtle.circle(80)

温度转换

#TempConvert.py
TempStr = input("请输入带有符号的温度值: ")
if TempStr[-1] in ['F', 'f']:
    C = (eval(TempStr[0:-1]) - 32)/1.8
    print("转换后的温度是{:.2f}C".format(C))
elif TempStr[-1] in ['C', 'c']:
    F = 1.8*eval(TempStr[0:-1]) + 32
    print("转换后的温度是{:.2f}F".format(F))
else:
    print("输入格式错误")
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值