python基础(16)算法练习
算法练习
冒泡排序法
普通的冒泡排序:
listToSort=[32,1,56,34,89,56]
def bubbleSort(listToSort):
for i in range(len(listToSort)-1):
for j in range(len(listToSort)-i-1):
if listToSort[j]>listToSort[j+1]:
tem=listToSort[j]
listToSort[j]=listToSort[j+1]
listToSort[j+1]=tem
return listToSort
print(bubbleSort(listToSort))
优化版本1:添加是否排序好的标志(新的一轮排序是否需要交换位置)
listToSort=[32,1,56,34,89,56]
def bubbleSort(listToSort):
for i in range(len(listToSort)-1):
sortedFlag=False
for j in range(len(listToSort)-i-1):
if listToSort[j]>listToSort[j+1]:
tem=listToSort[j]
listToSort[j]=listToSort[j+1]
listToSort[j+1]=tem
sortedFlag=True
if not sortedFlag:
break
return listToSort
print(bubbleSort(listToSort))
优化版本2:换成双向排序(考虑到最大值和最小值分别在两端的情况)
listToSort=[32,1,56,34,89,56]
def bubbleSort(listToSort):
for i in range(len(listToSort)-1):
sortedFlag=False
for j in range(len(listToSort)-i-1):
if listToSort[j]>listToSort[j+1]:
tem=listToSort[j]
listToSort[j]=listToSort[j+1]
listToSort[j+1]=tem
sortedFlag=True
if sortedFlag:
sortedFlag=False
for j in range(len(listToSort)-i-2,0,-1):
if listToSort[j]<listToSort[j-1]:
tem2=listToSort[j]
listToSort[j]=listToSort[j-1]
listToSort[j-1]=tem2
sortedFlag=True
if not sortedFlag:
break
return listToSort
print(bubbleSort(listToSort))
九九乘法表
for i in range(1,10,1):
for j in range(1,10,1):
if i>=j:
print(str(i)+"*"+str(j)+"="+str(i*j),end="\t")
if i==j:
print("\n")
运行结果为:
函数封装练习
def userN(): #获取用户输入的账号和密码
username=input("请输入账号:\n")
password=input("请输入密码:\n")
return username,password
def register():
username,password=userN()
temp=username+"|"+password
with open(r'E:\python_projects\python_project1\source\userPassword.txt','w') as f:
f.write(temp)
def getNick():
with open(r'E:\python_projects\python_project1\source\userPassword.txt','r') as f:
userInfo=f.read().split("|")
print("欢迎来到您的主页,{}".format(userInfo[0]))
def login():
username,password=userN()
with open(r'E:\python_projects\python_project1\source\userPassword.txt') as f:
userInfo=f.read().split("|")
if userInfo[0]==username and userInfo[1]==password:
print("登录成功了")
getNick()
elif userInfo[0] != username and userInfo[1] == password:
print("账号密码错误")
elif userInfo[0]==username and userInfo[1]!=password:
print("还是账号面错误")
else:
print("你输的都是什么东西")
def exitSys():
import sys
print("您已经退出登录了,欢迎下次光临")
sys.exit(1)
def main():
while True:
put=int(input("请选择:1.注册2.登录3.退出"))
if put==1:
register()
elif put==2:
login()
elif put==3:
exitSys()
else:
print("不要输入哪些乱七八糟的")
continue
if __name__=='__main__':
main()
运行后的效果: