程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Online notes of Python major course of Hangzhou Teachers management department (V): Supplementary Exercises of basic python (30 cases compiled by ourselves)

編輯:Python

notes : The title has been adapted appropriately , Cancel input step , Adapt to the style of the real problem , A daily topic , continued 30 God
True question link : Programming problem 、txt File operation problem


Because the selected part of the true question uses python2 grammar ,print There's no need for parentheses , So I got used to it print Bracketed can add this sentence at the beginning of the code :

#!/usr/bin/python3

Explain to the correction teacher that python3, That should not be a big problem


Catalog

  • day1 function 、for loop
  • day2 List traversal 、if sentence
  • day3 break Out of the loop
  • day4 two for loop 、set() function
  • day5 Mathematical expression
  • day6 Sort the list
  • day7 Dictionary traversal
  • day8 function 、for loop
  • day9 enumerate Traverse the list and get elements and subscripts at the same time
  • day10 //、/、% Different applications of 、while loop
  • day11 prime number 、for-else loop
  • day12 Narcissistic number 、 to be divisible by
  • day13 for A nested loop
  • day14 Nested loop 、 No repetitive combinations
  • day15 Fibonacci
  • day16 Prime judgment
  • day17 for loop
  • day18 Data exchange
  • day19 Build a dictionary
  • day20 Dictionary traversal
  • day21 function 、 The greatest common factor
  • day22 Triple loop nesting
  • day23 Build a dictionary
  • day24 Sort 、 Descending
  • day25 math library 、math.sqrt()
  • day26 txt Document title 1、 Build a dictionary 、 Dictionary traversal
  • day27 txt Document title 2、 imitation 19 The real question 、 Build a dictionary 、 Dictionary operation
  • day28 txt Document title 3、 Build a dictionary 、 Dictionary operation
  • day29 txt Document title 4、20 Adapted from the real topic 、 Increase score ranking
  • day30 txt Document title 5、 Build a dictionary 、 Dictionary operation

day1 function 、for loop

Write a function , Given a positive integer m(m>11), Calculation 11+12+13+…+m Value .

def a(m):
sum=0
for i in range(11,m+1):
sum=sum+i
return sum
print(a(21))

day2 List traversal 、if sentence

It is known that a=[3,1,12,5,14,8,7,2,5,3,2,6,7,2,3,8,5], The program output list can be 2 and 3 The number of integers

a=[3,1,12,5,14,8,7,2,5,3,2,6,7,2,3,8,5]
cnt=0
for i in a:
if i%2==0 and i%3==0:
cnt+=1
print(cnt)

Be careful if What is connected in the statement is and, No C Medium &&

day3 break Out of the loop

Programming calculation can divide at the same time 14 And 18 The smallest positive integer of ?

for i in range(1,14*18+1):
if i%14==0 and i%18==0:
print(i)
break

Be careful not to overlook range Ahead 1, Otherwise, it will start from 0 Start , The output is 0

day4 two for loop 、set() function

a=[2,1,5,1,2,3,1,3,5,6,1,8,2,1,7,7], Arrange the elements that appear twice in the list into a new list

a=[2,1,5,1,2,3,1,3,5,6,1,8,2,1,7,7]
b=list(set(a))# Storage a Different elements in , Use it carefully list() Change to list format 
cnt=0
c=[]
for i in b:
for j in a:
if i==j:
cnt+=1
if cnt==2:
c.append(i)
cnt=0
print(c)

day5 Mathematical expression

There is a cage , There are some chickens and rabbits in it , Common head 14 individual , leg 38 strip , How many chickens and rabbits are there

for i in range(1,15):
if i*2+(14-i)*4==38:
print(f' Chicken has :{
i} only , The rabbit has :{
14-i} only ')

day6 Sort the list

It is known that a=[3,1,12,5,14,8,7,2,5,3,2,6,7,2,3,8,5], The smallest in the program output list 2 An odd number ( A space separates )

a=[3,1,12,5,14,8,7,2,5,3,2,6,7,2,3,8,5]
a.sort(reverse=False)#False Expressing ascending order ,True Representation of descending order 
flag=2
for i in a:
if i%2==1 and flag!=0:
print(i,end=' ')
flag-=1
if flag==0:
break

day7 Dictionary traversal

Known dictionaries a={1:4,2:3,4:1,0:12,14:8,10:3,9:4,5:2,15:2}, Pick out all even values , Put the corresponding key into a list and output

a={
1:4,2:3,4:1,0:12,14:8,10:3,9:4,5:2,15:2}
keys=[]
for key,value in a.items():
if value%2==0:
keys.append(key)
print(keys)

day8 function 、for loop

Write a function to find a+aa+aaa++⋯+aa⋯a(n individual a) The sum of the .

def an(a,n):
sum=0# Must be placed in the function 、for Outside of the loop 
c=a# Storage a, Used with sum Add up 
for i in range(1,n+1):
sum=sum+c
c+=a*pow(10,i)
return sum
print(an(1,3))

day9 enumerate Traverse the list and get elements and subscripts at the same time

a=[143,174,119,127,117,164,110,128], Output the list subscript corresponding to the number greater than the average in the list ( Whitespace separated )

a=[143,174,119,127,117,164,110,128]
for index,i in enumerate(a):
if i>=sum(a)/len(a):
print(index,end=' ')

day10 //、/、% Different applications of 、while loop

Output a=234153 The number of digits and the sum of the digits , Separated by a space .

a=234153
sum=0
cnt=0
while a!=0:
cnt+=1
sum=sum+a%10
a=a//10
print(sum,cnt)

day11 prime number 、for-else loop

It is known that a=[3,1,12,5,14,8,7,2,5,3,2,6,7,2,3,8,5], Find the primes and sum them

for-else The meaning of : If it can be divided ( Not primes ),break Jump out of the present for loop , Do nothing ; If it's not divisible ( Prime number ),for After iteration, there are no books break Out of the loop , perform else sentence , Add this prime number to the list

a=[3,1,12,5,14,8,7,2,5,3,2,6,7,2,3,8,5]
b=[]
for i in a:
if i>1:
for j in range(2,i//2+1):
if i%j==0:
break
else:
b.append(i)
print(b)
print(sum(b))

Or by defining a function

def iszhi(n):
if n>1:
for i in range(2,n//2+1):
if n%i==0:
return False
else:
return True
a=[3,1,12,5,14,8,7,2,5,3,2,6,7,2,3,8,5]
b=[]
for j in a:
if iszhi(j)==True:
b.append(j)
print(b)
print(sum(b))

day12 Narcissistic number 、 to be divisible by

The number of Narcissus refers to a N Positive integer (N≥3), Of the numbers in each of its bits N The sum of the powers is equal to itself . for example :153=1×1×1+5×5×5+3×3×3. Programming , Calculate and output all 3 Number of daffodils .

n=3
for i in range(99,1000):
a=i//100
b=i//10-a*10
c=(i-a*100-b*10)
if i==pow(a,n)+pow(b,n)+pow(c,n):
print(i,end=' ')

day13 for A nested loop

seek 1!+3!+5!+7!+9! And , Design with loop nesting .

sum=0
a=1
for i in range(1,10,2):
for j in range(1,i+1):
a*=j
sum+=a
a=1
print(sum)

day14 Nested loop 、 No repetitive combinations

There are four numbers :1、2、3、4, How many different and unrepeated three digit numbers can be formed ? Program to output all qualified numbers

a=[1,2,3,4]
result=[]
for i in a:
for j in a:
for k in a:
if i*100+j*10+k not in result and i!=j and i!=k and j!=k:
result.append(i*100+j*10+k)
print(result)

day15 Fibonacci

Fibonacci sequence , from 1,1 Start , Each of the latter is equal to the sum of the first two , Ask before 18 Sum of items

def fib(n):
if n<=2:
return 1
else:
return fib(n-1)+fib(n-2)
sum=0
for i in range(1,19):
sum+=fib(i)
print(sum)

day16 Prime judgment

Judge 101-200 How many primes are there between , And output all prime numbers .

def iszhi(n):
if n>1:
for i in range(2,n//2+1):
if n%i==0:
return False
else:
return True
for i in range(101,201):
if iszhi(i)==True:
print(i,end=' ')

day17 for loop

Statistics 1 To 100 in 6 The sum of multiples of

sum=0
for i in range(101):
if i%6==0:
sum+=i
print(sum)

day18 Data exchange

a=[143,174,119,127,117,164,110,128], Achieve maximum exchange with the first element , The smallest exchange with the last element , The output array .

a=[143,174,119,127,117,164,110,128]
mina=min(a)
maxa=max(a)
for i in range(len(a)):
if a[i]==maxa:
a[i]=a[0]
a[0]=maxa
if a[i]==mina:
a[i]=a[-1]
a[-1]=mina
print(a)

day19 Build a dictionary

Existing list a=[2,3,1,3,2,1,3,5,4,2,1,5,2,3,1,4], Take the number in the list as the key , The number of occurrences is a value , Build dictionary and output .

a=[2,3,1,3,2,1,3,5,4,2,1,5,2,3,1,4]
keya=list(set(a))
cnt=0
result={
}
for i in keya:
for j in a:
if i==j:
cnt+=1
result[i]=cnt
cnt=0
print(result)

day20 Dictionary traversal

Known dictionaries a={1:4,2:3,4:1,0:12,14:8,10:3,9:4,5:2,15:2}, Pick out all key value pairs with even keys and values , Form a new dictionary .

a={
1:4,2:3,4:1,0:12,14:8,10:3,9:4,5:2,15:2}
result={
}
for key,value in a.items():
if key%2==0 and value%2==0:
result[key]=value
print(result)

day21 function 、 The greatest common factor

Write a function , Given any two positive integers m>1、n>1,m≠n, The greatest common factor of both ( The largest number that can be divided by both numbers ).

def a(m,n):
result=0
maxmn=0
if m>n:
maxmn=m
else:
maxmn=n
for i in range(2,maxmn//2+1):
if m%i==0 and n%i==0:
result=i
return result
print(a(140,200))

day22 Triple loop nesting

Yes 100 Bowl rice and 100 personal ,1 A man eats 2 bowl ,2 A woman eats 3 bowl ,3 A child eats 2 bowl , Ask how many men, women and children each ? Give the possibility

nan=2
nv=1.5
hai=2/3
for i in range(51):
for j in range(67):
for k in range(101):
if i+j+k==100 and nan*i+nv*j+hai*k==100:
print(i,j,k)

day23 Build a dictionary

a=[25,30,36,42,46,49,48,38,24,13,8,6],b=[10,12,14,16,18,20,22,24,26,28,30,32], among a For days ,b Is the demand number , With b As the key a Value , Create a dictionary and output the number of requirements for the maximum number of days

a=[25,30,36,42,46,49,48,38,24,13,8,6]
b=[10,12,14,16,18,20,22,24,26,28,30,32]
result={
}
for i in range(len(a)):
result[b[i]]=a[i]
print(result)
maxdaynum=max(list(result.values()))
for key,value in result.items():
if value==maxdaynum:
print(key)

day24 Sort 、 Descending

Find the list [-3,5,7,9,11,7,-1,-12,14,18] Greater than 0 Array into a new list , And output the new list in descending order

a=[-3,5,7,9,11,7,-1,-12,14,18]
b=[]
for i in a:
if i>0:
b.append(i)
b.sort(reverse=True)
print(b)

day25 math library 、math.sqrt()

import math
sum=0
for n in range(1,624):
b=math.sqrt(n)+math.sqrt(n+1)
c=1/b
sum=sum+c
print(sum)
print(f' The result is {
sum:.2f}')

In the picture txt The file has been packaged and uploaded , If necessary, you can comment on an email , The code file is placed in the and file Folder under the same level directory

day26 txt Document title 1、 Build a dictionary 、 Dictionary traversal

The figure below shows the sales of some goods in a shopping mall in the last four quarters , Stored in a file ( File directory :file/demo1.txt), The separator is ‘\t’, Notice that there is a line break at the end "\n”, The first act is to list , Programming to solve :
(1) Count the total sales of each commodity last year , Take the product name as the key , Sales volume is value output (9 branch )
(2) The average quarterly sales are greater than 1000 The goods , List output product name (6 branch )

totalSellDict={
}
aveSellOver1000=[]
with open('file/demo1.txt') as f:
f.readline()# Remove the first row that is not related to the data 
lines=f.readlines()# Read the remaining rows with data 
print('------- Answer the first question -------')
for i in range(len(lines)):
if lines[i].endswith('\n'):
lines[i]=lines[i][:-1] # Put the at the end of the string \n Get rid of , It also prevents the last line from missing \n The situation of 
lines[i]=lines[i].split('\t') # With \t Division 
totalSellDict[lines[i][0]]=int(lines[i][1])+int(lines[i][2])+int(lines[i][3])+int(lines[i][4])# If you can't write that long on the test paper , You can add '\' Line wrap writing 
print(totalSellDict)
print('------- Answer the second question -------')
for key,value in totalSellDict.items():
if value/4>1000:
aveSellOver1000.append(key)
print(aveSellOver1000)

day27 txt Document title 2、 imitation 19 The real question 、 Build a dictionary 、 Dictionary operation

The following figure shows a consumer's background record of various types of goods of a certain brand in a store one day , Stored in a file ( File directory :file/demo2.txt), The first act is to list , among type The column represents the model ,atcion The list shows the behavior (0 Indicates browsing ,1 Represents a collection ,2 Indicates additional purchase ,3 Means purchase ),time The column represents the time ( After decimation , Such as 15.25 Express 15:15 branch ), The separator is ‘\t’, Notice that there is a line break at the end "\n”, Programming to solve :
(1) Output the views of each product in the form of a dictionary (4 branch )
(2) Output the final result of each product in the form of a dictionary ( The behavior of the largest number )(5 branch )
(3) Ask for the model that takes the longest time to purchase after additional purchase (6 branch )

I feel like I have dug a big hole for myself … It was very difficult 、 What a mess , The first question has some value , The last two questions can be skipped

liuLanSum={
'A':0,'B':0,'C':0,'D':0}
state={
'A':0,'B':0,'C':0,'D':0}
startTime={
'A':0,'B':0,'C':0,'D':0}
endTime={
'A':0,'B':0,'C':0,'D':0}
costTime={
'A':0,'B':0,'C':0,'D':0}
with open('file/demo2.txt') as f:
f.readline()
lines=f.readlines()
print('------- Answer the first question -------')
for i in range(len(lines)):
if lines[i].endswith('\n'):
lines[i]=lines[i][:-1]
lines[i]=lines[i].split('\t')
if int(lines[i][1])==0:
liuLanSum[lines[i][0]]+=1
print(liuLanSum)
print('------- Answer the second question -------')
for j in range(len(lines)):
if int(lines[j][1]) > state[lines[j][0]]:
state[lines[j][0]]=int(lines[j][1])
print(state)
print('------- Answer the third question -------')
for k in range(len(lines)):
if int(lines[k][1])==2:
startTime[lines[k][0]]=float(lines[k][2])
if int(lines[k][1])==3:
endTime[lines[k][0]]=float(lines[k][2])
for key,value in startTime.items():
if value==0:
endTime[key]=0
for key,value in endTime.items():
if value==0:
startTime[key]=0
for key,value in costTime.items():
costTime[key]=endTime[key]-startTime[key]
for key,value in costTime.items():
if value==max(list(costTime.values())):
print(key)
break

day28 txt Document title 3、 Build a dictionary 、 Dictionary operation

The following figure shows four employees last year ABC Sales of three categories of goods , Stored in a file ( File directory :file/demo3.txt), The separator is ‘\t’, Notice that there is a line break at the end "\n”, The first act is to list , Programming to solve :
(1) Output for each employee ABC The total sales of the three categories of goods (8 branch )
(2) Output the average sales per employee for each product (7 branch )

staffSell={
'Lily':0,'Jane':0,'Joy':0,'Angel':0}
aveSell={
'A':0,'B':0,'C':0}
with open('file/demo3.txt') as f:
f.readline()
lines=f.readlines()
for i in range(len(lines)):
if lines[i].endswith('\n'):
lines[i]=lines[i][:-1]
lines[i]=lines[i].split('\t')
print('------- Answer the first question -------')
for j in range(len(lines)):
staffSell[lines[j][0]]+=int(lines[j][2])
print(staffSell)
print('------- Answer the second question -------')
for k in range(len(lines)):
aveSell[lines[k][1]]+=int(lines[k][2])
for key,value in aveSell.items():
aveSell[key]=value/4
print(aveSell)

day29 txt Document title 4、20 Adapted from the real topic 、 Increase score ranking

The following figure shows the comprehensive evaluation scores of several students in a class ( It is divided into moral education 、 Intellectual education points 、 Physical education scores , Full marks 100 branch ), among , According to moral education 20%、 Intellectual education points 70%、 Physical education scores 10% To calculate the total score of comprehensive evaluation . Files are stored in a file ( File directory :file/demo4.txt), The separator is ‘\t’, Notice that there is a line break at the end "\n”, The first act is to list , Programming to solve :
(1) Calculate the total score of each student in the comprehensive test ( Keep two decimal places )(4 branch )
(2) And calculate the excellence rate (85 The above points are excellent , Keep three decimal places )(5 branch )
(3) Output rank in descending order of scores 、 Name and score (6 branch )

The third question is a little difficult , Back up

excellent=0
scores={
}
names=[]
flag=0
sortedNames=[]
with open('file/demo4.txt') as f:
f.readline()
lines=f.readlines()
for i in range(len(lines)):
if lines[i].endswith('\n'):
lines[i]=lines[i][:-1]
lines[i]=lines[i].split('\t')
print('------- Answer the first question -------')
for j in range(len(lines)):
Score=0.2*int(lines[j][1])+0.7*int(lines[j][2])+0.1*int(lines[j][3])
scores[lines[j][0]]=Score
print(f'{
lines[j][0]} My total score is :{
Score:.2f}')
if Score>85:
excellent+=1
print('------- Answer the second question -------')
print(f' The excellence rate is :{
excellent/len(lines):.3f}')
print('------- Answer the third question -------')
sortedScores=list(scores.values())
sortedScores.sort(reverse=True)
for k in sortedScores:
for key,value in scores.items():
if k==value:
sortedNames.append(key)
for mingci,name,score in zip(range(1,len(lines)+1),sortedNames,sortedScores):# If you can't write that long on the test paper , You can add '\' Line wrap writing 
print(f' The first {
mingci} The name is {
name}, The score is {
score}')

day30 txt Document title 5、 Build a dictionary 、 Dictionary operation

The following picture shows a school during school 18 The number of projects approved at all levels participating in the innovation and entrepreneurship training program at level ,G It means national level ,S Means provincial ,X It means school level , Stored in a file ( File directory :file/demo5.txt), The separator is ‘\t’, Notice that there is a line break at the end "\n”, The first act is to list , Programming to solve :
(1) Seeking the whole 18 The total number of projects approved at all levels of level and output (6 branch )
(2) National level product 5 branch , Provincial plot 3 branch , School grade product 1 branch , Take the class as the key and the integral as the value to build a dictionary and output the scores of each class , And output the class with the highest score (9 branch )

total={
'G':0,'S':0,'X':0}
classPoint={
}
with open('file/demo5.txt') as f:
f.readline()
lines=f.readlines()
for i in range(len(lines)):
if lines[i].endswith('\n'):
lines[i]=lines[i][:-1]
lines[i]=lines[i].split('\t')
print('------- Answer the first question -------')
for j in range(len(lines)):
total['G']+=int(lines[i][1])
total['S']+=int(lines[i][2])
total['X']+=int(lines[i][3])
print(total)
print('------- Answer the second question -------')
for k in range(len(lines)):
classPoint[lines[k][0]]=5*int(lines[k][1])+3*int(lines[k][2])+int(lines[k][3])
print(classPoint)
maxPoint=max(list(classPoint.values()))
for key,value in classPoint.items():
if value==maxPoint:
print(key)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved