table of Contents
Example 001: Number combination
Example 002: "Individual tax calculation"
Example 003: Perfect square number
Example 004: The first few days of the day
Example 005: Three-number sort
Example 006: Fibonacci sequence
Example 007: copy
Example 008: Nine-Nine Multiplication Table
Example 009: Pause output for one second
Example 010: Time to show
Example 011: Raising a rabbit
Example 012: Prime numbers from 100 to 200
Example 013: Number of all daffodils
Example 014: Decompose prime factors
Example 015: Score archive
Example 016: Output date
Example 017: String composition
Example 018: Adding repeaters
Example 019: Finished counting
Example 020: Parabolic at high altitude
Example 021: Monkey steals peaches
Example 022: Competition opponent
Example 023: Draw a rhombus
Example 024: Fibonacci Sequence II
Example 025: Factorial summation
Example 026: Recursively find factorial
Example 027: Recursive output
Example 028: Recursive arithmetic sequence
Example 029: Reverse output
Example 030: Number of palindrome
Example 031: Letters to recognize words
Example 032: Reverse output II
Example 033: List to string
Example 034: Call function
Example 035: Set the output color
Example 036: Calculating prime numbers
Example 037: Sorting
Example 038: Sum of Diagonal Lines of Matrix
Example 039: Inserting an element in an ordered list
Example 040: Reverse sequence list
Example 041: Class methods and variables
Example 042: Variable scope
Example 043: Scope, class methods and variables
Example 044: Matrix addition
Example 045: Sum
Example 046: Break the loop
Example 047: Function exchange variables
Example 048: Number ratio size
Example 049: lambda
Example 050: random number
Example 051: Bitwise AND
Example 052: bitwise OR
Example 053: Bitwise XOR
Example 054: Bit inversion, bit shift
Example 055: Inverted by bit
Example 056: Draw a circle
Example 057: Draw a line
Example 058: Draw a rectangle
Example 059: Drawing (ugly)
Example 060: String length
Example 061: Yanghui Triangle
Example 062: Find a string
Example 063: Draw an ellipse
Example 064: Draw ellipse and rectangle
Example 065: Drawing combined graphics
Example 066: Three-number sort
Example 067: Exchange location
Example 068: Rotating sequence
Example 069: Report the number
Example 070: String length II
Example 071: Input and output
Example 072: Create a linked list
Example 073: Reverse output linked list
Example 074: List sorting, connection
Example 075: Incomprehensible
Example 076: Do a function
Example 077: Traverse the list
Example 078: Dictionary
Example 079: String sorting
Example 080: Monkey divides peaches
Example 081: Find the unknown
Example 082: octal to decimal
Example 083: Making odd numbers
Example 084: Connection string
Example 085: Divide
Example 086: Connection string II
Example 087: Access class members
Example 088: print asterisk
Example 089: Decoding
Example 090: Detailed list
Example 091: time module
Example 092: time module II
Example 093: time module III
Example 094: time module IV
Example 095: Convert time format
Example 096: Calculate the number of repeats
Example 097: Disk write
Example 098: Disk Write II
Example 099: Disk read and write
Example 100: List to dictionary
Due to the length of the space, only 25 questions and source codes are released. All questions and source codes are required to follow the editor, QQ group: 721195303 to receive.
Example 001: Number combination
There are four numbers in the question: 1, 2, 3, 4. How many different three-digit numbers can be formed without repeated numbers? What is each?
The program analyzes and traverses all the possibilities and shaves off the 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)
The easy way is to 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)
Example 002: "Individual tax calculation"
The bonus issued by the subject enterprise is based on the profit commission. When the profit (I) is less than or equal to 100,000 yuan, the bonus can be increased by 10%; when the profit is more than 100,000 yuan, and when the profit is less than 200,000 yuan, the portion of less than 100,000 yuan will be commissioned at 10%, which is higher than 100,000 yuan The commission is 7.5%; between 200,000 and 400,000, the part higher than 200,000 yuan can be commissioned 5%; between 400,000 and 600,000, the part higher than 400,000 yuan can be commissioned 3% ; Between 600,000 and 1 million, the portion above 600,000 yuan can be commissioned 1.5%, when it is more than 1 million yuan, the portion exceeding 1 million yuan will be commissioned at 1%. Enter the monthly profit I from the keyboard, and ask for it The total number of bonuses distributed?
The program analyzes the calculation between partitions.
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: Perfect square number
The question is an integer. After adding 100 to it, it is a perfect square number, and adding 168 is a perfect square number. What is the number?
Program analysis Because 168 is too small for exponential explosion, you can directly omit mathematical analysis and use the simplest method to get the upper limit:
n=0
while (n+1)**2-n*n<=168:
n+=1
print(n+1)
The idea is: the worst result is that the square of n is exactly 168 different from the square of (n+1). Because of the square relationship, it is impossible to have a larger gap than this.
As for judging whether it is a perfect square number, the simplest method is: the value of the square root can be a decimal of 0.
Combined:
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: The first few days of the day
Enter the title in a certain year, a certain month, and a certain day, which day is the day of the year?
The program analyzes special circumstances. In leap years, one extra day in February should be considered:
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: Three-number sort
Enter three integers x, y, z for the question. Please output these three numbers from small to large.
For program analysis and practice, just find a sorting algorithm to realize it, and if you are lazy, just adjust 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))
实例006:斐波那契数列
Title Fibonacci sequence.
The program analyzes the Fibonacci sequence (Fibonacci sequence), starting from 1,1, each item in the back is equal to the sum of the previous two items. Recursive implementation for graph convenience, and loop for graph performance.
Recursive implementation
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
The title copies data from one list to another list.
Program analysis use list [:], if you are not sure, you can call 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: Nine-Nine Multiplication Table
The title output 9*9 multiplication formula table.
The program analysis is divided into rows and columns to consider, 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=%2ld '%(i,j,i*j),end='')
print()
Example 009: Pause output for one second
The question output is suspended for one second.
Program analysis uses the sleep() function of the time module.
import time
for i in range(4):
print(str(int(time.time()))[-2:])
time.sleep(1)
Example 010: Time to show
The question output is paused for one second and the current time is formatted.
The program analysis is 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)
Example 011: Raising a rabbit
The topic is a pair of rabbits. From the third month after birth, one pair of rabbits will be born every month, and the little rabbit will give birth to a pair of rabbits every month after the third month. If the rabbits are not dead, ask every month What is the total number of rabbits?
Program analysis I think the original solution is a bit of a silly, and it doesn't take into account the issue of maturity at 3 months. How can people give birth to babies or babies? Considering three months of maturity, four data can be constructed, among which: January rabbits grow up to become February rabbits every month, February rabbits become March rabbits, March rabbits become annual rabbits, and adult rabbits (including newly mature rabbits) The March rabbit) gives birth to 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('第%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: Prime numbers from 100 to 200
The question judges how many prime numbers are between 101-200, and outputs all prime numbers.
The program analyzes and judges the method of prime numbers: Divide a number from 2 to sqrt (the number), if it can be divided evenly, it means that the number is not a prime number, otherwise it is a prime number. Using 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: Number of all daffodils
Print out all the "daffodil numbers" in the title. The so-called "daffodil number" refers to a three-digit number whose cube sum is equal to the number itself. For example: 153 is a "daffodil number", because 153 = 1 cube + 5 cube + 3 cube.
Program analysis uses the for loop to control 100-999 numbers, and each number is decomposed into units, tens, 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: Decompose prime factors
The question divides an integer into prime factors. For example: input 90 and print out 90=233*5.
Program analysis does not need to judge whether it is a prime number at all. Starting from 2 and traversing the number itself, the smallest prime number must be divisible.
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
The question uses the nesting of conditional operators to complete this question: students with academic performance >=90 points are represented by A, those with 60-89 points are represented by B, and those with less than 60 points are represented by C.
Conditional judgment can be used for program analysis.
points=int(input('输入分数:'))
if points>=90:
grade='A'
elif points<60:
grade='C'
else:
grade='B'
print(grade)
Example 016: Output date
The title outputs the date in the specified format.
Program analysis uses 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
Enter a line of characters for the title, and count the number of English letters, spaces, numbers and other characters.
Program analysis uses while or for statements, and the condition is that the input character 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: Adding repeaters
The question asks for the value of s=a+aa+aaa+aaaa+aa...a, where a is a number. For example, 2+22+222+2222+22222 (a total of 5 numbers are added at this time), and the addition of several numbers is controlled by the keyboard.
The program analysis is solved with a string.
a=input('被加数字:')
n=int(input('加几次?:'))
res=0
for i in range(n):
res+=int(a)
a+=a[0]
print('结果是:',res)
Example 019: Finished counting
If a number on the subject is exactly equal to the sum of its factors, this number is called "final number". For example, 6=1+2+3. Program to find all the completed numbers within 1000.
The program analysis adds each pair of factors to the set, and the duplication has been automatically removed in this process. The final result request does not 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)
Example 020: Parabolic at high altitude
Subject: A ball falls freely from a height of 100 meters. After each landing, it bounces back to half of its original height. If it falls again, how many meters does it pass on the 10th landing? How high is the 10th rebound?
Program analysis
high=200.
total=100
for i in range(10):
high/=2
total+=high
print(high/2)
print('总长:',total)
Example 021: Monkey steals peaches
Question: Monkey eating peach problem: The monkey picked off a few peaches on the first day, and ate half of it immediately, and was not addicted to it. He ate one more peach and ate one more peach the next morning. After that, I ate half and one of the remaining half of the previous day every morning. When I wanted to eat again in the morning of the 10th day, I saw that there was only one peach left. How many were picked on the first day?
The program analysis reversely deduced according to the rules: the monkey had a peach, and he stole a peach. He felt that it was not enough and stole the same amount of peaches in his hand for a total of 9 days.
peach=1
for i in range(9):
peach=(peach+1)*2
print(peach)
Example 022: Competition opponent
Subject Two table tennis teams compete, each with three players. Team A is composed of a, b, and c, and Team B is composed of x, y, and z. Lots have been drawn to determine the list of matches. Someone asked the players for the roster of the game. a says he does not compare with x, c says he does not compare with x, z, please program to find the list of the three teams.
Program analysis to find three opponents that do not 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))
Example 023: Draw a rhombus
The title prints out the following pattern (diamond):
*
***
*****
*******
*****
***
*
The program analyzes the 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)
Example 024: Fibonacci Sequence II
The question has a sequence of scores: 2/1, 3/2, 5/3, 8/5, 13/8, 21/13... Find the sum of the first 20 items of this sequence.
Program analysis is to divide the last term of the Fibonacci sequence by the previous term.
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 summation
The question asks for the sum of 1+2!+3!+…+20!.
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)