Python algorithm
Lukeclever ComputerSavvyMedic
It has been 0 days since the last update of this article. Some contents may be outdated. Please pay attention to screening.

本站之前有多篇文章是介绍不同python的函数,现将这些文章整合一下。

素数判断函数

1
2
3
4
5
6
7
def IsPrime(n):
if n<2:
return False
for i in range(2,n):
if n % i==0:
return False
return True

计算每位数的阶乘的函数

1
2
3
4
5
6
7
8
9
def Factorial(n):
sum1 = 0
for i in str(n):
i = int(i)
fact = 1
for j in range(2,i+1):
fact *= j
sum1 += fact
return sum1

寻找互质数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
for m in range(100,1000):
guam = m
nstr = str(m)
n = nstr[::-1]
if n[0] == '0':
continue
else:
n=eval(n)
guan = n
r = m%n
while r!= 0:
m=n
n=r
r=m%n
if n == 1:
print('{}与{}互质'.format(guam,guan))

找出规定范围内每位数都是素数的数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
for n in range(100,1000):   
nstr=str(n)
for s in nstr:
ints=eval(s)
if ints<2:
break
for i in range(2,ints):
if ints%i==0:
flag=False
break
else:
flag=True
if not flag:
break
else:
print(n)

寻找范围内的完数

1
2
3
4
5
6
7
8
9
for n in range(10,10000):
st=""
sum1=0
for i in range(1,n):
if n%i==0:
st=st+str(i)+"+"
sum1+=i
if sum1==n:
print("{}={}".format(n,st[:-1]))

最小公倍数

