友情提示:将下文中代码拷贝到JupyterNotebook中直接执行即可,部分代码需要连续执行。
1.注释就是对代码的解释和说明,其目的是让人们能够更加轻松地了解代码。
2.注释是编写程序时,写程序的人给一个语句、程序段、函数等的解释或提示,能提高程序代码的可读性。
3.在有处理逻辑的代码中,源程序有效注释量必须在20%以上。
print("hello everyone!") #向大家打招呼
hello everyone!
'''
这是使用三个单引号的多行注释
这是第二行
这是第三行
'''
'n这是使用三个单引号的多行注释n这是第二行n这是第三行n'
"""
这是使用三个双引号的多行注释
"""
'n这是使用三个双引号的多行注释n'
在函数体的第一行使用一对三个单引号 ‘’’ 或者一对三个双引号 “”" 来定义文档字符串。你可以使用 doc(注意双下划线)调用函数中的文档字符串属性。
编写示例如下:
def addfun(num1,num2):""" 完成传入的两个数之和:param num1: 加数1:param num2: 加数2:return: 求两个数的和"""return num1 + num2print( addfun.__doc__ )
完成传入的两个数之和:param num1: 加数1:param num2: 加数2:return: 求两个数的和
文档注释常用关键字:
①Parameters为函数传入参数
②Returns为函数返回结果
③Raises为函数可能会有的报错信息
“”"
This is a reST style.
:param param1: this is a first param
:param param2: this is a second param
:returns: this is a description of what is returned
:raises keyError: raises an exception
“”"
“”"
This is a groups style docs.
Parameters:
param1 - this is the first param
param2 - this is a second param
Returns:
This is a description of what is returned
Raises:
KeyError - raises an exception
“”"
“”"
My numpydoc description of a kind
of very exhautive numpydoc format docstring.
first : array_like
the 1st param name first
second :
the 2nd param
third : {‘value’, ‘other’}, optional
the 3rd param, by default ‘value’
string
a value in a string
KeyError
when a key error
OtherError
when an other error
“”"
算法思路:
我们设计一个变量flag,当它为0时,做+法并设置为1,当他为1时,做-法并设置为0,反复循环形成+ - + - + -…
通过i%2有余数,求出奇数,得出1/i
pi=0
flag=0
for i in range(1,1000000):if i%2: #有余数 Trueif flag == 0:pi += 1/iflag=1else:pi -= 1/iflag=0
print(pi*4)
3.141590653589692
算法思路:
在程序中trys 变量为我们尝试的次数,次数越多,越精确
hits 变量为命中数量
x = -1+2 * random()表明x轴在-1到1之间;y = -1+2 * random()表明y轴在-1到1之间
x ** 2 + y ** 2 <=1 表明击中⚪内
from random import random
trys =800000
hits =0
for i in range(trys):x = -1+2*random()y = -1+2*random()if x**2 + y**2 <=1:hits+=1
print("Estimate for pi={}".format(4*hits/trys))
Estimate for pi=3.140415
①x>1,求x的平方根y,0<y<x,low为0,high为x
②假设 guess是(low+high)/2,如果guess的平方非常接近x,那么y=guess
③若 g u e s s 2 guess^2 guess2<x,low设定为guess,然后重复第二步
④若 g u e s s 2 guess^2 guess2>x,high设定为guess,然后重复第二步
在程序中,trys为迭代次数,次数越多,越精准。
trys =10000
x =int(input("请输入需要求平方根的数字>>>n"))
low,high=0,x
for i in range(trys):guess = (low+high)/2if guess**2 < x:low = guesselse:high = guess
print(guess)
请输入需要求平方根的数字>>>
5
2.23606797749979
①295481 259481 254981 254891 254819
②254819 245819 245189
③245189 241589
④241589 214589
⑤124589
import random #冒泡排序
def bubbleSort(list:"需要排序的数组")->"输出排好序的数组":for i in range(1,len(list)):for j in range(0,len(list)-i):if list[j] > list[j+1]:list[j],list[j+1]=list[j+1],list[j]return list
bubbleSort(random.sample(range(0,100),8))
[32, 40, 42, 69, 80, 86, 91, 96]
①295481 Current=9
②295481 >>259481 Current=5
③259481 >>245981 Current=4
④245981 >>245891 Current=8
⑤245891 >>124589 Current=1
def insertionSort(list:list)->"sortedlist":for i in range(1,len(list)):current =list[i]k= i-1 #从左边第一个开始循环while k>=0 and list[k] > current: #左边大于current值时,向右移一位,直到不大于currentlist[k+1] = list[k]k-=1list[k+1] = current #把current相应的位置赋值currentreturn list
insertionSort([3,7,10,5,8,12,4,6])
[3, 4, 5, 6, 7, 8, 10, 12]
295481672954 816729 54 81 67
2 9 5 4 8 1 6 729 45 18 672459 167812456789
64 log n32 32 O(n)16 16 O(n)8 8 O(n)
import random
def mergeSort(list):n = len(list)#获取长度if n <=1:#如果列表长度1,直接返回return listmid = n//2 #取中间值,把数组拆分left = mergeSort(list[:mid])#取左半部分right = mergeSort(list[mid:])#取右半部分leftp = 0 #左半指针从0开始rightp = 0 #右半指针从0开始result =[]#定义空数组存储每次归并好的列表while leftp < len(left) and rightp < len(right):#当左右指针分别小于长度时if left[leftp] <= right[rightp]:result.append(left[leftp])leftp +=1else:result.append(right[rightp])rightp +=1result += left[leftp:]#考虑数组为奇数,把最后元素添加进来result += right[rightp:]return result
mergeSort(random.sample(range(0,100),20))
[0, 4, 8, 14, 16, 24, 35, 38, 49, 56, 62, 68, 75, 77, 78, 81, 87, 88, 89, 97]
128 Merge64 64 Merge32 32 Merge16 16 Insertion
def square(x):return x*x
square(100)
10000
def findmax(list):max = list[0]for i in range(1,len(list)):if list[i] > max:max = list[i]return max
findmax([1,4,0,8,4,9,3])
9
def findduplicate(list):dupli=[]for i in range(len(list)):for j in range(i+1,len(list)):if list[i] == list[j]:dupli.append(list[i])breakreturn dupli
findduplicate([1,3,5,7,9,2,3,6,8,0,7])
[3, 7]
二分法查找思路:
进阶提示:
二分法查找需要先对数组进行排序。
def binarySearch(list,value):low=0high=len(list)while(low <= high):mid = (low + high) // 2if (list[mid]==value):return midelif (value > list[mid]):low = mid + 1else:high = mid - 1return -1
print(binarySearch([1,2,3,4,5,6,7],5))
4
您的代码:
您的代码:
[0,2,6,12,20,30,42…]
您的代码:
您的代码:
tips:函数运行时间可以使用下列函数
def timer(f):def _f(*args):t0=time.time()f(*args)return time.time()-t0return _f
您的代码:
rate=5.00
balance =10000.00
bal_list = []
for year in range(1,21):balance += balance*rate/100print("%4d %10.2f" %(year,balance))bal_list.append(balance)
1 10500.002 11025.003 11576.254 12155.065 12762.826 13400.967 14071.008 14774.559 15513.2810 16288.9511 17103.3912 17958.5613 18856.4914 19799.3215 20789.2816 21828.7517 22920.1818 24066.1919 25269.5020 26532.98
import matplotlib.pyplot as plt
fig,ax =plt.subplots()
ax.plot([i for i in range(1,21)],bal_list)
ax.set(xlabel="n th year",ylabel="Money",title="How much I got")
ax.grid()
plt.show()
import pyinputplus as pi
age = pi.inputInt("Please enter age:",min=0,max=110,limit=2)
gender = pi.inputChoice(['Male','Female'],timeout=10)
print("age={} gender={}".format(age,gender))
Please enter age:20
Please select one of: Male, Female
Male
age=20 gender=Male
menu_dict={"1.主食":{"1.面条":6,"2.米饭":2,"3.抄手":8,"4.馒头":1},"2.饮料":{"1.芬达":3,"2.无糖可乐":4,"3.面汤":1,"4.酸梅汁":2},"3.小吃":{"1.甩饼":4,"2.糍粑":7,"3.小油条":8,"4.金银馒头":6},
}
menu_dict={"1.主食":{"1.面条":6,"2.米饭":2,"3.抄手":8,"4.馒头":1},"2.饮料":{"1.芬达":3,"2.无糖可乐":4,"3.面汤":1,"4.酸梅汁":2},"3.小吃":{"1.甩饼":4,"2.糍粑":7,"3.小油条":8,"4.金银馒头":6},
}
for k,v in menu_dict.items():print("{}".center(20,"-").format(k))for k1,v1 in v.items():print("{}".ljust(6," ").format(k1),"价格:{}".rjust(de("GBK"))," ").format(v1))
---------1.主食---------
1.面条 价格:6
2.米饭 价格:2
3.抄手 价格:8
4.馒头 价格:1
---------2.饮料---------
1.芬达 价格:3
2.无糖可乐 价格:4
3.面汤 价格:1
4.酸梅汁 价格:2
---------3.小吃---------
1.甩饼 价格:4
2.糍粑 价格:7
3.小油条 价格:8
4.金银馒头 价格:6
correct_answers = "adbdcacbda"
correct_list = list(correct_answers)
done =False
while not done:user_answers = input("Enter your exam answers!n>>>")if len(user_answers)== len(correct_answers):user_list =list(user_answers)done = Trueelse:print("length is not equal")
judge_list= list(map(lambda user,corr:"Y" if user ==corr else "X",user_list,correct_list))
judge_dict={i: unt(i)for i in set(judge_list)}
total= judge_dict["Y"]*10
print("user_answers={}njudgement={}nfinallytotal={}".format(judge_list,judge_dict,total))
Enter your exam answers!
>>>abbdaccdda
user_answers=['Y', 'X', 'Y', 'Y', 'X', 'X', 'Y', 'X', 'Y', 'Y']
judgement={'X': 4, 'Y': 6}
finallytotal=60
本文发布于:2024-01-31 02:54:12,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170664085524820.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |