![]()
-
- In general, it was not difficult and took less than two days to do all of them, with more than half the time spent writing documents.
- And whether it be of the hands, or of those that are ready to practice.
Bibliography
- Python 3,100 cases
-
-
- Example 001: Numeric combinations
- Example 002: “One tax calculation”
- Example 003: Full square number
- Example 004: Days of the day
- Example 005: Sorting of three digits
- Example 006: Fibonacci series
- Example 007:copy
- Example 008: 999 Multiplication Table
- Example 009: Pause output for one second
- Example 010: Time for people to see
- Example 011: Rabbits
- Example 012: 100 to 200 prime figures
- Example 013: All daffodils
- Example 014: Decomposition factor
- Example 015: Score Archive
- Example 016: Output date
- Example 017: String Composition
- Example 018: Repeater added
- Example 019: Finish
- Example 020: High-air parabolics
- Example 021: Monkeys steal peaches
- Example 022: Competing opponent
- Example 023: Scratch
- Example 024: Fibonacci series II
- Example 025: Factorial Sum
- Example 026: Retrogression factor multiplier
- Example 027: Recursive output
- Example 028: Retrogression Parity Column
- Example 029: Inverse output
- Example 030: Number of replies
- Example 031: Alphabetical
- Example 032: Inverse output II
- Example 033: List-Turn String
- Example 034: Call function
- Example 035: Set Output Colour
- Example 036: Numerical
- Example 037: Sorting
- Example 038: sum of the diagonal array
- Example 039: Arranged list for insertion of elements
- Example 040: Inverse Sequence Table
- Example 041: Methods and variables for categories
- Example 042: Variable action area
- Example 043: Scopes, Category Methods and Variables
- Example 044: Matrix added
- Example 045: Summation
- Example 046: Breaking the cycle
- Example 047: Function exchange variables
- Example 048: Numbers vs. Size
- Example 049:lambda
- Example 050: Random number
- Example 051: By
- Example 052: By Bit or
- Example 053: Differing or
- Example 054: Inverse and shift
- Example 055: Inverted in place
- Example 056: Circles
- Example 057: Painting line
- Example 058: Draw Rectangle
- Example 059: Drawing (b)
- Example 060: String Length
- Example 061: Yang Fai Triangle
- Example 062: Find Strings
- Example 063: Draw Ellipse
- Example 064: Draw ellipse, rectangle
- Example 065: Draw a combination of graphics
- Example 066: Sorting of three digits
- Example 067: Exchange location
- Example 068: Rotation Columns
- Example 069: Counting
- Example 070: String length II
- Example 071: Input and Output
- Example 072: Create Chain
- Example 073: Reverse Export Chain Table
- Example 074: List Sorting, Connecting
- Example 075: Ignorance
- Example 076: Perform function
- Example 077: List of Walking Through
- Example 078: Dictionary
- Example 079: String Sorting
- Example 080: Monkey split peaches
- Example 081: Unknown
- Example 082: Octahedron to Decimal
- Example 083: Production odd
- Example 084: Connect String
- Example 085: Dissociation
- Example 086: Connection string II
- Example 087: Visiting category members
- Example 088: Print asterisk
- Example 089: Decoding
- Example 090: List details
- Example 091:time module
- Example 092:time module II
- Example 093:time Module III
- Example 094:time Module IV
- Example 095: Conversion time format
- Example 096: Calculate the number of times read again
- Example 097: Disk Writing
- Example 098: Disk Writing II
- Example 099: Disk reading and writing
- Example 100: List transword dictionary
-
-
Example 001: Numeric combinations
Title There are four numbers: 1, 2, 3 and 4, how many of them can make up a three-digit number that is different and not duplicated?
Analysis of procedures Go through all possible, shave the repeat.
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. It’s okay to use the permutations in the itertols.
import itertools
sum2=0
a=[1,2,3,4]
for i in itertools.permutations(a,3):
print(i)
sum2+=1
print(sum2)
Example 002: “One tax calculation”
Title An enterprise pays a bonus based on profits. The bonus is 10% when profit (I) is less than or equal to $100,000; the portion below $100,000 is 10% and above $100,000, 7.5%; between 200,000 and 400,000 are higher than $200,000, 5%; between 400,000 and 600,000 are greater than $400,000, 3%; between 600,000 and 1 million, it is 1.5% and over $1 million, and more than $1 million is calculated by 1%; the total amount of monthly profits should be paid from keyboards?
Analysis of procedures The partition calculation is sufficient.
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)
Example 003: Full square number
Title An integer number, which is 100 plus a full square number, and 168 plus a full square number. What is that number?
Analysis of procedures Because 168 is too small for an index explosion, it is possible to omit the mathematical analysis directly and get the upper limit in the most simple way:
n=0
while (n+1)**2-n*n<=168:
n+=1
print(n+1)
----------
85
The idea is that the worst result would be a difference of 168 between n squares and (n+1) squares, which, because of their relationship, cannot exist at any greater gap than this. As to whether or not they are completely squares, the simplest way to judge is by 0 decimal places in square root.
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)
Example 004: Days of the day
Title Enter the day of a certain year, and judge that day as the first day of the year?
Analysis of procedures In exceptional circumstances, the year is to be considered for an additional day in 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)
Example 005: Sorting of three digits
Title Enter three integers x, y, z. Please insert these three numbers from small to large.
Analysis of procedures You know, you just find a sort of algorithm to get it done and you’re lazy and you just switch functions.
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))
Example 006: Fibonacci series
Title Fibonacci series.
Analysis of procedures Fibonaci sequence, starting with 1, 1 and each of which is equal to the sum of the first two. The ease of return is realized, and the performance of the diagrams is circular.
# 递归实现
def Fib(n):
return 1 if n<=2 else Fib(n-1)+Fib(n-2)
print(Fib(int(input())))
# 朴素实现
target=int(input())
res=0
a,b=1,1
for i in range(target-1):
a,b=b,a+b
print(a)
Example 007:copy
Title Copys the data from one list to another.
Analysis of procedures Use the list [:] to unable access the copy module.
import copy
a = [1,2,3,4,['a','b']]
b = a # 赋值
c = a[:] # 浅拷贝
d = copy.copy(a) # 浅拷贝
e = copy.deepcopy(a) # 深拷贝
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']]
Example 008: 999 Multiplication Table
Title Output 9*9 multiplication machine table.
Analysis of procedures Lines and columns are considered for a total of 9 rows, i control rows, j control column.
for i in range(1,10):
for j in range(1,i+1):
print('%d*%d=%2ld '%(i,j,i*j),end='')
print()
Example 009: Pause output for one second
Title Pause the output for one second.
Analysis of procedures The sleep() function with the time module.
import time
for i in range(4):
print(str(int(time.time()))[-2:])
time.sleep(1)
Example 010: Time for people to see
Title Pauses the output for one second and formats the current time.
Analysis of procedures 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)
Example 011: Rabbits
Title There’s a pair of rabbits that have been born every month since the third month of life, and a pair of rabbits growing up until the third month. If they don’t die, ask what the total number of rabbits is per month.
Analysis of procedures I think the solution to the original text is a little ludicrous: how do people or babies have children without taking into account three months of maturity? Given that three months of maturity, four data can be constructed: January rabbits grow up every month as February rabbits, February rabbits become March rabbits, and adult rabbits (including newly mature three months rabbits) are born as January rabbits.
month=int(input('繁殖几个月?: '))
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('第%d个月共'%(i+1),month_1+month_2+month_3+month_elder,'对兔子')
print('其中1月兔:',month_1)
print('其中2月兔:',month_2)
print('其中3月兔:',month_3)
print('其中成年兔:',month_elder)
Example 012: 100 to 200 prime figures
Title Determines how many prime numbers are between 101 and 200, and output all.
Analysis of procedures The method of determining the prime numbers: removing from sqrt (this number) a single number, if it can be severed, shows that this number is not a base figure, but rather a base figure. Use else can further simplify the code.
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)
Example 013: All daffodils
Title Prints all “the number of daffodils,” which means a three-digit number, and the numbers are squared and equal to that number itself. For example: 153 is a “faffage number”, because 153 = 1 x 3 + 5 x 3.
Analysis of procedures Control of 100-999 digits using foror circulation, deciphering one place, ten places and hundreds.
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)
Example 014: Decomposition factor
Title Dissolves an integer factor. For example, enter 90 and print out 90 = 2.33*5。
Analysis of procedures There is no need to judge whether or not it is a prime number, going from 2 to the number itself, and it must be the smallest prime number that can be eliminated.
target=int(input('输入一个整数:'))
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
Example 015: Score Archive
Title Use the encoder of condition operators to do this: learning achievement>= 90 points in class, A, 60-89 points in B and less than C.
Analysis of procedures It’s good to judge by the terms.
points=int(input('输入分数:'))
if points>=90:
grade='A'
elif points<60:
grade='C'
else:
grade='B'
print(grade)
Example 016: Output date
Title Output specifies the date of the format.
Analysis of procedures Use the 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)
Example 017: String Composition
Title Enter the number of letters, spaces, numbers and other characters in a row that you want to count.
Analysis of procedures Using a while or for statement, the condition is not ⁇ n.
string=input("输入字符串:")
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)
Example 018: Repeater added
Title s = a+aa+aaa+aaa+aaa…a of which a is a number. For example, 2+22+222+2222222 (at this time there are 5 numbers added), several additions are controlled by keyboard.
Analysis of procedures Use a string to solve it.
a=input('被加数字:')
n=int(input('加几次?:'))
res=0
for i in range(n):
res+=int(a)
a+=a[0]
print('结果是:',res)
Example 019: Finish
Title If a number exactly equals the sum of its factors, it is called “complete.” For example, 6=1+2+3. Programming finds all of them within 1,000.
Analysis of procedures Each pair of factors is added to the pool, and has been automatically weighed in this process. The final result requires that it not be counted 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)
Example 020: High-air parabolics
Title One ball falls freely from 100 metres and then jumps back half of the altitude; then drops again, asking how many meters did it pass when it landed 10th time? How high was the tenth rebound?
Analysis of procedures None
high=200.
total=100
for i in range(10):
high/=2
total+=high
print(high/2)
print('总长:',total)
Example 021: Monkeys steal peaches
Title Monkeys eat peaches on the first day: monkeys take a few peaches, half of which are not addicted to eating, and one more day eats the rest of the peaches in the morning, and then another. Then every morning they eat the other half and one of the other ones. When they want to eat again on the tenth morning, there is only one peach left. Ask how much was picked together on the first day.
Analysis of procedures Inversely, the monkey had a peach and he stole a peach. He didn’t think it was enough to steal the same amount of peach in his hand for nine days.
peach=1
for i in range(9):
peach=(peach+1)*2
print(peach)
Example 022: Competing opponent
Title Two ping-pong teams play three games each. Team A is a, b, c, and team B is x, y, z. The list has been drawn by lot. Someone asked the players about the list.a says he doesn’t match x,c says he isn’t match x,z, so make up a program to find out the names of the three teams.
Analysis of procedures It is sufficient to find three opponents who do not repeat under the conditions.
a=set(['x','y','z'])
b=set(['x','y','z'])
c=set(['x','y','z'])
c-=set(('x','z'))
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))
Example 023: Scratch
Title Prints the following pattern (roar):
*
***
*****
*******
*****
***
*
Analysis of procedures Recursive call is sufficient.
def draw(num):
a="*"*(2*(4-num)+1)
print(a.center(9,' '))
if num!=1:
draw(num-1)
print(a.center(9,' '))
draw(4)
Example 024: Fibonacci series II
Title A series of fractions: 2/1, 3/2, 5/3, 8/5, 13/8, 21/13… Summarized the top 20 items in this column.
Analysis of procedures It’s the last of the Fibonacci series 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)
Example 025: Factorial Sum
Title 1+2! +3! +…+20!
Analysis of procedures 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)
Example 026: Retrogression factor multiplier
Title Retrogressively requested 5!
Analysis of procedures Recursive call is sufficient.
def factorial(n):
return n*factorial(n-1) if n>1 else 1
print(factorial(5))
Example 027: Recursive output
Title Prints the five characters you entered in reverse order using a recursive function to call.
Analysis of procedures Retrogression is a stupid way.
def rec(string):
if len(string)!=1:
rec(string[1:])
print(string[0],end='')
rec(input('string here:'))
Example 028: Retrogression Parity Column
Title Five people sat together and asked how old the fifth person was? He said that he was two years older than the fourth. Ask him four, he said two years older than the third. Ask him a third, and say two years older than the second. Ask him two years older than the first. Finally, ask the first one, what is the fifth?
Analysis of procedures It’s just a first-class range.
def age(n):
if n==1:
return 10
return 2+age(n-1)
print(age(5))
Example 029: Inverse output
Title Give a positive integer number of no more than five places, and request: first, if it’s several numbers, second, reverse to print out your numbers.
Analysis of procedures Learn to break out every number, and it’s always cheaper using strings.
n=int(input('输入一个正整数:'))
n=str(n)
print('%d位数'%len(n))
print(n[::-1])
Example 030: Number of replies
Title A five-digit number to determine whether it is the number of returns. That’s 12321, which is the number of returns, each one being the same as 10,000 and ten being the same as thousands.
Analysis of procedures It is easier to use a string, even if the number is not entered.
n=input("随便你输入啥啦:")
a=0
b=len(n)-1
flag=True
while a<b:
if n[a]!=n[b]:
print('不是回文串')
flag=False
break
a,b=a+1,b-1
if flag:
print('是回文串')
Example 031: Alphabetical
Title Please enter the first letter of a week to judge a few days, and if the first letter is the same, continue to judge the second letter.
Analysis of procedures This is a dictionary that will put the relation directly in place.
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('请输入第一位字母:')).lower()]
if a==weekT or a==weekS:
print(a[str(input('请输入第二位字母:')).lower()])
else:
print(a)
Example 032: Inverse output II
Title Output the value of the list in the opposite order.
Analysis of procedures None.
a = ['one', 'two', 'three']
print(a[::-1])
Example 033: List-Turn String
Title Comma-separated list.
Analysis of procedures None.
L = [1,2,3,4,5]
print(','.join(str(n) for n in L))
Example 034: Call function
Title Practice function calls.
Analysis of procedures None.
def hello():
print('Hello World!')
def helloAgain():
for i in range(2):
hello()
if __name__=='__main__':
helloAgain()
Example 035: Set Output Colour
Title Text colour settings.
Analysis of procedures None.
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 + "警告的颜色字体?" + bcolors.ENDC)
Example 036: Numerical
Title Ask for a prime number within 100.
Analysis of procedures Use else to implement the fore-cycled incentive code (iffor is normal, not break).
lo=int(input('下限:'))
hi=int(input('上限:'))
for i in range(lo,hi+1):
if i > 1:
for j in range(2,i):
if (i % j) == 0:
break
else:
print(i)
Example 037: Sorting
Title Sort 10 figures.
Analysis of procedures Same example 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)
Example 038: sum of the diagonal array
Title Seeks the sum of the elements of a 3*3 matrix to the main angle.
Analysis of procedures None.
mat=[[1,2,3],
[3,4,5],
[4,5,6]
]
res=0
for i in range(len(mat)):
res+=mat[i][i]
print(res)
Example 039: Arranged list for insertion of elements
Title There is an array that has been sequenced. Enter a number which you want to insert into the array according to the usual pattern.
Analysis of procedures First, to determine whether this number is greater than the last number and then to consider the insertion of a number in the middle, the number after the insertion of the element, and then one position later.
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)
Example 040: Inverse Sequence Table
Title Output of an array in reverse order.
Analysis of procedures Swaps the position in turn, or directly calls the 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('第一种实现:')
print(lis)
lis=[1,10,100,1000,10000,100000]
print('第二种实现:')
lis.reverse()
print(lis)
Example 041: Methods and variables for categories
Title imitation of the use of static variables.
Analysis of procedures Construct the class, understand the method and variables of the 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()
Example 042: Variable action area
Title Learn to define the use of variables using auto.
Analysis of procedures The variable field in python.
i=0
n=0
def dummy():
i=0
print(i)
i+=1
def dummy2():
global n
print(n)
n+=1
print('函数内部的同名变量')
for j in range(20):
print(i)
dummy()
i+=1
print('global声明同名变量')
for k in range(20):
print(n)
dummy2()
n+=10
Example 043: Scopes, Category Methods and Variables
Title Imitation of static variable (static) in another case.
Analysis of procedures Consolidated examples 041 and 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()
Example 044: Matrix added
Title Computes two arrays that add up.
Analysis of procedures Creates a new matrix, uses for an iterative and removes the values of the corresponding positions in the X and Y matrices, adding them to the corresponding position in the new array.
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)
Example 045: Summation
Title Statistics 1 to 100 times the sum.
Analysis of procedures None
res=0
for i in range(1,101):
res+=i
print(res)
Example 046: Breaking the cycle
Title To enter the square of a number, exit if less than 50 is calculated on the square.
Analysis of procedures None
while True:
try:
n=float(input('输入一个数字:'))
except:
print('输入错误')
continue
dn=n**2
print('其平方为:',dn)
if dn<50:
print('平方小于50,退出')
break
Example 047: Function exchange variables
Title The two variables are swapped with functions.
Analysis of procedures None
def exc(a,b):
return (b,a)
a=0
b=10
a,b=exc(a,b)
print(a,b)
Example 048: Numbers vs. Size
Title Number comparison.
Analysis of procedures None
a=int(input('a='))
b=int(input('b='))
if a<b:
print('a<b')
elif a>b:
print('a>b')
else:
print('a=b')
Example 049:lambda
Title Uselambda to create an anonymous function.
Analysis of procedures None
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))
Example 050: Random number
Title Output a random number.
Analysis of procedures Use the Randall module.
import random
print(random.uniform(10,20))
Example 051: By
Title Learning to use place-to-place & 。
Analysis of procedures 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)
Example 052: By Bit or
Title Learn to use bitwise or molybdenum.
Analysis of procedures 0|0=0; 0|1=1; 1|0=1; 1|1=1
a=0o77
print(a|3)
print(a|3|7)
Example 053: Differing or
Title Learn to use a bitwise or ⁇ .
Analysis of procedures 0^0=0; 0^1=1; 1^0=1; 1^1=0
a=0o77
print(a^3)
print(a^3^7)
Example 054: Inverse and shift
Title Take an integer a 4 ⁇ 7 bit from the right.
Analysis of procedures This can be considered: (1) to move a four-bit right first. (2) to set the number of one low of four full 1 and the rest all 0 available.(0<<4) (3) Conduct both above&Operating.
a=int(input('输入一个数字: '))
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))
Example 055: Inverted in place
Title Learn to use bitwise reverses.
Analysis of procedures ~0=1; ~1=0;
print(~234)
print(~~234)
Example 056: Circles
Title Draw, learn to use a circle of Circle.
Analysis of procedures None.
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()
Example 057: Painting line
Title Draw, use line to draw straight lines.
Analysis of procedures None.
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()
Example 058: Draw Rectangle
Title Draw, learn to draw squares with rectangle.
Analysis of procedures None.
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()
Example 059: Drawing (b)
Title Painting, composite example.
Analysis of procedures 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()
Example 060: String Length
Title Calculates the length of a string.
Analysis of procedures None.
s='zhangguang101'
print(len(s))
Example 061: Yang Fai Triangle
Title Prints the top ten lines of the Yang Fai triangle.
Analysis of procedures None.
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)
Example 062: Find Strings
Title Finds a string.
Analysis of procedures None.
s1='aabbxuebixuebi'
s2='ab'
s3='xue'
print(s1.find(s2))
print(s1.find(s3))
Example 063: Draw Ellipse
Title Draw an ellipse.
Analysis of procedures 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()
Example 064: Draw ellipse, rectangle
Title Draws drawings using ellipse and rectangle.
Analysis of procedures None.
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()
Example 065: Draw a combination of graphics
Title The most beautiful pattern.
Analysis of procedures None.
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()
Example 066: Sorting of three digits
Title Enter three digitsa,b,c in size order.
Analysis of procedures Same example 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))
Example 067: Exchange location
Title Enter an array, the largest for the first element, the smallest for the last element, and the output array.
Analysis of procedures None.
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)
Example 068: Rotation Columns
Title There are n integers, moving the order of numbers ahead backwards to m and finally m to m at the top.
Analysis of procedures None.
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))
Example 069: Counting
Title There are n-persons in a circle, with sequenced numbers. From the first person to report (from 1 to 3), those who report to three exit from the circle and ask what was left of the original number.
Analysis of procedures None.
if __name__ == '__main__':
nmax = 50
n = int(input('请输入总人数:'))
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])
Example 070: String length II
Title Writes a function that seeks the length of a string, enters a string in the Main function and output its length.
Analysis of procedures None.
def lenofstr(s):
return len(s)
print(lenofstr('tanxiaofengsheng'))
Example 071: Input and Output
Title Enter the input() and output() functions, output data records for five students.
Analysis of procedures None.
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)
Example 072: Create Chain
Title Creates a chain table.
Analysis of procedures It’s not very authentic.
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("给定位置不合理")
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("插入结点位置不合理")
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))
Example 073: Reverse Export Chain Table
Title Inversely output a chain table.
Analysis of procedures None.
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("给定位置不合理")
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("插入结点位置不合理")
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)))
Example 074: List Sorting, Connecting
Title list and connect.
Analysis of procedures Sorts can use the sort() method and connect with the + number or the extend() method.
a=[2,6,8]
b=[7,0,4]
a.extend(b)
a.sort()
print(a)
Example 075: Ignorance
Title Relax, it’s a simple title.
Analysis of procedures Ghost knows what it is.
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)
Example 076: Perform function
Title Write a function, enter n an even number and call the function for 1/2+1/4+… +1/n and when n is odd, call the function 1/1+1/3+… +1/n
Analysis of procedures None.
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)
Example 077: List of Walking Through
Title Cyclical Output List
Analysis of procedures None.
l=['moyu','niupi','xuecaibichi','shengfaji','42']
for i in range(len(l)):
print(l[i])
Example 078: Dictionary
Title Find the oldest person and output. Find out what’s wrong with the program.
Analysis of procedures None.
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]))
Example 079: String Sorting
Title String sorting.
Analysis of procedures None.
l=['baaa','aaab','aaba','aaaa','abaa']
l.sort()
print(l)
Example 080: Monkey split peaches
Title There are peaches on the beach, divided by five monkeys. The first monkey split them into five and one more, and this monkey threw another of them in the sea, and took one. The second monkey split the remaining peaches into five and then another, and it throws the other one into the sea, and takes one. This is what the third, fourth, fifth monkey did. Asks how many peaches were there on the beach?
Analysis of procedures None.
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)
Example 081: Unknown
Title The result is two digits, 9*?
Analysis of procedures None.
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
Example 082: Octahedron to Decimal
Title Convert octal to Decimal
Analysis of procedures None.
n=eval('0o'+str(int(input('八进制输入:'))))
print(n)
Example 083: Production odd
Title Asking for odd numbers that can be formed by 0-7.
Analysis of procedures
The first one is not 0 and the third is 7*8*4. In the middle, the fourth is 7*8*8*4.
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)
Example 084: Connect String
Title Connects a string.
Analysis of procedures None.
delimiter = ','
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))
Example 085: Dissociation
Title Enter an odd number, and then judge at least a few 9 divided by that number with the result being integer.
Analysis of procedures 999999 / 13 = 76923。
if __name__ == '__main__':
zi = int(input('输入一个数字:'))
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 个 9 可以被 %d 整除 : %d' % (c9,zi,sum))
r = sum / zi
print ('%d / %d = %d' % (sum,zi,r))
Example 086: Connection string II
Title Two string connectors.
Analysis of procedures None.
a='guangtou'
b='feipang'
print(b+a)
Example 087: Visiting category members
Title Answer the result (structure variable transmission).
Analysis of procedures None.
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)
Example 088: Print asterisk
Title Reads the integer value of seven numbers (1-50), and for each value read, the program prints* of that number.
Analysis of procedures None.
for i in range(3):
print('*'*int(input('input a number: ')))
Example 089: Decoding
Title A company uses a public telephone to transmit data, which is four-digit integer number and is encrypted during the transmission process. The encryption rules are as follows: add five for each number, then replace that figure with the balance of 10 divided, then exchange first and fourth, and second and third.
Analysis of procedures None.
n=input()
n = str(n)
a=[]
for i in range(4):
a.append((int(n[i])+5)%10)
a[0],a[3]=a[3],a[0]
a[1],a[2]=a[2],a[1]
print ("".join('%s' %s for s in a))
Example 090: List details
Title list.
Analysis of procedures None.
#list
#新建列表
testList=[10086,'中国移动',[1,2,4,5]]
#访问列表长度
print (len(testList) )
#到列表结尾
print (testList[1:])
#向列表添加元素
testList.append('i\'m new here!')
print (len(testList) )
print (testList[-1] )
#弹出列表的最后一个元素
print (testList.pop(1) )
print (len(testList) )
print (testList )
#list comprehension
#后面有介绍,暂时掠过
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)
Example 091:time module
Title Example 1 of the time function.
Analysis of procedures None.
if __name__ == '__main__':
import time
print (time.ctime(time.time()))
print (time.asctime(time.localtime(time.time())))
print (time.asctime(time.gmtime(time.time())))
Example 092:time module II
Title Example 2 of the time function.
Analysis of procedures How waste of time.
if __name__ == '__main__':
import time
start = time.time()
for i in range(3000):
print(i)
end = time.time()
print (end - start)
Example 093:time Module III
Title Example 3 of the time function.
Analysis of procedures How waste of 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))
Example 094:time Module IV
Title Example 4 of the time function.
Analysis of procedures How waste of 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.')
Example 095: Conversion time format
Title String dates are converted to readable date formats.
Analysis of procedures Look at it. Datatil is a third-party library.
from dateutil import parser
dt = parser.parse("Aug 28 2015 12:00AM")
print (dt)
Example 096: Calculate the number of times read again
Title Calculates the number of times a string neutron string appears.
Analysis of procedures None.
s1='xuebixuebixuebixuebixuebixuebixuebixue'
s2='xuebi'
print(s1.count(s2))
Example 097: Disk Writing
Title Enter some characters from the keyboard and write them to disk files one by one until you enter a #.
Analysis of procedures None.
if __name__ == '__main__':
from sys import stdout
filename = input('输入文件名:\n')
fp = open(filename,"w")
ch = input('输入字符串:\n')
while ch != '#':
fp.write(ch)
stdout.write(ch)
ch = input('')
fp.close()
Example 098: Disk Writing II
Title Enter a string from the keyboard that converts all lowercase letters to uppercase letters, and then output them to a disk file “test”.
Analysis of procedures None.
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()
Example 099: Disk reading and writing
Title There are two disk files A and B, each of which is stored in a row of letters, requesting that the information from both files be combined (in alphabetical order) for output to a new document C.
Analysis of procedures None.
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()
Example 100: List transword dictionary
Title list.
Analysis of procedures None.
i = ['a', 'b']
l = [1, 2]
print (dict(zip(i,l)))
End!
未经允许不得转载:萌萌Apprentissage » 100 examples of python
Python batches to extract mainstream search engine pictures
Python's word crawling across 100 degrees.
PythonTaiichi Taipei Artificial Intelligence Tensoflow Graphic Processing
Selenium with Tor Browser using Python
I'm gonna get you a new one, shell.cloud.google on the line.