Example 001: Combination of numbers
** Title: ** has four numbers: 1, 2, 3, 4. How many different and non-repeating three-digit numbers can be formed? What are they?
** Program analysis: ** traverses all possibilities, shaving off duplicates.
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)Copy the code
** Easy method: ** use Permutations in itertools.
Import itertools sum2=0 a=[1,2,3,4] for I in itertools. Permutations (a,3): print(I) sum2+=1 print(sum2)Copy the code
Example 002: “Individual Income Tax Calculation”
** The bonus paid by the enterprise is based on the profit commission. When profit (I) is less than or equal to 100,000 yuan, 10% of bonus can be raised; If the profit is higher than 100,000 yuan, the part below 100,000 yuan will be 10% commission, and the part above 100,000 yuan will be 7.5% commission. Between 200,000 and 400,000 yuan, the part higher than 200,000 yuan, can be 5% commission; Between 400,000 and 600,000, the part higher than 400,000 yuan, can be 3% commission; When arrive between 600 thousand and 1 million, prep above 600 thousand yuan part, can commission 1.5%, prep above 1 million yuan when, the part of more than 1 million yuan presses 1% commission, input that month profit I from the keyboard, beg should extend bonus total amount?
** program analysis: ** partition can be calculated.
profit=int(input('Show me the money: ')) bonus = 0 thresholds = [100000100, 000200, 000200, 000400, 000] 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)Copy the code
Example 003: Perfect squares
** An integer is a perfect square when added to 100. 168 is a perfect square when added to 168.
** Because 168 is too small for exponential explosions, we can omit the mathematical analysis and use the simplest method to obtain the upper limit:
n=0
while (n+1)**2-n*n<=168:
n+=1
print(n+1)
----------
85
Copy the code
The idea is: the worst possible result is that n squared is exactly 168 different from (n+1) squared, and since it’s a square, you can’t have a bigger gap than that. The easiest way to determine if a square is a perfect square is to have the square root as a decimal value of 0. Combine:
N = 0, while 2 - (n + 1) * * n * n < = 168: n + = 1 for I in range (2) (n + 1) * * : if I * * 0.5 = = int * * 0.5 (I) and (I + 168) * * 0.5 = = int (0.5) (I + 168) * * : print(i-100)Copy the code
Example 004: The day of the day
**题目 : ** enter x date x date, judge this day is the day of the year.
** In special cases, an extra day in February is required for leap year:
def isLeapYear(y): return (y%400==0 or (y%4==0 and y%100! ,31,28,31,30,31,30,31,31,30,31,30 DofM = = 0)) [0] res = 0 year = int (input (' year: ')) the month = int (input (' the month:)) day=int(input('day:')) if isLeapYear(year): DofM[2]+=1 for i in range(month): res+=DofM[i] print(res+day)Copy the code
Example 005: Three-digit sort
** Input three integers x,y,z, please output these three numbers from the smallest to the largest.
** program analysis: ** practice hand just find a sorting algorithm to achieve it, lazy directly tune function.
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))
Copy the code
Example 006: Fibonacci sequence
** Title: ** Fibonacci sequence.
** Fibonacci sequence, starting from 1,1, each subsequent term equals the sum of the preceding two terms. Graph convenient recursive implementation, graph performance with a cycle.
Def Fib(n): Return 1 if n<=2 else Fib(n-1)+Fib(n-2) print(Fib(int(input()))) # plain implement target=int(input())) res=0 a,b=1,1 for I in range(target-1): a,b=b,a+b print(a)Copy the code
Example 007: copy
** Title: ** Copy data from one list to another.
** Program analysis: ** use list [:], uncertain can call copy module.
Import copy a = [1,2,3,4,['a','b']] b = a # assignment c = a[:] # shallow copy d = copy.copy(a) # shallow copy 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']]Copy the code
Example 008: The multiplication table
** Title: ** Output 9*9 multiplication table.
** Program analysis: ** branch and column consideration, a total of 9 rows and 9 columns, I control row, J control column.
For I in range (1, 10) : for j in range (1, I + 1) : print (' * % d = % d % 2 ld '% (I, j, I * j), end =' ') print ()Copy the code
Example 009: Pause output for one second
** Title: ** Pause output for one second.
** Program analysis: ** Use the sleep() function of the time module.
import time
for i in range(4):
print(str(int(time.time()))[-2:])
time.sleep(1)
Copy the code
Example 010: Show time
** Title: ** Pause output for a second and format the current time.
** program analysis: ** the 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)
Copy the code
Example 011: Raising rabbits
** title: ** there are a pair of rabbits, from the birth of the third month from every month a pair of rabbits, rabbit children grow to the third month after every month and a pair of rabbits, if rabbits are not dead, ask the total number of rabbits every month for how many?
** I think the solution of the original is a bit ridiculous, did not consider the problem of 3 months of maturity, people or babies how to give birth to children? Considering the maturity of three months, four data can be constructed, where: January rabbits grow into February rabbits every month, February rabbits turn into March rabbits, March rabbits turn into adult rabbits, and adults (including newly mature March rabbits) have the same number of 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 (' month_1+month_2+month_3+month_elder,') print(' month_1: ',month_1: ') ',month_2) print(' month_elder ')Copy the code
Example 012: Primes from 100 to 200
** Determine how many primes there are between 101 and 200 and print all primes.
** Program analysis: ** Judge the method of prime number: use a number to remove 2 to SQRT (this number), if it can be divisible, it indicates that this number is not prime, and vice versa.
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)Copy the code
Example 013: Number of all daffodils
** Title: ** Print out all the daffodil numbers. The daffodil number is a three-digit number whose cube sum equals the number itself. For example, 153 is a “daffodil number” because 153=1 ^ 3 +5 ^ 3 +3 ^ 3.
** Program analysis: ** uses the for loop to control 100-999 numbers, each number decomposed into ones, tens, hundreds.
For I in range (100100) : s = STR (I) one = int [1] (s) ten = int [2] (s) hun = int [3] (s) if I = = one 3 + 3 + ten * * * * hun * * 3: print (I)Copy the code
Example 014: Factoring prime factors
** Decompose an integer into its prime factors. For example, enter 90 and print 90=233*5.
** program analysis: ** does not need to judge whether it is prime at all, from 2 to the number itself traversal, can be divisible must be the smallest prime number.
Print (target,'= ',end=') 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 breakCopy the code
Example 015: Score archiving
Students with scores >=90 are represented by A, those between 60 and 89 are represented by B, and those below 60 are represented by C.
** program analysis: ** can be determined by conditions.
Points =int(input(' input: ')) if points>=90: grade='A' elif points<60: grade='C' else: grade='B' print(grade)Copy the code
Example 016: Output date
** Title: ** Prints the date in the specified format.
** Program analysis: ** Use datetime module.
Import a datetime print (datetime. Date. Today ()) print (datetime. Date (2333, 2, 3)) Print (datetime. Date. Today (). The strftime (' % % % d/m/Y)) day = a datetime. Date (1111, 2, 3) day = day. Replace (year = day. Year + 22) print(day)Copy the code
Example 017: String composition
Enter a line of characters and count the number of letters, Spaces, digits, and other characters.
** Program analysis: ** use while or for statements, as long as the input character is not ‘\n’.
String =input(" input string: ") alp=0 num=0 spa=0 oth=0 for 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)Copy the code
Example 018: Add the repeater
S =a+aa+aaa+aaaa+aa… The value of a, where a is a number. For example, 2+22+222+2222+22222(a total of 5 numbers are added), and the addition of several numbers is controlled by the keyboard.
** program analysis: ** with string solution.
A =input(' input ') n=int(' input ') : ')) res=0 for I in range(n): res+=int(a) a+=a[0] print('Copy the code
Example 019: Complete
A number that is exactly equal to the sum of its factors is called a perfect number. For example, 6=1+2+3. Program to find all completions up to 1000.
** Program analysis: ** adds each pair of factors to the set, automatically deduplicating in the process. The final result requires no calculation of 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)Copy the code
Example 020: Projectile from high altitude
** A ball falls from a height of 100 meters and bounces back to half of its original height after each landing; And when it lands again, how many meters does it travel on the 10th landing? How high is the 10th bounce?
** program analysis: ** none
High =200. Total =100 for I in range(10): high/=2 total+=high print(high/2) print(total)Copy the code
Example 021: Monkey steals peach
** Title: ** Monkeys eat peaches problem: the first day the monkey picked a number of peaches, immediately eat half, not addiction, and eat one more the next morning and eat the rest of the peach half, and eat one more. For the rest of the day, I ate half and one each morning. In the morning of the 10th day, when I wanted to eat again, THERE was only one peach left. How much did you pick the first day?
** Program analysis: ** Reverse inference according to the rules: the monkey has a peach, he stole a peach, feel that is not enough to steal the same amount of peaches with the hand, a total of 9 days of stealing.
peach=1
for i in range(9):
peach=(peach+1)*2
print(peach)
Copy the code
Example 022: Match opponent
** Two ping-pong teams are playing a match of three players each. Team A consists of a, B and C, and team B consists of X, Y and Z. The list of players has been drawn. The players were asked for the match list. A says he doesn’t compete with X, C says he doesn’t compete with X and Z. Please program to find out the names of the three teams.
** Program analysis: ** find conditions under the three opponents can not repeat.
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))
Copy the code
Example 023: Draw a diamond
** Title: ** Print the following pattern (diamond) :
* *** ***** ******* ***** *** *
** program analysis: ** recursive 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)Copy the code
Example 024: Fibonacci sequence II
** Title: ** has a sequence of fractions: 2/1, 3/2, 5/3, 8/5, 13/8, 21/13… Find the sum of the first 20 terms in this sequence.
** program analysis: ** is the last term of the Fibonacci sequence divided by the previous term.
A = 2.0b = 1.0s = 0 for n in range(1,21): s += a/b a,b = a + b,a print (s)Copy the code
Example 025: Factorial summation
** = 1+2! + 3! +… + 20! And.
**1+2! + 3! +… + 20! (1 = 1 + 2 + 3 (1 + 4 (… 20 (1))))
Res =1 for I in range(20,1,-1): res= I *res+1 print(res)Copy the code
Example 026: Recursive factorial
** Title: ** Use recursive method to find 5! .
** program analysis: ** recursive call.
def factorial(n):
return n*factorial(n-1) if n>1 else 1
print(factorial(5))
Copy the code
Example 027: Recursive output
** Print out the 5 characters typed in reverse order using recursive function calls.
Program analysis: recursion is stupid.
def rec(string): if len(string)! =1: rec(string[1:]) print(string[0],end='') rec(input('string here:'))Copy the code
Example 028: Recursive arithmetic sequence
Five people are sitting together. How old is the fifth person? He said he was two years older than the fourth. Asked how old the fourth man was, he said he was two years older than the third. He asked the third man and said he was two years older than the second. Ask the second person and say he is two years older than the first person. Finally asked the first man, he said 10. How old is the fifth, please?
** program analysis: ** on an arithmetic sequence.
def age(n):
if n==1:
return 10
return 2+age(n-1)
print(age(5))
Copy the code
Example 029: Reverse output
** Given a positive integer of not more than 5 digits, the requirements are: 1, find how many digits it is, 2, reverse print the digits.
** program analysis: ** learn to decompose each digit, using the string method is always easier.
N = int (input (' enter a positive integer: ')) n = STR (n) print (' % d digits' % len (n)) print (n] [: : - 1)Copy the code
Example 030: Palindrome number
** A 5 digit number, determine whether it is a palindrome number. That is, 12321 is a palindrome number, the ones place is the same as the thousands place, and the tens place is the same as the thousands place.
** program analysis: ** with strings more convenient, even if the input is not a number are OK.
N =input(" 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()Copy the code
Example 031: Letters recognize words
** Please enter the first letter of the week to determine the day of the week. If the first letter is the same, proceed to the second letter.
** program analysis: ** here in the form of a dictionary will directly save the comparison relationship.
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:)). The lower ()] if a = = weekT or a = = weekes: Print (a [STR (input (' please enter the second letter:)). The lower ()]) else: print (a)Copy the code
Example 032: Reverse output II
** Title: ** Prints the values of the list in reverse order.
** program analysis: ** none
a = ['one', 'two', 'three']
print(a[::-1])
Copy the code
Example 033: List-to-string
** Topics: ** Comma-separated list.
** program analysis: ** none
L = [1, 2, 3, 4, 5] print (', '. Join (STR (n) for n in L))Copy the code
Example 034: Calling a function
** Title: ** Practice function calls.
** program analysis: ** none
def hello(): print('Hello World! ') def helloAgain(): for i in range(2): hello() if __name__=='__main__': helloAgain()Copy the code
Example 035: Set the output color
** Title: ** Text color Settings.
** program analysis: ** 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.Copy the code
Example 036: Compute prime numbers
** Title: ** find prime numbers within 100.
** Program analysis: ** Execute the reward code for loop with else (if for ends normally, not break).
Lo =int(input(' low: ')) hi=int(input(' low: ')) for I in range(lo,hi+1): if I > 1: for j in range(2, I): if (I % j) == 0: break else: print(i)Copy the code
Example 037: Sort
** Sort 10 numbers.
** program analysis: ** the same as 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)
Copy the code
Example 038: Sum of diagonals of matrix
Find the sum of the principal diagonal elements of a 3*3 matrix.
** program analysis: ** none
Mat = [[1, 2, 3], [three, four, five], [4 and 6]] res = 0 for I in range (len (mat) : res + = mat [I] [I] print (res)Copy the code
Example 039: Ordered list inserts elements
** Title: ** has an sorted array. Now enter a number and insert it into the array as usual.
** program analysis: ** first judge whether this number is greater than the last number, and then consider the case of inserting the middle number, after the insertion of this element after the number, one position later.
,10,100,1000,10000,100000 lis = [1] 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)Copy the code
Example 040: Reverse list
** Print an array in reverse order.
** Program analysis: ** switch positions in turn, or call the reverse method directly.
,10,100,1000,10000,100000 lis = [1] for I in range (int (len (lis) / 2)) : The lis [I], lis [len (lis) - 1 - I] = lis [len (lis) - 1 - I], lis [I] print (' the first implementation: ') print (lis) lis =,10,100,1000,10000,100000 [1] print (' the second implementation: ') lis. Reverse () print (lis)Copy the code
Example 041: Class methods and variables
** Mimics the use of static variables.
** Program analysis: ** construct class, understand the methods and variables of 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()
Copy the code
Example 042: Variable scope
Learn how to use auto to define the use of variables.
** Program analysis: ** Variable scope in Python.
I = 0 n = 0 def dummy () : I = 0 print (I) (I) + = 1 def dummy2 () : global n print (n) n + = 1 print (' function internal variable of the same name) for j in range (20) : Print (I) dummy() I +=1 print('global ') for k in range(20): print(n) dummy2() n+=10Copy the code
Example 043: Scope, class methods, and variables
Another example of mimicking a static variable
** Program analysis: ** Synthesis of example 041 and example 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()
Copy the code
Example 044: Matrix addition
** Title: ** Calculate the addition of two matrices.
** Program analysis: ** Create a new matrix, use for iteration and take the values of the corresponding positions in the X and Y matrices, add them together and put them into the corresponding positions in the new matrix.
,7,3 X = [[12], [4, 5, 6], [7, 8, 9]] Y = [,8,1 [5], [6,7,3], [4, 9]] res = [0, 0, 0, 0, [0, 0]] for I in range (len (res) : for j in range (len (res) [0]) : res [I] [j] [I] [j] = X + Y [I] [j] print (res)Copy the code
Example 045: Summation
** Title: ** Count the sum of 1 to 100.
** program analysis: ** none
Res =0 for I in range(1,101): res+= I print(res)Copy the code
Example 046: Breaking the cycle
** Square the input number. If the number is less than 50, exit.
** program analysis: ** none
While True: try: n=float(input(' enter a number: ') except: print(' enter a number: ') continue dn=n**2 print(' square: ',dn) if dn<50: Print (' square less than 50, exit ') breakCopy the code
Example 047: Functions swap variables
** The values of the two variables are interchangeable with functions.
** program analysis: ** none
def exc(a,b):
return (b,a)
a=0
b=10
a,b=exc(a,b)
print(a,b)
Copy the code
Example 048: Numeric ratio size
** Title: ** Comparison of numbers.
** program analysis: ** 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')
Copy the code
Example 049: lambda
** Title: ** Create anonymous functions using lambda.
** program analysis: ** 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))
Copy the code
Example 050: Random number
Output a random number.
** Program analysis: ** Uses the Random module.
Import the random print (random uniform (10, 20))Copy the code
Example 051: Bitwise and
** Topic: ** Learn to use bitwise and &.
** program analysis: **0&0=0; 1 = 0 0 &; 1 & 0 = 0; 1 and 1 = 1.
a=0o77
print(a)
b=a&3
print(b)
b=b&7
print(b)
Copy the code
Example 052: Bitwise or
Title: * * * * learn to use bitwise or |.
Program analysis: * * * * 0 | 0 = 0; 0 | 1 = 1; 1 | 0 = 1; 1 | = 1
a=0o77
print(a|3)
print(a|3|7)
Copy the code
Example 053: Bitwise xOR
** Topic: ** Learn to use bitwise xor ^.
**0^0=0; 0 ^ 1 = 1; 1 ^ 0 = 1; 1 ^ 1 = 0
a=0o77
print(a^3)
print(a^3^7)
Copy the code
Example 054: Bit reversal, bit shift
** Take an integer from 4 to 7 digits from the right end of a.
** Program analysis: ** can be considered as: (1) first move a to the right 4 bits. (2) set a number where the lower four bits are all 1s and the rest are all 0s. We can use ~(~0<<4) (3) to perform & on the above two.
A =int(input(' input 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))Copy the code
Example 055: Reverse by bit
** Title: ** Learn to use the reverse of the bit ~.
Program analysis: ~0=1; ~ 1 = 0;
print(~234)
print(~~234)
Copy the code
Example 056: Draw circles
** Topic: ** Draw pictures, learn to draw circles.
** program analysis: ** 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.3mainloop ()Copy the code
Example 057: Draw lines
** Title: ** Draw a picture, learn to draw a line with line.
** program analysis: ** 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()
Copy the code
Example 058: Draw a rectangle
I have a Rectangle to draw a picture.
** program analysis: ** 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()Copy the code
Example 059: Drawing (Ugly)
**题目 : ** draw a picture, 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()Copy the code
Example 060: String length
** Calculate the length of the string.
** program analysis: ** none
s='zhangguang101'
print(len(s))
Copy the code
Example 061: Yang Hui triangle
** Title: ** Print out the first ten lines of the Yang Hui triangle.
** program analysis: ** 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)
Copy the code
Example 062: Find the string
** Title: ** Find string.
** program analysis: ** none
s1='aabbxuebixuebi'
s2='ab'
s3='xue'
print(s1.find(s2))
print(s1.find(s3))
Copy the code
Example 063: Draw an ellipse
** Title: ** Draw an ellipse.
** Program analysis: ** Using 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()
Copy the code
Example 64: Draw ellipses and rectangles
Draw a picture using ellipse and rectangle.
** program analysis: ** 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 + left) canvas 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()Copy the code
Example 065: Draw composite graphics
** Title: ** A most beautiful design.
** program analysis: ** none
import math from tkinter import * class PTS: def __init__(self): self.x = 0 self.y = 0 points = [] def LineToDemo(): 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()Copy the code
Example 066: Three-digit sort
** Input 3 numbers A, B,c, in order of size output.
** program analysis: ** the same as 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))
Copy the code
Example 067: Switching places
Input array, swap the largest with the first element, swap the smallest with the last element, output array.
** program analysis: ** none
Li,2,5,7,8,1,5 li = [3] [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)Copy the code
Example 068: Rotate the sequence
** Has n integers, so that the preceding numbers move backward by m, and the last m number becomes the first M number
** program analysis: ** 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))Copy the code
Example 069: Count off
** Title: ** There are n people in a circle, in order of number. Count off from the first person (counting from 1 to 3). If the person reporting for 3 leaves the circle, ask who was left last.
** program analysis: ** none
If __name__ = = "__main__ ': nmax = 50 n = int (input (' please enter the total number of:')) 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])Copy the code
Example 070: String length II
Write a function to find the length of a string, enter the string in the main function, and print its length.
** program analysis: ** none
def lenofstr(s):
return len(s)
print(lenofstr('tanxiaofengsheng'))
Copy the code
Example 071: Input and output
** Write input() and output() function inputs to output 5 student data records.
** program analysis: ** 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)
Copy the code
Example 072: Creating a linked list
** Create a linked list.
** program analysis: ** the original is not quite 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 () 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(self.head cur_pos = 0) 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))Copy the code
Example 073: Reverse output linked list
** Title: ** Reverse output a linked list.
** program analysis: ** 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(self.head cur_pos = 0) 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)))Copy the code
Example 074: List sort, join
** title: ** list sort and join.
** Program analysis: ** sorts can use the sort() method, and joins can use the + sign or extend() method.
A =[2,6,8] b=[7,0,4] a. xtend(b) a print(a)Copy the code
Example 075: Unintelligible
** Relax and work out an easy problem.
** program analysis: ** who 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)Copy the code
Example 076: Make a function
** Write a function that, when n is even, calls 1/2+1/4+… +1/n, when the input n is odd, call the function 1/1+1/3+… +1/n
** program analysis: ** none
Def peven(n): I = 0 s = 0.0 for I in range(2,n + 1): s += 1.0 / I def podd(n): S = 0.0 for I in range(1, n + 1): 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)Copy the code
Example 077: Traversing the list
** title: ** loop output list
** program analysis: ** none
l=['moyu','niupi','xuecaibichi','shengfaji','42']
for i in range(len(l)):
print(l[i])
Copy the code
Example 078: Dictionary
** Find the oldest person and print it. Please find out what is wrong with the program.
** program analysis: ** 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]))
Copy the code
Example 079: String sort
** title: ** string sort.
** program analysis: ** none
l=['baaa','aaab','aaba','aaaa','abaa']
l.sort()
print(l)
Copy the code
Example 080: Monkeys divide peaches
There is a pile of peaches on the beach. Five monkeys divide them. The first monkey divided the pile of peaches into five equal parts, one too many, the monkey threw the extra one into the sea, took one. The second monkey divided the remaining peaches into five equally, and there was one more. He threw the one more into the sea and took one. The third, fourth and fifth monkeys did the same, asking how many peaches there were on the beach?
** program analysis: ** 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)Copy the code
Example 081: Finding unknowns
Topic: 809?? = 800?? + 9?? One?? The two-digit number that represents 809?? Is a four-digit number, 8*?? The result is double digit, 9*?? The result is 3 digits. O?? Represents two digits, and 809*?? After the results.
** program analysis: ** none
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 (10100) : 8 * if I > 99 or 9 * I < 100: the continue if I = = 809 * 800 * I + 9 * I: print(i) breakCopy the code
Example 082: Octal to decimal
** Convert octal to decimal
** program analysis: ** none
Eval ('0o'+ STR (int(input(' octal input: ')))) print(n))Copy the code
Example 083: Making an odd number
** Find the number of odd numbers that can be formed from 0 to 7.
Program analysis:
There are four digits that make up a digit number. 1 hc-positie end
The number that makes up the 2-digit number is 7 times 4. The first digit cannot be 0
The three-digit number is 784. In the middle at random
The four digits are 788 times 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)Copy the code
Example 084: Connection string
** Title: ** connection string.
** program analysis: ** none
delimiter = ','
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))
Copy the code
Example 085: Divisible
Enter an odd number and determine if at least nine divided by that number is an integer.
** 99999/13 = 76923.
If __name__ == '__main__': zi = int(input(' input a number :')) n1 = 1 c9 = 1 m9 = 9 sum = 9 while n1! If sum % zi == 0: n1 = 0 else: m9 *= 10 sum += m9 c9 += 1 print ('%d ') %d' % (c9,zi,sum)) r = sum / zi print ('%d / %d = %d' % (sum,zi,r))Copy the code
Example 086: Connection string II
** Title: ** Two string concatenators.
** program analysis: ** none
a='guangtou'
b='feipang'
print(b+a)
Copy the code
Example 087: Accessing class members
** Question: ** answer result (struct variable pass).
** program analysis: ** 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)
Copy the code
Example 088: Print an asterisk
For each value read, the program prints the * of that number.
** program analysis: ** none
for i in range(3):
print('*'*int(input('input a number: ')))
Copy the code
Example 089: Decoding
A company uses a public phone to transmit data. The data is a four-digit integer that is encrypted during transmission. The encryption rules are as follows: add 5 to each digit, replace it with the remainder of the sum divided by 10, and swap the first and fourth digits, and the second and third digits.
** program analysis: ** 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))
Copy the code
Example 090: List details
** title: ** list use examples.
** program analysis: ** none
Print (len(testList)) print (testList[1:]) print (testList[1:] testList.append('i\'m new here! Pop (1) print (len(testList)) print (testList[-1]) print (len(testList)) print (testList[-1] (testList) # List Comprehension Matrix = [[1, 2, 3], [4, 5, 6], 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)Copy the code
Example 091: Time module
** title: ** time function example 1.
** program analysis: ** 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())))
Copy the code
Example 092: Time module II
** title: ** time function example 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)
Copy the code
Example 093: Time module III
** title: ** time function example 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))Copy the code
Example 094: Time module IV
** title: ** time function example 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 = 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.')Copy the code
Example 095: Convert the time format
** Title: ** String date converted to readable date format.
Dateutil is a third-party library.
from dateutil import parser
dt = parser.parse("Aug 28 2015 12:00AM")
print (dt)
Copy the code
Example 096: Count the number of retries
** Count the number of neutrons in a string.
** program analysis: ** none
s1='xuebixuebixuebixuebixuebixuebixuebixue'
s2='xuebi'
print(s1.count(s2))
Copy the code
Example 097: Disk write
Type some characters from the keyboard and write them one by one to the disk file until you type a #.
** program analysis: ** none
if __name__ == '__main__': From sys import stdout filename = input(' input filename :\n') fp = open(filename,"w") ch = input(' input string :\n') while ch! = '#': fp.write(ch) stdout.write(ch) ch = input('') fp.close()Copy the code
Example 098: Disk write II
Input a string from the keyboard, convert all lowercase letters to uppercase letters, and output it to a disk file “test” for saving.
** program analysis: ** 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()
Copy the code
Example 099: Disk read and write
** There are two disk files A and B, each containing A row of letters, and the information in these two files is merged (in alphabetical order) into A new file C.
** program analysis: ** 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()
Copy the code
Example 100: List-to-dictionary
** title: ** lists are converted to dictionaries.
** program analysis: ** none
i = ['a', 'b']
l = [1, 2]
print (dict(zip(i,l)))
Copy the code
Python3.7, python-100-examples. Python3.7, python-100-examples
Author: RichardFu123 address: github.com/RichardFu12…