目录标题
1,计算数字的阶乘
def get_jiecheng(number):
result = number
while number > 1:
result *= number - 1
number -= 1
return result
print('阶乘6=', get_jiecheng(6))
2,区间内的所有素数
素数:只能整除1和自身
思路:一个函数判断是否素数,再一个循环区间里的数
def is_prime(num):
if num in (1,2): #特殊情况记得考虑
return True
for i in range(2,num):
if num%i == 0:
return True
return False #return的用法
def print_primes(begin,end):
for i in range(begin,end+1):
if is_prime(i) == 0:
print(i)
begin =3
end = 7
print_primes(3,7)
特殊情况记得考虑
return的用法
3,求前n个数字的平方和
输入n,输出:1平方+2平方+3平方+。。。n平方
c = int(input('请输入:'))
s = 0
for i in range(1,c+1):
s += i*i
print(s)
输入的数字记得转换为int类型
4,移除列表中的多个元素
remove函数
def yichu(la,lb):
for i in la:
if i in lb:
la.remove(i)
return la
la = [3,7,5,9,11]
lb= [7,11]
print(f"from{la}中remove{lb}:",yichu(la,lb))
有一个更简单的
la = [3,7,5,9,11]
lb= [7,11]
data = [i fro i in la if i not in lb]
print(f"from{la}中remove{lb}:",data)
5,列表去重
利用set
lista = [1,3,5,2,3,1]
print('liat(set(lista))')
6,对简单列表元素排序
原列表改变了:
la = [2,4,5,3,7]
la.sort() #升序
print(la)
原列表不改变:
la = [2,4,5,3,7]
lb = sorted(la)
print(lb)
降序:加一个reverse=True
la = [2,4,5,3,7]
la.sort(reverse=True) #降序
print(la)
la = [2,4,5,3,7]
lb = sorted(reverse=True) #降序
print(lb)
7,对复杂列表元素排序
对学生成绩排序。
依旧sort函数,加一个key参数
sort(要排序的东西,key=排序列,reverse=True)#降序
students = [
{'id':1,'name':'小a','grade':88},
{'id':2,'name':'小b','grade':98},
{'id':3,'name':'小c','grade':78}
]
students_sort = sorted(students,key=lambda x:x['grade'])
print(students)
print(students_sort)
8,读取成绩问卷并排序-读取文件,写入文件
student.txt文件中输入:
1,小张,88
2,小王,78
3,小米,98
4,小红,85
def read_file():
result = [] #用来记录
with open('./student.txt') as fin:
for line in fin:
line = line[:-1]#去掉最后的换行符
result.append(line.split(','))
return result
#此时,result中[['1','小张','88'],['2','小王','78'],...]
#都是字符串形式
def sort_grades(datas):
return sorted(datas,key=lambda x:int(x[2]),reverse=True)
def write_file(datas):
with open('./student1.txt','w') as font:
for data in datas:
font.write(','.join(data)+'\n')
#读取文件
datas = read_file()
print('读取:',datas)
#排序数据
datas = sort_grades(datas)
print('排序后:',datas)
#写出文件
write_file(datas)
9,统计最高分最低分平均分
求平均值:avg_score = round(sum(scores)/len(scores),2)
def compute_score():
scores = []
with open('./student.txt') as fin:
for line in fin:
line = line[:-1] #去掉换行符
fields = line.split(',')
scores.append(int(fields[-1])) #只读取成绩
max_score = max(scores)
min_score = min(scores)
avg_score = round(sum(scores)/len(scores),2)
return max_score,min_score,avg_score
max_score,min_score,avg_score = compute_score()
print(f'max={max_score},min={min_score},avg={avg_score}')
10,统计英文文章中单词出现次数–统计次数的代码
用字典来进行统计
英语文章放在txt文件中
word_count = {}
with open('./wenzhang.txt') as fin:
for line in fin:
line = line[:-1]
words = line.split()#按空格分列,得到单词列表
for word in words:
if word not in word_count:
word_count[word] =0
word_count[word]+=1
print(word_count) #即得到每个单词出现的次数
d = sort(word_count.items(),key=lambda x:x[-1],reverse=True) #排序
print(d[:10]) #输出词频最多的前10个单词
字典.items()函数,会返回一个list,其中会包含字典的values和key。格式如下: