当前位置:网站首页>Python 100 cases
Python 100 cases
2020-11-06 21:13:00 【itread01】
For example 001: Combination of numbers
Title There are four numbers :1、2、3、4, How many distinct three digit numbers can be formed without repeating numbers ? How many are each ?
Program analysis Traverse all possibilities , Shave off the repetitive ones .
total=0
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if ((i!=j)and(j!=k)and(k!=i)):
print(i,j,k)
total+=1
print(total)
Easy way use itertools Medium permutations that will do .
import itertools
sum2=0
a=[1,2,3,4]
for i in itertools.permutations(a,3):
print(i)
sum2+=1
print(sum2)
For example 002:“ Personal tax calculation ”
Title The bonus paid by the enterprise is based on the profit . Profit (I) Less than or equal to 10 Ten thousand yuan , The prize money can be raised 10%; The profit is higher than 10 Ten thousand yuan , Lower than 20 Ten thousand yuan , Lower than 10 Ten thousand yuan part by 10% Royalty , Higher than 10 Ten thousand yuan , It's a percentage 7.5%;20 Ten thousand to 40 Between ten thousand , Higher than 20 Ten thousand yuan , It's a percentage 5%;40 Ten thousand to 60 Ten thousand is higher than 40 Ten thousand yuan , It's a percentage 3%;60 Ten thousand to 100 Between ten thousand , Higher than 60 Ten thousand yuan , It's a percentage 1.5%, Higher than 100 Ten thousand yuan , More than 100 Ten thousand yuan part by 1% Royalty , Enter the month's profit from the keyboard I, The total amount of bonus should be paid ?
Program analysis Divide the calculation between the slots .
profit=int(input('Show me the money: '))
bonus=0
thresholds=[100000,100000,200000,200000,400000]
rates=[0.1,0.075,0.05,0.03,0.015,0.01]
for i in range(len(thresholds)):
if profit<=thresholds[i]:
bonus+=profit*rates[i]
profit=0
break
else:
bonus+=thresholds[i]*rates[i]
profit-=thresholds[i]
bonus+=profit*rates[-1]
print(bonus)
For example 003: Perfect squared number
Title An integer , It adds 100 And then it's a perfect square , Plus 168 It's another perfect square , What's the number, please ?
Program analysis Because 168 It's too small for an exponential explosion , So mathematical analysis can be omitted directly , Get the upper limit in the simplest way :
n=0
while (n+1)**2-n*n<=168:
n+=1
print(n+1)
The train of thought is : The worst is n The square sum of (n+1) The square of is just the difference 168, Because it's Square , There can't be a bigger gap than this .
To judge whether it is a perfect square , The easiest way is : The value of the square root is decimal 0 that will do .
Together :
n=0
while (n+1)**2-n*n<=168:
n+=1
for i in range((n+1)**2):
if i**0.5==int(i**0.5) and (i+168)**0.5==int((i+168)**0.5):
print(i-100)
For example 004: The day of the day
Title Enter the date, month and year , Judge the day of the year ?
Program analysis Special circumstances , In leap years, consider adding one more day to February :
def isLeapYear(y):
return (y%400==0 or (y%4==0 and y%100!=0))
DofM=[0,31,28,31,30,31,30,31,31,30,31,30]
res=0
year=int(input('Year:'))
month=int(input('Month:'))
day=int(input('day:'))
if isLeapYear(year):
DofM[2]+=1
for i in range(month):
res+=DofM[i]
print(res+day)
For example 005: Three number sort
Title Enter three integers x,y,z, Please output these three numbers from small to large .
Program analysis Practice hands to find a random sorting algorithm to achieve , If you're lazy, you just call the function directly .
raw=[]
for i in range(3):
x=int(input('int%d: '%(i)))
raw.append(x)
for i in range(len(raw)):
for j in range(i,len(raw)):
if raw[i]>raw[j]:
raw[i],raw[j]=raw[j],raw[i]
print(raw)
raw2=[]
for i in range(3):
x=int(input('int%d: '%(i)))
raw2.append(x)
print(sorted(raw2))
For example 006: Fibonacci series
Title Fibonacci series .
Program analysis Fibonacci series (Fibonacci sequence), From 1,1 Start , Each of the latter is equal to the sum of the preceding two . The graph is convenient to implement recursively , Use loop for efficiency .
Recursive realization
def Fib(n):
return 1 if n<=2 else Fib(n-1)+Fib(n-2)
print(Fib(int(input())))
Simple realization
target=int(input())
res=0
a,b=1,1
for i in range(target-1):
a,b=b,a+b
print(a)
For example 007:copy
Title Copy data from one list to another .
Program analysis Use list [:], I'm not sure I can call copy Module .
import copy
a = [1,2,3,4,['a','b']]
b = a # Assignment
c = a[:] # Light copy
d = copy.copy(a) # Light copy
e = copy.deepcopy(a) # Deep copy
a.append(5)
a[4].append('c')
print('a=',a)
print('b=',b)
print('c=',c)
print('d=',d)
print('e=',e)
============ RESTART: F:\PyWorkspace\Python100\100examples\007.py ============
a= [1, 2, 3, 4, ['a', 'b', 'c'], 5]
b= [1, 2, 3, 4, ['a', 'b', 'c'], 5]
c= [1, 2, 3, 4, ['a', 'b', 'c']]
d= [1, 2, 3, 4, ['a', 'b', 'c']]
e= [1, 2, 3, 4, ['a', 'b']]
For example 008: multiplication table
Title Output 9*9 Multiplication table .
Program analysis Branch and column considerations , common 9 That's ok 9 Column ,i The control line ,j Control the column .
for i in range(1,10):
for j in range(1,i+1):
print('%d*%d=%2ld '%(i,j,i*j),end='')
print()
For example 009: Pause output for one second
Title Pause output for one second .
Program analysis Use time Modular sleep() Function .
import time
for i in range(4):
print(str(int(time.time()))[-2:])
time.sleep(1)
For example 010: Time for people to see
Title Pause output for one second , And format the current time .
Program analysis Same as 009.
import time
for i in range(4):
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
time.sleep(1)
For example 011: Raising rabbits
Title There's a couple of Rabbits , Since the birth of 3 Rabbits are born once a month , After the third month, the rabbit gives birth to another pair of rabbits every month , If the rabbits don't die , Ask the total number of rabbits per month ?
Program analysis I think the solution of the original text is a little bit lame , No consideration of 3 Months of maturity , How can a child be born when he is still a baby ? Considering three months of maturity , You can build four profiles , among : January rabbits grow up to be February rabbits every month , February rabbit becomes March rabbit , March rabbit becomes adult rabbit , Adult rabbits ( Including the new mature March rabbit ) Give birth to an equal number of January rabbits .
month=int(input(' Breeding for months ?: '))
month_1=1
month_2=0
month_3=0
month_elder=0
for i in range(month):
month_1,month_2,month_3,month_elder=month_elder+month_3,month_1,month_2,month_elder+month_3
print(' The first %d Months in total '%(i+1),month_1+month_2+month_3+month_elder,' To the rabbit ')
print(' among 1 Moon Rabbit :',month_1)
print(' among 2 Moon Rabbit :',month_2)
print(' among 3 Moon Rabbit :',month_3)
print(' The adult rabbit :',month_elder)
For example 012:100 To 200 The prime number of
Title Judge 101-200 How many primes between , And output all prime numbers .
Program analysis How to judge prime numbers : Remove by a number 2 To sqrt( This number ), If it can be divided , The number is not a prime number , On the contrary, it's a prime . use else Code can be further simplified .
import math
for i in range(100,200):
flag=0
for j in range(2,round(math.sqrt(i))+1):
if i%j==0:
flag=1
break
if flag:
continue
print(i)
print('\nSimplify the code with "else"\n')
for i in range(100,200):
for j in range(2,round(math.sqrt(i))+1):
if i%j==0:
break
else:
print(i)
For example 013: All daffodils count
Title Print out all " Number of Narcissus ", So called " Number of Narcissus " It means a three digit number , The number cubes are equal to the number itself . for example :153 It's a " Number of Narcissus ", Because 153=1 The third power of +5 The third power of +3 The third power of .
Program analysis utilize for Loop control 100-999 Number , Each number is decomposed into bits , ten , Hundred bit .
for i in range(100,1000):
s=str(i)
one=int(s[-1])
ten=int(s[-2])
hun=int(s[-3])
if i == one**3+ten**3+hun**3:
print(i)
For example 014: Decompose the prime factor
Title Factoring an integer into prime factors . for example : Input 90, Print out 90=233*5.
Program analysis There's no need to judge whether it's a prime number at all , From 2 Start traversing the number itself , It must be the smallest prime number that can be divisible .
target=int(input(' Enter an integer :'))
print(target,'= ',end='')
if target<0:
target=abs(target)
print('-1*',end='')
flag=0
if target<=1:
print(target)
flag=1
while True:
if flag:
break
for i in range(2,int(target+1)):
if target%i==0:
print("%d"%i,end='')
if target==i:
flag=1
break
print('*',end='')
target/=i
break
For example 015: Score filing
Title Use the nest of conditional operators to complete this problem : Academic performance >=90 The students who are divided into two parts A Express ,60-89 Between the points B Express ,60 Divide the following uses C Express .
Program analysis Judge by condition .
points=int(input(' Enter the score :'))
if points>=90:
grade='A'
elif points<60:
grade='C'
else:
grade='B'
print(grade)
For example 016: Output date
Title Output date in specified format .
Program analysis Use datetime Module .
import datetime
print(datetime.date.today())
print(datetime.date(2333,2,3))
print(datetime.date.today().strftime('%d/%m/%Y'))
day=datetime.date(1111,2,3)
day=day.replace(year=day.year+22)
print(day)
For example 017: Strings make up
Title Type a line of characters , The Chinese and English letters are counted respectively 、 Space 、 The number of numbers and other characters .
Program analysis utilize while or for Sentence , If the input character is not ‘\n’.
string=input(" Type the string :")
alp=0
num=0
spa=0
oth=0
for i in range(len(string)):
if string[i].isspace():
spa+=1
elif string[i].isdigit():
num+=1
elif string[i].isalpha():
alp+=1
else:
oth+=1
print('space: ',spa)
print('digit: ',num)
print('alpha: ',alp)
print('other: ',oth)
For example 018: Repeater addition
Title seek s=a+aa+aaa+aaaa+aa…a Value , among a It's a number . for example 2+22+222+2222+22222( At this time, there is 5 Add up the numbers ), The addition of several numbers is controlled by the keyboard .
Program analysis Solve with a string .
a=input(' Added number :')
n=int(input(' Add it a few times ?:'))
res=0
for i in range(n):
res+=int(a)
a+=a[0]
print(' The result is :',res)
For example 019: It's over
Title If a number is exactly equal to the sum of its factors , This number is called " It's over ". for example 6=1+2+3. Programming finds 1000 All the completions within .
Program analysis Add each pair of factors to the set , This process has gone automatically . The final result requires not to calculate itself .
def factor(num):
target=int(num)
res=set()
for i in range(1,num):
if num%i==0:
res.add(i)
res.add(num/i)
return res
for i in range(2,1001):
if i==sum(factor(i))-i:
print(i)
For example 020: High altitude parabolic
Title A ball from 100 Free fall at meter height , Jump back to half of the original altitude after each landing ; And then fall , Ask it in the 10 On the second landing , How many meters has it passed ? The first 10 How high is the rebound ?
Program analysis Nothing
high=200.
total=100
for i in range(10):
high/=2
total+=high
print(high/2)
print(' The total length is :',total)
For example 021: Monkeys steal peaches
Title Monkeys eat peaches : The monkey picked several peaches on the first day , I ate half of it immediately , It's not addictive , I ate one more and ate half of the remaining peaches the next morning , One more . After that, I ate half and one of the rest of the day before every morning . To the first 10 When I want to eat again in the morning , There's only one peach left . Ask how much you picked on the first day .
Program analysis Infer backward according to the rules : The monkey has a peach , He stole a peach , I think it's not enough. I stole the same amount of peaches as my hands , They stole 9 God .
peach=1
for i in range(9):
peach=(peach+1)*2
print(peach)
For example 022: Competitors
Title Two table tennis teams play , Three people each . Team a is a,b,c Three people , Team B is for x,y,z Three people . The list of matches has been drawn . Someone asked the players for the list of the game .a Said he didn't agree with x Than ,c Said he didn't agree with x,z Than , Please find out the list of players in the three teams by programming .
Program analysis Find three opponents that don't repeat under the conditions .
a=set(['x','y','z'])
b=set(['x','y','z'])
c=set(['x','y','z'])
c-=set(('x','y'))
a-=set('x')
for i in a:
for j in b:
for k in c:
if len(set((i,j,k)))==3:
print('a:%s,b:%s,c:%s'%(i,j,k))
For example 023: Draw a diamond
Title Print out the following pattern ( The diamond ):
*
***
*****
*******
*****
***
*
Program analysis Send back the call .
def draw(num):
a="*"*(2*(4-num)+1)
print(a.center(9,' '))
if num!=1:
draw(num-1)
print(a.center(9,' '))
draw(4)
For example 024: Fibonacci series II
Title There's a sequence of scores :2/1,3/2,5/3,8/5,13/8,21/13… This is the first sequence 20 Sum of items .
Program analysis It's the last term in the Fibonacci sequence, except for the previous one .
a = 2.0
b = 1.0
s = 0
for n in range(1,21):
s += a / b
a,b = a + b,a
print (s)
For example 025: Factorial summation
Title seek 1+2!+3!+…+20! And .
Program analysis 1+2!+3!+…+20!=1+2(1+3(1+4(…20(1))))
res=1
for i in range(20,1,-1):
res=i*res+1
print(res)
For example 026: Go back to factorial
Title Using recursive method to find 5!.
Program analysis Send back the call .
def factorial(n):
return n*factorial(n-1) if n>1 else 1
print(factorial(5))
For example 027: Recursive output
Title Using recursive function to call , Will enter the 5 Characters , Print it out in reverse order .
Program analysis It's a stupid way to go back .
def rec(string):
if len(string)!=1:
rec(string[1:])
print(string[0],end='')
rec(input('string here:'))
For example 028: To find the arithmetic sequence step by step
Title Yes 5 Individuals sitting together , Ask the fifth man how old he is ? He said Biddy 4 Personal big 2 Year old . Ask No 4 Personal age , He said Biddy 3 Personal big 2 Year old . Ask a third person , Again, Biddy 2 People are two years old . Ask No 2 Individual , Two years older than the first one . Finally, ask the first person , He said it was 10 Year old . How old is the fifth person ?
Program analysis Just an arithmetic sequence .
def age(n):
if n==1:
return 10
return 2+age(n-1)
print(age(5))
For example 029: Reverse output
Title Give one not more than 5 The positive integer of the bit , requirement : One 、 How many digits is it , Two 、 Print the numbers in reverse order .
Program analysis Learn to break down every digit , It's always easier to use strings .
n=int(input(' Enter a positive integer :'))
n=str(n)
print('%d Number of digits '%len(n))
print(n[::-1])
For example 030: Palindrome number
Title One 5 Number of digits , Judge whether it is palindrome number . namely 12321 It's palindrome number , One is the same as ten thousand , Ten is the same as a thousand .
Program analysis It's more convenient to use a string , Even if the input is not a number ok.
n=input(" Whatever you type in :")
a=0
b=len(n)-1
flag=True
while a<b:
if n[a]!=n[b]:
print(' It's not a palindrome string ')
flag=False
break
a,b=a+1,b-1
if flag:
print(' It's a palindrome ')
For example 031: Letters recognize words
Title Please enter the first letter of the day of the week to judge the day of the week , If the first letter is the same , Then continue to judge the second letter .
Program analysis Here we use the form of a dictionary to store the comparison relationship directly .
weekT={'h':'thursday',
'u':'tuesday'}
weekS={'a':'saturday',
'u':'sunday'}
week={'t':weekT,
's':weekS,
'm':'monday',
'w':'wensday',
'f':'friday'}
a=week[str(input(' Please enter the first letter :')).lower()]
if a==weekT or a==weekS:
print(a[str(input(' Please enter the second letter :')).lower()])
else:
print(a)
For example 032: Reverse output II
Title Output the values of the list in reverse order .
Program analysis Nothing .
a = ['one', 'two', 'three']
print(a[::-1])
For example 033: List to string
Title Separate the list by comma .
Program analysis Nothing .
L = [1,2,3,4,5]
print(','.join(str(n) for n in L))
For example 034: Call function
Title Practice function calls .
Program analysis Nothing .
def hello():
print('Hello World!')
def helloAgain():
for i in range(2):
hello()
if __name__=='__main__':
helloAgain()
For example 035: Set the output color
Title Text color setting .
Program analysis Nothing .
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
print(bcolors.WARNING + " The color and font of the warning ?" + bcolors.ENDC)
For example 036: Count prime numbers
Title seek 100 Prime numbers within .
Program analysis use else Execute for The reward code of the circle ( If for It's a normal ending , Not break).
lo=int(input(' Lower limit :'))
hi=int(input(' ceiling :'))
for i in range(lo,hi+1):
if i > 1:
for j in range(2,i):
if (i % j) == 0:
break
else:
print(i)
For example 037: Sort
Title Yes 10 Sort by number .
Program analysis In the same case 005.
raw=[]
for i in range(10):
x=int(input('int%d: '%(i)))
raw.append(x)
for i in range(len(raw)):
for j in range(i,len(raw)):
if raw[i]>raw[j]:
raw[i],raw[j]=raw[j],raw[i]
print(raw)
For example 038: The sum of the diagonals of a matrix
Title Ask for one 3*3 The sum of the main diagonal elements of a matrix .
Program analysis Nothing .
mat=[[1,2,3],
[3,4,5],
[4,5,6]
]
res=0
for i in range(len(mat)):
res+=mat[i][i]
print(res)
For example 039: Ordered list insert elements
Title There's an ordered array . Now enter a number , It is required to insert it into the array according to the original rule .
Program analysis First judge whether the number is greater than the last number , Then consider the case of inserting the middle number , The number after this element is inserted , Move back one position in turn .
lis=[1,10,100,1000,10000,100000]
n=int(input('insert a number: '))
lis.append(n)
for i in range(len(lis)-1):
if lis[i]>=n:
for j in range(i,len(lis)):
lis[j],lis[-1]=lis[-1],lis[j]
break
print(lis)
For example 040: Reverse list
Title Output an array in reverse order .
Program analysis Switch positions in turn , Or call directly reverse Method .
lis=[1,10,100,1000,10000,100000]
for i in range(int(len(lis)/2)):
lis[i],lis[len(lis)-1-i]=lis[len(lis)-1-i],lis[i]
print(' The first kind of implementation :')
print(lis)
lis=[1,10,100,1000,10000,100000]
print(' The second implementation :')
lis.reverse()
print(lis)
For example 041: Class methods and variables
Title Imitate the use of static variables .
Program analysis Construction class , Understand the methods and variables of a class .
def dummy():
i=0
print(i)
i+=1
class cls:
i=0
def dummy(self):
print(self.i)
self.i+=1
a=cls()
for i in range(50):
dummy()
a.dummy()
For example 042: Variable scope
Title Learn to use auto Define the usage of variables .
Program analysis python Variable scope in .
i=0
n=0
def dummy():
i=0
print(i)
i+=1
def dummy2():
global n
print(n)
n+=1
print(' A variable with the same name inside a function ')
for j in range(20):
print(i)
dummy()
i+=1
print('global Declare the variable with the same name ')
for k in range(20):
print(n)
dummy2()
n+=10
For example 043: Scope 、 Class methods and variables
Title Imitate static variables (static) Another case .
Program analysis Comprehensive example 041 And examples 042.
class dummy:
num=1
def Num(self):
print('class dummy num:',self.num)
print('global num: ',num)
self.num+=1
n=dummy()
num=1
for i in range(5):
num*=10
n.Num()
For example 044: Matrix addition
Title Calculate the addition of two matrices .
Program analysis Build a new matrix , Use for Iterate and extract X and Y The value of the corresponding position in the matrix , Add it and put it in the corresponding position of the new matrix .
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
res=[[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(len(res)):
for j in range(len(res[0])):
res[i][j]=X[i][j]+Y[i][j]
print(res)
For example 045: Sum up
Title Statistics 1 To 100 The sum of the .
Program analysis Nothing
res=0
for i in range(1,101):
res+=i
print(res)
For example 046: Break the circle
Title Square the input number , If the square is less than 50 Then exit .
Program analysis Nothing
while True:
try:
n=float(input(' Enter a number :'))
except:
print(' Input error ')
continue
dn=n**2
print(' Its square is :',dn)
if dn<50:
print(' The square is less than 50, sign out ')
break
For example 047: Functions exchange variables
Title Two variables are interchanged by functions .
Program analysis Nothing
def exc(a,b):
return (b,a)
a=0
b=10
a,b=exc(a,b)
print(a,b)
For example 048: The number is bigger than the size
Title Number comparison .
Program analysis Nothing
a=int(input('a='))
b=int(input('b='))
if a<b:
print('a<b')
elif a>b:
print('a>b')
else:
print('a=b')
For example 049:lambda
Title Use lambda To create anonymous functions .
Program analysis Nothing
Max=lambda x,y:x*(x>=y)+y*(y>x)
Min=lambda x,y:x*(x<=y)+y*(y<x)
a=int(input('1:'))
b=int(input('2:'))
print(Max(a,b))
print(Min(a,b))
For example 050: Random numbers
Title Output a random number .
Program analysis Use random Module .
import random
print(random.uniform(10,20))
For example 051: Bitwise and
Title Learn to use bitwise and & .
Program analysis 0&0=0; 0&1=0; 1&0=0; 1&1=1.
a=0o77
print(a)
b=a&3
print(b)
b=b&7
print(b)
For example 052: Press bit or
Title Learn to use bitwise OR | .
Program analysis 0|0=0; 0|1=1; 1|0=1; 1|1=1
a=0o77
print(a|3)
print(a|3|7)
For example 053: According to position XOR
Title Learn to use bitwise XOR ^ .
Program analysis 0^0=0; 0^1=1; 1^0=1; 1^1=0
a=0o77
print(a^3)
print(a^3^7)
For example 054: Bit inversion 、 Bit shift
Title Take an integer a It starts at the right end 4~7 position .
Program analysis Think about it this way :
(1) First of all a Move right 4 position .
(2) Set a low 4 All the seats are 1, The rest are all 0 The number of . You can use (0<<4)
(3) The above two are carried out & Operations .
a=int(input(' Enter a number : '))
b=0 # 0
b=~b # 1
b=b<<4 # 10000
b=~b # 1111
c=a>>4
d=c&b
print('a:',bin(a))
print('b:',bin(b))
print('c:',bin(c))
print('d:',bin(d))
For example 055: According to the not
Title Learn to use positional inversion ~.
Program analysis ~0=1; ~1=0;
print(~234)
print(~~234)
For example 056: Circle
Title Drawing , Learn to use circle Draw a circle .
Program analysis Nothing .
from tkinter import *
canvas=Canvas(width=800,height=600,bg='yellow')
canvas.pack(expand=YES,fill=BOTH)
k=1
j=1
for i in range(26):
canvas.create_oval(310-k,250-k,310+k,250+k,width=1)
k+=j
j+=0.3
mainloop()
For example 057: Draw a line
Title Drawing , Learn to use line Draw a straight line .
Program analysis Nothing .
if __name__ == '__main__':
from tkinter import *
canvas = Canvas(width=300, height=300, bg='green')
canvas.pack(expand=YES, fill=BOTH)
x0 = 263
y0 = 263
y1 = 275
x1 = 275
for i in range(19):
canvas.create_line(x0,y0,x0,y1, width=1, fill='red')
x0 = x0 - 5
y0 = y0 - 5
x1 = x1 + 5
y1 = y1 + 5
x0 = 263
y1 = 275
y0 = 263
for i in range(21):
canvas.create_line(x0,y0,x0,y1,fill = 'red')
x0 += 5
y0 += 5
y1 += 5
mainloop()
For example 058: Draw a rectangle
Title Drawing , Learn to use rectangle Draw a square .
Program analysis Nothing .
if __name__ == '__main__':
from tkinter import *
root = Tk()
root.title('Canvas')
canvas = Canvas(root,width = 400,height = 400,bg = 'yellow')
x0 = 263
y0 = 263
y1 = 275
x1 = 275
for i in range(19):
canvas.create_rectangle(x0,y0,x1,y1)
x0 -= 5
y0 -= 5
x1 += 5
y1 += 5
canvas.pack()
root.mainloop()
For example 059: Drawing ( Ugly )
Title Drawing , Comprehensive examples .
Program analysis Ugly .
if __name__ == '__main__':
from tkinter import *
canvas = Canvas(width = 300,height = 300,bg = 'green')
canvas.pack(expand = YES,fill = BOTH)
x0 = 150
y0 = 100
canvas.create_oval(x0 - 10,y0 - 10,x0 + 10,y0 + 10)
canvas.create_oval(x0 - 20,y0 - 20,x0 + 20,y0 + 20)
canvas.create_oval(x0 - 50,y0 - 50,x0 + 50,y0 + 50)
import math
B = 0.809
for i in range(16):
a = 2 * math.pi / 16 * i
x = math.ceil(x0 + 48 * math.cos(a))
y = math.ceil(y0 + 48 * math.sin(a) * B)
canvas.create_line(x0,y0,x,y,fill = 'red')
canvas.create_oval(x0 - 60,y0 - 60,x0 + 60,y0 + 60)
for k in range(501):
for i in range(17):
a = (2 * math.pi / 16) * i + (2 * math.pi / 180) * k
x = math.ceil(x0 + 48 * math.cos(a))
y = math.ceil(y0 + 48 + math.sin(a) * B)
canvas.create_line(x0,y0,x,y,fill = 'red')
for j in range(51):
a = (2 * math.pi / 16) * i + (2* math.pi / 180) * k - 1
x = math.ceil(x0 + 48 * math.cos(a))
y = math.ceil(y0 + 48 * math.sin(a) * B)
canvas.create_line(x0,y0,x,y,fill = 'red')
mainloop()
For example 060: String length
Title Calculate string length .
Program analysis Nothing .
s='zhangguang101'
print(len(s))
For example 061: Yang Hui triangle
Title Print out the first ten lines of Yang Hui's triangle .
Program analysis Nothing .
def generate(numRows):
r = [[1]]
for i in range(1,numRows):
r.append(list(map(lambda x,y:x+y, [0]+r[-1],r[-1]+[0])))
return r[:numRows]
a=generate(10)
for i in a:
print(i)
For example 062: Query string
Title Query string .
Program analysis Nothing .
s1='aabbxuebixuebi'
s2='ab'
s3='xue'
print(s1.find(s2))
print(s1.find(s3))
For example 063: Draw an ellipse
Title Draw an ellipse .
Program analysis Use tkinter.
if __name__ == '__main__':
from tkinter import *
x = 360
y = 160
top = y - 30
bottom = y - 30
canvas = Canvas(width = 400,height = 600,bg = 'white')
for i in range(20):
canvas.create_oval(250 - top,250 - bottom,250 + top,250 + bottom)
top -= 5
bottom += 5
canvas.pack()
mainloop()
For example 064: Draw an ellipse 、 rectangular
Title utilize ellipse and rectangle Drawing ..
Program analysis Nothing .
if __name__ == '__main__':
from tkinter import *
canvas = Canvas(width = 400,height = 600,bg = 'white')
left = 20
right = 50
top = 50
num = 15
for i in range(num):
canvas.create_oval(250 - right,250 - left,250 + right,250 + left)
canvas.create_oval(250 - 20,250 - top,250 + 20,250 + top)
canvas.create_rectangle(20 - 2 * i,20 - 2 * i,10 * (i + 2),10 * ( i + 2))
right += 5
left += 5
top += 10
canvas.pack()
mainloop()
For example 065: Draw a combination of figures
Title One of the most beautiful patterns .
Program analysis Nothing .
import math
from tkinter import *
class PTS:
def __init__(self):
self.x = 0
self.y = 0
points = []
def LineToDemo():
screenx = 400
screeny = 400
canvas = Canvas(width = screenx,height = screeny,bg = 'white')
AspectRatio = 0.85
MAXPTS = 15
h = screeny
w = screenx
xcenter = w / 2
ycenter = h / 2
radius = (h - 30) / (AspectRatio * 2) - 20
step = 360 / MAXPTS
angle = 0.0
for i in range(MAXPTS):
rads = angle * math.pi / 180.0
p = PTS()
p.x = xcenter + int(math.cos(rads) * radius)
p.y = ycenter - int(math.sin(rads) * radius * AspectRatio)
angle += step
points.append(p)
canvas.create_oval(xcenter - radius,ycenter - radius,
xcenter + radius,ycenter + radius)
for i in range(MAXPTS):
for j in range(i,MAXPTS):
canvas.create_line(points[i].x,points[i].y,points[j].x,points[j].y)
canvas.pack()
mainloop()
if __name__ == '__main__':
LineToDemo()
For example 066: Three number sort
Title Input 3 Number a,b,c, Output in order of size .
Program analysis In the same case 005.
raw=[]
for i in range(3):
x=int(input('int%d: '%(i)))
raw.append(x)
for i in range(len(raw)):
for j in range(i,len(raw)):
if raw[i]>raw[j]:
raw[i],raw[j]=raw[j],raw[i]
print(raw)
raw2=[]
for i in range(3):
x=int(input('int%d: '%(i)))
raw2.append(x)
print(sorted(raw2))
For example 067: Swap places
Title Input array , The biggest exchange with the first element , The smallest exchange with the last element , Output array .
Program analysis Nothing .
li=[3,2,5,7,8,1,5]
li[-1],li[li.index(min(li))]=li[li.index(min(li))],li[-1]
m=li[0]
ind=li.index(max(li))
li[0]=li[ind]
li[ind]=m
print(li)
For example 068: Rotation sequence
Title Yes n An integer , Move the preceding numbers backward in order m A place , Finally m The number becomes the first m Number
Program analysis Nothing .
from collections import *
li=[1,2,3,4,5,6,7,8,9]
deq=deque(li,maxlen=len(li))
print(li)
deq.rotate(int(input('rotate:')))
print(list(deq))
For example 069: Report number
Title Yes n A circle of individuals , Sequence number . Count from the first person ( From 1 To 3 Report number ), Where to report 3 Of the people out of the circle , What's the last one left behind .
Program analysis Nothing .
if __name__ == '__main__':
nmax = 50
n = int(input(' Please enter the total number of people :'))
num = []
for i in range(n):
num.append(i + 1)
i = 0
k = 0
m = 0
while m < n - 1:
if num[i] != 0 : k += 1
if k == 3:
num[i] = 0
k = 0
m += 1
i += 1
if i == n : i = 0
i = 0
while num[i] == 0: i += 1
print(num[i])
For example 070: String length II
Title Write a function , Find the length of a string , stay main Type the string in the function , And output its length .
Program analysis Nothing .
def lenofstr(s):
return len(s)
print(lenofstr('tanxiaofengsheng'))
For example 071: Input and output
Title Write input() and output() Function input , Output 5 Student records .
Program analysis Nothing .
N = 3
#stu
#num : string
#name : string
#score[4]: list
student = []
for i in range(5):
student.append(['','',[]])
def input_stu(stu):
for i in range(N):
stu[i][0] = input('input student num:\n')
stu[i][1] = input('input student name:\n')
for j in range(3):
stu[i][2].append(int(input('score:\n')))
def output_stu(stu):
for i in range(N):
print ('%-6s%-10s' % ( stu[i][0],stu[i][1] ))
for j in range(3):
print ('%-8d' % stu[i][2][j])
if __name__ == '__main__':
input_stu(student)
print (student)
output_stu(student)
For example 072: Create a connection string
Title Create a link string .
Program analysis The original is not very reliable .
class Node:
def __init__(self, data):
self.data = data
self.next = None
def get_data(self):
return self.data
class List:
def __init__(self, head):
self.head = head
def is_empty(self):
return self.get_len() == 0
def get_len(self):
length = 0
temp = self.head
while temp is not None:
length += 1
temp = temp.next
return length
def append(self, node):
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = node
def delete(self, index):
if index < 1 or index > self.get_len():
print(" The positioning is unreasonable ")
return
if index == 1:
self.head = self.head.next
return
temp = self.head
cur_pos = 0
while temp is not None:
cur_pos += 1
if cur_pos == index-1:
temp.next = temp.next.next
temp = temp.next
def insert(self, pos, node):
if pos < 1 or pos > self.get_len():
print(" The insertion node position is unreasonable ")
return
temp = self.head
cur_pos = 0
while temp is not Node:
cur_pos += 1
if cur_pos == pos-1:
node.next = temp.next
temp.next =node
break
temp = temp.next
def reverse(self, head):
if head is None and head.next is None:
return head
pre = head
cur = head.next
while cur is not None:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
head.next = None
return pre
def print_list(self, head):
init_data = []
while head is not None:
init_data.append(head.get_data())
head = head.next
return init_data
if __name__=='__main__':
head=Node('head')
link=List(head)
for i in range(10):
node=Node(i)
link.append(node)
print(link.print_list(head))
For example 073: Reverse output concatenation
Title Output a concatenated column in reverse .
Program analysis Nothing .
class Node:
def __init__(self, data):
self.data = data
self.next = None
def get_data(self):
return self.data
class List:
def __init__(self, head):
self.head = head
def is_empty(self):
return self.get_len() == 0
def get_len(self):
length = 0
temp = self.head
while temp is not None:
length += 1
temp = temp.next
return length
def append(self, node):
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = node
def delete(self, index):
if index < 1 or index > self.get_len():
print(" The positioning is unreasonable ")
return
if index == 1:
self.head = self.head.next
return
temp = self.head
cur_pos = 0
while temp is not None:
cur_pos += 1
if cur_pos == index-1:
temp.next = temp.next.next
temp = temp.next
def insert(self, pos, node):
if pos < 1 or pos > self.get_len():
print(" The insertion node position is unreasonable ")
return
temp = self.head
cur_pos = 0
while temp is not Node:
cur_pos += 1
if cur_pos == pos-1:
node.next = temp.next
temp.next =node
break
temp = temp.next
def reverse(self, head):
if head is None and head.next is None:
return head
pre = head
cur = head.next
while cur is not None:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
head.next = None
return pre
def print_list(self, head):
init_data = []
while head is not None:
init_data.append(head.get_data())
head = head.next
return init_data
if __name__=='__main__':
head=Node('head')
link=List(head)
for i in range(10):
node=Node(i)
link.append(node)
print(link.print_list(head))
print(link.print_list(link.reverse(head)))
For example 074: Sort the list 、 Connect
Title List sorting and linking .
Program analysis Sorting can be done using sort() Method , The connection can use + No. or extend() Method .
a=[2,6,8]
b=[7,0,4]
a.extend(b)
a.sort()
print(a)
For example 075: confused
Title Just relax , A simple question .
Program analysis Who knows what .
if __name__ == '__main__':
for i in range(5):
n = 0
if i != 1: n += 1
if i == 3: n += 1
if i == 4: n += 1
if i != 4: n += 1
if n == 3: print (64 + i)
For example 076: Do function
Title Write a function , Input n Even number , Call function to find 1/2+1/4+…+1/n, When input n When it is odd , Call function 1/1+1/3+…+1/n
Program analysis Nothing .
def peven(n):
i = 0
s = 0.0
for i in range(2,n + 1,2):
s += 1.0 / i
return s
def podd(n):
s = 0.0
for i in range(1, n + 1,2):
s += 1.0 / i
return s
def dcall(fp,n):
s = fp(n)
return s
if __name__ == '__main__':
n = int(input('input a number: '))
if n % 2 == 0:
sum = dcall(peven,n)
else:
sum = dcall(podd,n)
print (sum)
For example 077: Traverse the list
Title Loop output list
Program analysis Nothing .
l=['moyu','niupi','xuecaibichi','shengfaji','42']
for i in range(len(l)):
print(l[i])
For example 078: Dictionaries
Title Find the oldest person , And output . Please find out what's wrong with the program .
Program analysis Nothing .
if __name__ == '__main__':
person = {"li":18,"wang":50,"zhang":20,"sun":22}
m = 'li'
for key in person.keys():
if person[m] < person[key]:
m = key
print ('%s,%d' % (m,person[m]))
For example 079: String sort
Title String sort .
Program analysis Nothing .
l=['baaa','aaab','aaba','aaaa','abaa']
l.sort()
print(l)
For example 080: The monkey divides the peach
Title There is a pile of peaches on the beach , Five monkeys to divide . The first monkey divided the pile of peaches into five parts , One more , The monkey threw one more into the sea , Took a share of . The second monkey divided the remaining peaches into five parts , One more , It also throws one more into the sea , Took a share of , Third 、 Fourth 、 The fifth monkey did this , Ask how many peaches there are at least on the beach ?
Program analysis Nothing .
if __name__ == '__main__':
i = 0
j = 1
x = 0
while (i < 5) :
x = 4 * j
for i in range(0,5) :
if(x%4 != 0) :
break
else :
i += 1
x = (x/4) * 5 +1
j += 1
print(x)
for p in range(5):
x=(x-1)/5*4
print(x)
For example 081: Ask for the unknowns
Title 809*??=800*??+9*?? among ?? Two digits for , 809*?? It's four digits ,8*?? The results are in two digits ,9*?? The result is 3 Number of digits . seek ?? Two digits for , And 809*?? The result after .
Program analysis Nothing .
a = 809
for i in range(10,100):
b = i * a
if b >= 1000 and b <= 10000 and 8 * i < 100 and 9 * i >= 100:
print(b,' = 800 * ', i, ' + 9 * ', i)
for i in range(10,100):
if 8*i>99 or 9*i<100:
continue
if 809*i==800*i+9*i:
print(i)
break
For example 082: Carry to decimal
Title Conversion from octave to decimal
Program analysis Nothing .
n=eval('0o'+str(int(input(' Octal input :'))))
print(n)
For example 083: Make odd numbers
Title seek 0—7 The odd number that can be made up of .
Program analysis
Make up 1 The number of digits is 4 One .1,3,5,7 End
Make up 2 The number of digits is 7*4 One . The first one can't be for 0
Make up 3 The number of digits is 784 One . In the middle
Make up 4 The number of digits is 788*4 One .
if __name__ == '__main__':
sum = 4
s = 4
for j in range(2,9):
print (sum)
if j <= 2:
s *= 7
else:
s *= 8
sum += s
print('sum = %d' % sum)
For example 084: Connection string
Title Connection string .
Program analysis Nothing .
delimiter = ','
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))
For example 085: to be divisible by
Title Enter an odd number , Then judge at least a few 9 The result of division is an integer .
Program analysis 999999 / 13 = 76923.
if __name__ == '__main__':
zi = int(input(' Enter a number :'))
n1 = 1
c9 = 1
m9 = 9
sum = 9
while n1 != 0:
if sum % zi == 0:
n1 = 0
else:
m9 *= 10
sum += m9
c9 += 1
print ('%d One 9 Can be %d to be divisible by : %d' % (c9,zi,sum))
r = sum / zi
print ('%d / %d = %d' % (sum,zi,r))
For example 086: Connection string II
Title Two string connectors .
Program analysis Nothing .
a='guangtou'
b='feipang'
print(b+a)
For example 087: Access class members
Title The answer is ( Structure variable passing ).
Program analysis Nothing .
if __name__ == '__main__':
class student:
x = 0
c = 0
def f(stu):
stu.x = 20
stu.c = 'c'
a= student()
a.x = 3
a.c = 'a'
f(a)
print(a.x,a.c)
For example 088: Print the asterisk
Title Read 7 Number (1—50) The integer value of , Every time a value is read , The program prints out the number of *.
Program analysis Nothing .
for i in range(3):
print('*'*int(input('input a number: ')))
For example 089: Decoding
Title A company uses a public phone to transfer information , Data is a four digit integer , It's encrypted during delivery , The encryption rules are as follows : Add... To each number 5, And divide by sum 10 In place of the number , Exchange the first and the fourth , The second and third place are exchanged .
Program analysis Nothing .
n=input()
n = str(n)
a=[]
for i in range(4):
a.append(int(n[i])+5)
a[0],a[3]=a[3],a[0]
a[1],a[2]=a[2],a[1]
print ("".join('%s' %s for s in a))
For example 090: List details
Title List usage example item .
Program analysis Nothing .
#list
# New list
testList=[10086,' China Mobile ',[1,2,4,5]]
# Access list length
print (len(testList) )
# To the end of the list
print (testList[1:])
# Add elements to the list
testList.append('i\'m new here!')
print (len(testList) )
print (testList[-1] )
# The last element of the pop-up list
print (testList.pop(1) )
print (len(testList) )
print (testList )
st comprehension
# There is an introduction later , For a while
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print (matrix )
print (matrix[1] )
col2 = [row[1] for row in matrix]#get a column from a matrix
print (col2 )
col2even = [row[1] for row in matrix if row[1] % 2 == 0]#filter odd item
print (col2even)
For example 091:time Module
Title Examples of time functions 1.
Program analysis Nothing .
if __name__ == '__main__':
import time
print (time.ctime(time.time()))
print (time.asctime(time.localtime(time.time())))
print (time.asctime(time.gmtime(time.time())))
For example 092:time Module II
Title Examples of time functions 2.
Program analysis How to waste time .
if __name__ == '__main__':
import time
start = time.time()
for i in range(3000):
print(i)
end = time.time()
print (end - start)
For example 093:time Module III
Title Examples of time functions 3.
Program analysis How to waste time .
if __name__ == '__main__':
import time
start = time.clock()
for i in range(100):
print(i)
end = time.clock()
print('different is %6.3f' % (end - start))
For example 094:time Module IV
Title Examples of time functions 4.
Program analysis How to waste time .
if __name__ == '__main__':
import time
import random
play_it = input('do you want to play it.(\'y\' or \'n\')')
while play_it == 'y':
c = input('input a character:\n')
i = random.randint(0,2**32) % 100
print ('please input number you guess:\n')
start = time.clock()
a = time.time()
guess = int(input('input your guess:\n'))
while guess != i:
if guess > i:
print('please input a little smaller')
guess = int(input('input your guess:\n'))
else:
print('please input a little bigger')
guess = int(input('input your guess:\n'))
end = time.clock()
b = time.time()
var = (end - start) / 18.2
print (var)
# print 'It took you %6.3 seconds' % time.difftime(b,a))
if var < 15:
print ('you are very clever!')
elif var < 25:
print ('you are normal!')
else:
print ('you are stupid!')
print ('Congradulations')
print ('The number you guess is %d' % i)
play_it = input('do you want to play it.')
For example 095: Convert time format
Title Convert string date to readable date format .
Program analysis Just look at it ,dateutil It's a third party Library .
from dateutil import parser
dt = parser.parse("Aug 28 2015 12:00AM")
print (dt)
For example 096: Count the number of repetitions
Title Count the number of substrings in a string .
Program analysis Nothing .
s1='xuebixuebixuebixuebixuebixuebixuebixue'
s2='xuebi'
print(s1.count(s2))
For example 097: Disk write
Title Enter some characters from the keyboard , Write them to disk files one by one , Until you enter a # Until .
Program analysis Nothing .
if __name__ == '__main__':
from sys import stdout
filename = input(' Enter the file name :\n')
fp = open(filename,"w")
ch = input(' Type the string :\n')
while ch != '#':
fp.write(ch)
stdout.write(ch)
ch = input('')
fp.close()
For example 098: Disk write II
Title Enter a string from the keyboard , Convert all lowercase letters to uppercase letters , Then output to a disk file "test" Medium storage .
Program analysis Nothing .
if __name__ == '__main__':
fp = open('test.txt','w')
string = input('please input a string:\n')
string = string.upper()
fp.write(string)
fp = open('test.txt','r')
print (fp.read())
fp.close()
For example 099: Disk reading and writing
Title There are two disk files A and B, Store one line of letters each , Request to merge the information in these two files ( In alphabetical order ), Output to a new file C in .
Program analysis Nothing .
if __name__ == '__main__':
import string
fp = open('test1.txt')
a = fp.read()
fp.close()
fp = open('test2.txt')
b = fp.read()
fp.close()
fp = open('test3.txt','w')
l = list(a + b)
l.sort()
s = ''
s = s.join(l)
fp.write(s)
fp.close()
For example 100: Turn to the list
Title List to dictionary .
Program analysis Nothing .
i = ['a', 'b']
l = [1, 2]
print (dict(zip(i,l)))
&n
版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
边栏推荐
- From overseas to China, rancher wants to do research on container cloud market
- 解决 WPF 绑定集合后数据变动界面却不更新的问题
- Kubernetes and OAM to build a unified, standardized application management platform knowledge! (Internet disk link attached)
- C語言I部落格作業03
- 2020年第四届中国 BIM (数字建造)经理高峰论坛即将在杭举办
- Building a new generation cloud native data lake with iceberg on kubernetes
- What is the tensor in tensorflow?
- Call analysis of start method in JNI thread and callback analysis of run method
- To Lianyun analysis: why is IPFs / filecoin mining so difficult?
- Summary of front-end performance optimization that every front-end engineer should understand:
猜你喜欢

What is the purchasing supplier system? Solution of purchasing supplier management platform

What are Devops

意派Epub360丨你想要的H5模板都在这里,电子书、大转盘、红包雨、问卷调查……

An article takes you to understand CSS3 picture border

事务的本质和死锁的原理
![Tron smart wallet PHP development kit [zero TRX collection]](/img/3b/00bc81122d330c9d59909994e61027.jpg)
Tron smart wallet PHP development kit [zero TRX collection]

如何对数据库账号权限进行精细化管理?

代码重构之法——方法重构分析

What is the tensor in tensorflow?

What knowledge do Python automated testing learn?
随机推荐
2020-09-03:裸写算法:回形矩阵遍历。
Use modelarts quickly, zero base white can also play AI!
递归、回溯算法常用数学基础公式
Call analysis of start method in JNI thread and callback analysis of run method
With this artifact, quickly say goodbye to spam messages
2020年第四届中国 BIM (数字建造)经理高峰论坛即将在杭举办
Unity performance optimization
事务的本质和死锁的原理
Using an example to understand the underlying processing mechanism of JS function
Markdown tricks
Summary of front-end interview questions (C, s, s) that front-end engineers need to understand (2)
An article takes you to understand CSS gradient knowledge
jenkins安装部署过程简记
实用工具类函数(持续更新)
How to understand Python iterators and generators?
Git rebase is in trouble. What to do? Waiting line
list转换map(根据key来拆分list,相同key的value为一个list)
2020-08-29:进程线程的区别,除了包含关系之外的一些区别,底层详细信息?
ES6 learning notes (5): easy to understand ES6's built-in extension objects
ES中删除索引的mapping字段时应该考虑的点