100 learning notes of Python

Title Source: Python 100 cases

Example 2

Skill: segment function uses number axis to divide and locate.

Profit:

ratio = [0.01, 0.015, 0.03, 0.05, 0.075, 0.1]

Title:

The bonus paid by the enterprise is based on the profit commission. If the profit (I) is less than or equal to RMB 100000, the bonus can be increased by 10%; if the profit is higher than RMB 100000, the part lower than RMB 100000 will be increased by 10%; if the profit is higher than RMB 100000, the bonus can be increased by 7.5%; if the profit is between RMB 200000 and RMB 400000, the bonus can be increased by 5%; if the profit is between RMB 400000 and RMB 600000, the bonus can be increased by 3%; if the profit is between RMB 600000 and RMB 1000000, the bonus can be increased by 3%; if the profit is higher than RMB 600000 For the part above 1 million yuan, 1% commission will be applied for the part above 1 million yuan. Input the profit I of the month from the keyboard, and calculate the total amount of bonus to be paid?

Program analysis:

Please use the number axis to divide and locate. Pay attention to defining bonus as growth integer.

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
i = int(input('Please enter profit:'))
arr = [1000000, 600000, 400000, 200000, 100000, 0]
ratio = [0.01, 0.015, 0.03, 0.05, 0.075, 0.1]
reward = 0
for idx in range(1, 6):
    if i > arr[idx]:
        reward += (i - arr[idx])*ratio[idx]
        i = arr[idx]
print(reward)

Example 7

Tip: how to copy a list.

b = a[:]

Title:

Copy data from one list to another.

Program analysis:

Use the list [:].

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
a = [1, 2, 3]
b = a[:]
print(b)

Example 8

Tip: format output

print("%d*%d=%d" % (i, j, i*j))

Title:

Output 9 * 9 multiplication table.

Program analysis:

Considering branches and columns, there are 9 rows and 9 columns in total, i control row and j control column.

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
for i in range(1,10):
    print('')
    for j in range(1,i+1):
        #print('%d*%d=%d' % (i, j, i*j), end = ' ')
        #print('{}*{}={}'.format(i,j,i*j), end = ' ')
        print(i,'*',j,'=',i*j,end = '  ')

Example 9

Tip: pause output for one second

import time
time.sleep(1)

Title:

Pause output for one second.

Program analysis:

Use the sleep() function of the time module.

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
#1
import time
for i in range(6):
    print(i)
    time.sleep(1)

#2
import time
myD = {1 : 'a', 2 : 'b'}
for key, value in dict.items(myD):
    print(key, value)
    time.sleep(1)

Example 10

Tip: format and output the current time

#!/usr/bin/python
import time
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
#perhaps
import time,datetime
TIME = datetime.datetime.now()
print(TIME.strftime("%Y.%m.%d %H-%M-%S"))

Title:

Pause the output for one second and format the current time.

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
#Method 1:
import time
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
time.sleep(1)
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))

#Method 2:
import time,datetime
time.sleep(1)
TIME = datetime.datetime.now()
print(TIME.strftime("%Y.%m.%d %H-%M-%S"))

Example 13

Skill: break down the number of "one", "ten", "hundred"

#!/usr/bin/python
n%10 #individual
int(n/10)%10 #Ten
int(n/100) #hundred

Title:

Print out all the "narcissus number". The so-called "narcissus number" refers to a three digit number, and the sum of each digit cube is equal to the number itself. For example: 153 is a "narcissus number", because 153 = 1 to the third power + 5 to the third power + 3 to the third power.

Program analysis:

Using for loop to control 100-999 numbers, each number is decomposed into bits, tens and hundreds.

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
sum = 0
for i in range(100, 1000):
    bai = int(i/100)
    shi = int(i/10) % 10
    ge = i % 10
    if bai**3 + shi**3 + ge**3 == i:
        print(i)
        sum += 1
print('sum =', sum)

Example 14

Tip 1: isinstance() function

Determine whether an object is a known type.
Syntax: isinstance(object, classinfo)
Return value: same return True, otherwise return False
example:

>>>a = 2
>>>isinstance(a, int)
True
>>>isinstance(a,(str, int, list)) #Is one of the tuples that returns True
Ture

The difference between isinstance() and type():
🔺 isinstance() will consider that the subclass is a type of parent class, and consider the inheritance relationship
🔺 type() does not consider a subclass as a parent type and does not consider inheritance
example:

class A: 
    pass
class B(A):
    pass
isinstance(A(),A)  #True
type(A()) == A     #True
isinstance(B(),A)  #True
type(B()) == A     #False

Tip 2: isdigit() method