1
2
3
4
5
6
7
8
9
m = int(input("Please input the first num:"))
n = int(input("Please in put the second num:"))
p = m*n
r = m%n
while r != 0:
m = n
n = r
r = m % n
print(p//n)

寻找4位降序数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import random
ls=[]
for i in range(30):
x=random.randint(1000,9999)
ls.append(x)
print(ls)
count=0
for t in ls:
s=str(t)
for j in range(len(s)-1):
if s[j]<=s[j+1]:
break
else:
print(s)
count+=1
if count==0:
print("无降序数")

实现读取json文件功能的部分函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import os

def ReadJson(fn):
retL = []
f = open(fn, encoding = 'utf-8')
for line in f:
retL.append(eval(line.strip())[0])
f.close()
return retL

def ReadFiles(fp):
retAll = []
files = os.listdir(fp)
for file in files:
fa = fp + '\\' + file
retT = ReadJson(fa)
retAll += retT
return retAll

获取Json字典中值数量最多的项目

1
2
3
4
5
6
7
8
9
def getContent(key):
comL = []
for item in ret:
commentcnt = int(item[key])
content = item['sth']
comL.append((key,sth))
comL.sort(key = lambda x:x[0], reverse = True)
return comL
maxCount = comL[0][0]

直角坐标系两点求距离

1
2
3
4
5
6
7
8
print("A、B两点坐标分别为A(x1,y1)、B(x2,y2)")
a=input("请输入x1:")
b=input("请输入y1:")
c=input("请输入x2:")
d=input("请输入y2:")
print("A和B两点之间的距离为:",end=" ")
print(round(pow(pow(eval(a)-eval(c),2)+pow(eval(b)-eval(d),2),0.5),1))
#上述式子由平面直角坐标系距离公式写出

通过if-elif-else计算税

1
2
3
4
5
6
7
8
9
10
11
12
income = eval(input('请输入月收入:'))
if income <= 2000:
tax = 0
elif income > 2000 and income <=3000:
tax = ( income - 2000 ) * 0.05
elif income > 3000 and income <=4000:
tax = ( income - 3000 ) * 0.15 + 50
elif income > 4000 and income <=5000:
tax = ( income - 4000 ) * 0.25 + 200
else:
tax = ( income - 5000 ) * 0.35 + 450
print('月收入{:.2f},调节税为{:.2f}'.format(income,tax))

生成指定项数的斐波拉契数列

1
2
3
4
5
6
7
8
9
10
11
12
list0 = [1,1]
terms = eval(input('斐波拉契数列的项数:'))
for i in range(terms-2):
list0.append(list0[-2]+list0[-1])
print(list0)
for t in range(2,terms-1): #t表示index
num = list0[t] #num为从列表中取出的数
for k in range(2,t): #k表示可能的因数
if num%k == 0:
break
else:
print(num)

将分钟转化为X小时X分钟

1
2
3
4
5
6
7
8
9
min_time = eval(input('please input you num(minute):\n'))
hour = 0
while True:
if min_time >= 60 :
min_time -= 60
hour += 1
else:
break
print('{}hours and {}minutes'.format(hour,min_time))

try-except-finally

1
2
3
4
5
6
7
try:
try_suite #监控这里的异常
except Exception:
except_suite #异常处理代码
else:
finally:
finally_suite #无论如何都执行

若有一个else,至少有一个except

format方法

1
2
3
4
5
6
7
list1=[1,2,3,4]             #stuid
list2=[98,67,89,80] #c-score
list3=[100,90,83,62] #m-score
list4=[90,98,100,82] #e-score
stuid=input("请输入学生的学号:")
listid=eval(stuid)-1 #index
print("该学生成绩为语文{0},数学{1},英语{2},总分{3}。".format(list2[listid],list3[listid],list4[listid],list2[listid]+list3[listid]+list4[listid]))

if-else实现注册功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
##operation:1register 2login 3changepwd 4logout
##在break之前为mode赋值实现切换功能
prompt = "Select the appropriate operation: 1:register 2:login 3:change-password 4:exit\n"
users = {}
mode = 0
while True:
if mode == 0:
print("We will use the 'num-' -like form to indicate what you are doing.")
mode = input(prompt)
elif mode == "1":
while True:
user = input("1-The user will now continue to be created.\n1-Type # to end.\n\n1-Please input your username.\n")
if user == "#":
mode = 0 ##程序初始化
break
pwd = input("1-Please input your password now.\n")
while True:
if user == pwd:
print("1-Password is too weak!")
pwd = input("1-Please input your password now.\n") ##密码强度检查
else:
break
if user not in users:
users[user] = pwd
else:
print("1-@@@Alert!The user already exists!")
elif mode == "2":
while True:
user = input("2-Please input your username.\n2-Type # to end.\n")
if user == "#":
mode = 0 ##初始化
break
if user in users:
pwd = input("2-Please input your password now.\n")
if users[user] == pwd:
print("2-Login successfully!")
else:
print("2-Wrong password provided!")
else:
mode = input("2-The user does not exist.\n2-Enter the function number provided before to switch to another function.\n")
break ##实现功能跳转。
break
elif mode == "3":
while True:
user = input("3-Please input your username.\n3-Type # to end.\n")
if user == "#":
mode = 0 ##初始化
break
if user in users:
pwd = input("3-Please input your original password now.\n")
if users[user] == pwd:
pwd1 = input("3-Correct password!\n3-Now please input the new password.\n")
while pwd1 == pwd:
pwd1 = input("3-The password is the same as the old one. Please re-enter it.\n")
if pwd1 == input("3-Please input your new password again!\n"):
users[user] = pwd1
print("3-Password updated successfully!")
else:
print("3-Wrong password provided!")
else:
mode = input("3-The user does not exist.\n3-Enter the function number provided before to switch to another function.\n")
break ##实现功能跳转。
break
else:
break

获取hitokoto的api内容并且将其保存至HTML文件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import time
import requests
start_num = eval(input('define start_num:\n'))
file_name = str(start_num) + '.html'
while True:
stapi = requests.get('https://v1.hitokoto.cn/?encode=text')
if stapi.text == '' :
break
## saying = str(input('define saying for {}.html:\n'.format(start_num)))
## if saying == '' :
## print('Empty!Empty!Empty!')
## saying = str(input('define saying for {}.html:\n'.format(start_num)))
#file_process-start
f = open( 'D:\stapi\%s.html' % (start_num,) , 'x' , encoding='utf-8' )
## f.write( '%s' % (saying,) )
f.write( stapi.text )
f.close()
#file_process-end
## print('success!{}.html:{}'.format(start_num,saying))
print('success!{}.html:{}'.format(start_num,stapi.text))
start_num += 1
time.sleep(1)

format用法指南

<模板字符串>.format(<逗号分隔的参数>)

"I'm {}, I'm {} years old.".format('Tom','five')

在模板字符串中,大括号内有如下方法:{<参数序号>:<格式控制标记>}如模板字符串中有多个{},且{}中没指定序号,按出现顺序对应参数。格式控制标记顺序:<填充><对齐><宽度><,><.精度><类型>等六个字段

<填充>:修改默认填充字符。

<对齐>:<左对齐,>右对齐,^居中对齐。

<宽度>:输出字符宽度。如实际位数小于指定宽度,默认以空格补充。反之,则按实际位数输出。

<,>:用于显示数字类型的千位分隔符。

<.精度>:对于浮点数,精度表示小数部分的有效位数;对于字符串,精度表示输出的最大长度,如果实际长度大于精度,仍输出精度指定的长度。

<类型>:表示输出整数和浮点数的格式规则。

1.对于整数类型,输出格式主要包括:b(二进制),d(十进制),o(八进制),x(小写十六进制),X(大写十六进制)等。

2.对于浮点数类型,输出格式包括:e(小写e指数形式),E(大写E指数形式),f(标准浮点形式),%(百分比)。

附:format语法PDF

报错解释

SyntaxError:解释器语法错误
NameError:尝试访问一个未申明的变量
TypeError 数据类型不匹配
KeyError:请求一个不存在的字典关键字
IOError:输入输出错误(打开的文件不存在)
AttributeError: 尝试访问未知的对象属性
KeyError不存在字典关键字
ZeroDivisionError:除数为零
FileNotFoundError打开文件不存在
IndexError:请求的索引超过序列范围

 Comments
Comment plugin failed to load
Loading comment plugin