Checks whether a string consists only of numbers.
Syntax: str.isdigit()
Return value: return True only including numbers, otherwise return False

Tip 3: join() method

Generates a new string by connecting elements in the sequence with the specified characters.
Syntax: str.join(sequence)

Title:

Decompose a positive integer into prime factors. For example: enter 90 and print out 90 = 233 * 5.

Program analysis:

To decompose the prime factor of n, first find a minimum prime number k, and then complete as follows:
(1) If the prime number is exactly equal to n, it means that the process of decomposing the prime factor is over. Just print it out.
(2) If n < > k, but n can be divided by K, print out the value of K, and use the quotient of N divided by K as a new positive integer. Repeat step 1.
(3) If n cannot be divided by k, repeat the first step with k+1 as the value of k.

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
def reduceNum(n):
    l = []
    while n > 1:
        for i in range(2, n+1):
            if n % i == 0:
                l.append(i)
                n = int(n / i)
                break
    return l

s = input('Please enter a number:')
if s.isdigit() and int(s) > 0:
    print(s,'=',' * '.join([str(x) for x in reduceNum(int(s))]))
else:
    print("Please enter the correct positive integer")

Example 15

Technique: the assignment of different values is realized through the sequence of logical connections

s = (score >= 90)and 'A' or (score >= 60)and 'B' or 'C'

Title:

Using the nesting of conditional operators to complete this question: students with A score of > = 90 are represented by A, those between 60-89 are represented by B, and those below 60 are represented by C.

Program analysis:

(a > b)? A: B this is a basic example of conditional operators.

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
score = int(input('Please enter a score:'))
s = (score >= 90)and 'A' or (score >= 60)and 'B' or 'C'
print(s)

Example 16

skill:

Outputs the date in the specified format.

Title:

Outputs the date in the specified format.

Program analysis:

Use the datetime module.

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import datetime
 
if __name__ == '__main__':
 
    # Output today's date in the format dd/mm/yyyy. For more options, see the strftime() method
    print(datetime.date.today().strftime('%d/%m/%Y'))
 
    # Create date object
    miyazakiBirthDate = datetime.date(1941, 1, 5)
 
    print(miyazakiBirthDate.strftime('%d/%m/%Y'))
 
    # Date arithmetic
    miyazakiBirthNextDay = miyazakiBirthDate + datetime.timedelta(days=1)
 
    print(miyazakiBirthNextDay.strftime('%d/%m/%Y'))
 
    # Date replacement
    miyazakiFirstBirthday = miyazakiBirthDate.replace(year=miyazakiBirthDate.year + 1)
 
    print(miyazakiFirstBirthday.strftime('%d/%m/%Y'))

Example 23

Tip 1:

"/" indicates floating-point division, and returns floating-point result;
"/ /" indicates integer division.

Tip 2:

The procedure is simple and regular.

Title:

Print out the following pattern (diamond):

   *
  ***
 *****
*******
 *****
  ***
   *

Program analysis:

First, the graph is divided into two parts. The first four lines have a rule, and the last three lines have a rule. Using the double for loop, the first layer controls the row and the second layer controls the column.

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
n = int(input('enter a number:'))
for i in range(1, n+1, 2):
    m = (n - i)//2
    print(' '*m, '*'*i)
for i in range(n-2, 0, -2):
    m = (n - i)//2
    print(' '*m, '*'*i)

Example 35

skill:

Text color settings

Title:

Text color settings.

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
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 + "Color font for warnings?" + bcolors.ENDC)

Example 38

skill:

Two dimensional matrix generation

a = []
for i in range(3):
    a.append([])
    for j in range(3):
        a[i].append(float(input('Please enter a number:')))

Title:

Find the sum of the main diagonal elements of a 3 * 3 matrix.

Program analysis:

The dual for loop is used to control the input two-dimensional array, and then a[i][i] is accumulated and output.

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
a = []
sum = 0.0
for i in range(3):
    a.append([])
    for j in range(3):
        a[i].append(float(input('Please enter a number:')))
for i in range(3):
    sum += a[i][i]
print(sum)

Example 41

skill:

Static variable

Title:

Mimics the use of static variables.

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
def varfunc():
    var = 0
    print 'var = %d' % var
    var += 1
if __name__ == '__main__':
    for i in range(3):
        varfunc()

# Properties of class
# As a property of a class
class Static:
    StaticVar = 5
    def varfunc(self):
        self.StaticVar += 1
        print self.StaticVar

print Static.StaticVar
a = Static()
for i in range(3):
    a.varfunc()

Output results:

var = 0
var = 0
var = 0
5
6
7
8

Example 42

skill:

auto?

Title:

Learn how to use auto to define variables.

Program analysis:

Without the auto keyword, use the variable scope as an example.

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
num = 2
def autofunc():
    num = 1
    print('internal block num = %d' % num)
    num += 1
for i in range(3):
    print('The num = %d' % num)
    num += 1
    autofunc()

Output results:

The num = 2
internal block num = 1
The num = 3
internal block num = 1
The num = 4
internal block num = 1

Example 43

skill:

Static variable

Title:

Imitate another case of static variable.

Program analysis:

Demonstrate the use of a python scope

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Num:
    nNum = 1
    def inc(self):
        self.nNum += 1
        print 'nNum = %d' % self.nNum

if __name__ == '__main__':
    nNum = 2
    inst = Num()
    for i in range(3):
        nNum += 1
        print 'The num = %d' % nNum
        inst.inc()

Output results:

The num = 3
nNum = 2
The num = 4
nNum = 3
The num = 5
nNum = 4

Example 44

skill:

Two dimensional matrix generation

z = []
for i in range(3):
    z.append([])
    for j in range(3):
        z[i].append(x[i][j]+y[i][j])

Title:

Python adds two matrices:
Two matrices of three rows and three columns are used to add the data of their corresponding positions, and a new matrix is returned:
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[5,8,1],
[6,7,3],
[4,5,9]]

Program analysis:

Create a new matrix of three rows and three columns, use for to iterate and take out the values of corresponding positions in the X and Y matrices, add them and put them in the corresponding positions of the new matrix.

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
x = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]
y = [[5,8,1],
    [6,7,3],
    [4,5,9]]
z = []
for i in range(3):
    z.append([])
    for j in range(3):
        z[i].append(x[i][j]+y[i][j])
print(z)

Output results:

[[17, 15, 4], [10, 12, 9], [11, 13, 18]]

Example 47

skill:

The values of the two variables are interchanged.

a,b = b,a

Title:

The values of the two variables are interchanged.

Program analysis:

nothing

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
def exchange(x, y):
    x, y = y, x
    return(x, y)
if __name__ == '__main__':
    x, y = 10, 20
    print('x=%d,y=%d'%(x,y))
    x, y = exchange(x, y)
    print('x=%d,y=%d' % (x, y))

Output results:

x=10,y=20
x=20,y=10

Example 49

Tip 1:

Use of lambda

MAXIMUM = lambda x, y: (x>y)*x + (x<y)*y
MINIMUM = lambda x, y: (x<y)*x + (x>y)*y

Tip 2:

How to get the maximum and minimum value in python

MAXIMUM = lambda x, y: (x>y)*x + (x<y)*y
MINIMUM = lambda x, y: (x<y)*x + (x>y)*y

Title:

Use lambda to create anonymous functions.

Program analysis:

nothing

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
MAXIMUM = lambda x, y: (x>y)*x + (x<y)*y
MINIMUM = lambda x, y: (x<y)*x + (x>y)*y

if __name__=='__main__':
    a = 10
    b = 20
    print('the larger one is %d'%(MAXIMUM(a ,b)))
    print('the smaller one is %d'%(MINIMUM(a ,b)))

Output results:

the larger one is 20
the smaller one is 10

Example 50

skill:

Output random number

Title:

Output a random number.

Program analysis:

Use the random module.

code

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import random
import string

# Random floating point number between 0-1
print(random.random())

# Random floating point number, interval may not be an integer
print(random.uniform(1.1, 5.4))

# Random integer
print(random.randint(10, 20))

# Random selection of odd numbers between 1-100
print(random.randrange(1,100,2))

# Random selection of elements from a sequence
print(random.choice([x for x in range(1,100)]))  # Output random number between 1-99
print(random.choice('tomorrow'))                 # Randomly select an element from a sequence
print(random.choice(['scissors', 'stone', 'cloth']))     # Random selection string

# Generate a specified number of random characters in multiple characters:
print(random.sample('zyxwvutsrqponmlkjihgfedcba',5))

# Select a specified number of characters from multiple characters to form a new string:
print(''.join(random.sample(['z','y','x','w','v','u','t','s','r','q','p','o','n',
                             'm','l','k','j','i','h','g','f','e','d','c','b','a'], 5)))

# Generate a specified number of random characters from a-z A-Z 0-9:
ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 8))
print(ran_str)

# Disorganize the order
a=[1,3,5,6,7]
print(random.shuffle(a))

Output results:

0.698448960846087
5.141896050136319
12
43
83
t
['d', 'x', 's', 'r', 'h']
RWchwZJg
xcfjg
[7, 6, 3, 1, 5]

Tags: Python Lambda less

Posted on Thu, 11 Jun 2020 01:04:17 -0400 by Thatsmej