7 classic basic cases about Python

Time:2022-5-19
catalogue
  • 1. List sorting
  • 2. Exchange dictionary key values
  • 3. Delete duplicate elements in the list
  • 4. Output prime
  • 5. The judgment is the day of the year
  • 6. Guess the number
  • 7. Binary conversion

1. List sorting

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def que6():
    # 6. Enter three integers x, y and Z to form a list. Please output these n numbers from small to large.
    #Program analysis: the list has sort method, so they can form a list.
    li = np.random.randint(-100, 100, size=10)
    #In situ conversion
    li = li.tolist()
    #Result with sort()
    li_sort = sorted(li, reverse = False)
    print('rearrange the results with sort method: {} '.format(li_sort))
 
    #Instead of using the sort method, write your own sorting method,
 
    #Bubble sorting
    def bubbleSort(m):
        m = m.copy()
        for time in range(1, len(m)):
            for index in range(len(m) - time):
                if m[index] > m[index+1]:
                    m[index], m[index+1] = m[index+1] , m[index]
        return  m
 
    #Select sort
    def selectSort(m):
        m = m.copy()
        for seat_L in range(len(m)-1):
            for seat_R in range(seat_L+1, len(m)):
                if m[seat_L] > m[seat_R]:
                    m[seat_L], m[seat_R] = m[seat_R], m[seat_L]
        return m
 
    #Insert sort 1 (internally written as a function):
    def insertSort_1(m):
        result = []
 
        #Single element K insertion list Li
        def to_insert(li, k):
            #Identifier
            tab = False
 
            #Find insertion location
            #The number of cycles should be at least greater than the length of the list + 1, and none also occupies one place (empty list), that is, there is an 'empty card' at the end of the playing card
            for i in range(len(li) + 1):
                #Modify the identifier to mark 'the next cycle after traversal', that is, in comparison with 'empty card'
                if i == (len(li)):
                    tab = True
 
                #If you find the position before the comparison of Li [- 1] is completed (included), compare the poker from left to right
                if not tab and k < li[i]:
                    li.insert(i, k)
                    break
            #If the traversal is completed, cycle again, that is, there is no need to compare with the 'empty card', and directly replace the card with the 'empty card'
            if tab:
                li.append(k)
            return li
        #Traversal list
        # result = result[:1]
        for length in range(len(m)):
            result = to_insert(result, m[length])
 
            # print(result,m[length])
        return result
 
    #Insert sort 2 (direct nested loop):
    def insertSort2(m):
        m = m.copy()
        result = m[:1]
        for index_choose in range(1, len(m)):
            #I already have an index on my hand_ Choose a card, compare the second index_ Choose + 1 card will append
            #Compare the cards on your opponent one by one. If you compare them all, add them to the end
            for index_insert in range(len(result) + 1):
                print(result, index_insert,'\n',m, index_choose,'\n\n')
                if index_insert != index_choose and m[index_choose] < result[index_insert] :
                    result.insert(index_insert, m[index_choose])
                    break
                if index_insert == index_choose:
                    result.append(m[index_choose])
            # print(result, m[index_choose])
        return result
 
 
 
    # print(li)
    print('insert sort:',insertSort3(li))
    print('select sort: ',selectSort(li))
    print('bubble sort:',bubbleSort(li))
que6()

2. Exchange dictionary key values

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 1. Swap elements\
def que1():
    d={1:"one",2:"two"}
 
    #Method 1 - dynamic assignment
    def method1(d):
        d = d.copy()
        result = {}
        for k,v in d.items():
            result[v] = k
        return result
 
    #Method 2 - generator
    def method2(d):
        d = d.copy()
        result = {v:k for k,v in d.items()}
        return result
 
    #Method 3 --- find key by value
    def method3(d):
        d = d.copy()
        #Find value by key
        def match(dic, b):
            return [k for k,v in dic.items() if v == b]
        #Sir, enter key none, and then assign a value
        result = {}
        result = result.fromkeys(d.values())
        for k in result.keys():
            result[k] = match(d, k)[0]
        return result
 
    #Method 4 --- list to dictionary < direct conversion / dynamic assignment >
    def method4(d):
        d = d.copy()
        key = d.keys()
        val = d.values()
        data = list(zip(key, val))
 
        #Method 4-1
        result1 = {}
        for i in range(len(data)):
            result1[data[i][1]] = data[i][0]
 
        #Method 4-2
        result2 = dict(zip(val, key))
 
        return result1, result2
 
    print('new list dynamic assignment method: {}'.format(method1(d)))
    print('generator method: {}'.format(method2(d)))
    print('search by key method: {} '.format(method3(d)))
    print('dynamic assignment list to dictionary method: {} '.format(method4(d)[0]))
    print('direct list to dictionary method: {} '.format(method4(d)[1]))
# que1()

3. Delete duplicate elements in the list

No one answers any questions? Xiaobian created a python learning exchange group: 531509025
Look for like-minded friends to help each other. There are also good video learning tutorials and PDF e-books in the group!

Delete duplicate element list = [1,2,5,4,1,5,6,8,0,2,5]

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
a = np.random.randint(-100, 100, size=10)
a = a.tolist()
 
def method1(a):
    a = a.copy()
    a = set(a)
    return a
def method2(a):
    b = a.copy()
    c = 0
    for i in range(len(a)-1):
        if b[i+c] in b[:i+c]+b[i+c+1:]:
            b.pop(i+c)
            c -= 1
    return b
print('set legal: ',method1(a))
print('traversal method: ',method2(a))

4. Output prime

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def prime(end):
 
    prime_list = []
    if end <= 1:
        print('must be greater than 1 ')
    else:
        # prime_list.append(2)
        for i in range(2, end+1, 1):
            count = 0
            if i == 2:
                if i%2 != 0:
                    prime_list.append(2)
            else:
                for m in range(2, i):
                    #If it can be divided, it will jump out of the loop
                    if (i % m) == 0:
                        # print(i, m)
                        break
                    #Otherwise, count + 1
                    else:
                        count += 1
                    #Judge whether division is complete (0 / N)
                    if count == i - 2:
                        prime_list.append(i)
 
                    print(count, i, m)
 
    return (prime_list)
 
num = int(input('how much do you want to output 2 to?'))
print(prime(num))

5. The judgment is the day of the year

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def que3():
    # 3. Enter a certain day of a certain month in a certain year to judge the day of the year?:
    #Leap year judgment function
    def judge_leap(num):
        date = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        #Four hundred year leap
        if (num % 4 == 0 and num % 100 != 0) or num % 400 ==0:
            date[1] =29
        return date
 
    #Format conversion
    date = (input('please enter a date in the format of "February 12, 2018":))
    date_list = (list(map(int, (date.split('.')))))
    #Traversal calculation days
    day = date_list[2]
    for i in range(date_list[1]):
        day += judge_leap(date_list[0])[i]
    print('{} month {} day is the {} day of year {} \ n'.format(date_list[1], date_list[2], date_list[0], day))
# que3()

6. Guess the number

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#Guess the number again
import random
 
def judge_num(num, num_random):
    if num > num_random:
        print('It\'s too big')
        return 1
    elif num < num_random:
        print('It\'s too small')
        return 1
    else:
        print("Congratulation!! That\' right!")
        return 0
 
#Generate random number
num_start = int(input('Digital lower limit of guess number:\n'))
num_end = int(input('Digital upper limit of guess number:\n'))
num_random = random.randint(num_start, num_end)
 
#Parameter initialization
result = 1      #Judgment result
i = 0           #Number of cycles
frequency = 3   #Cycle limit times
 
#Prompt total guess times and remaining times
print('WARNING: You have【{}】 chances you guess '.format(frequency), end = '--&&>>--')
print('【{}】 chances left now:\n'.format(frequency - i +1))
 
while result and i != frequency:
    #Guess the number
    num = int(input('Please guess a int_number:\n'))
    result = judge_num(num, num_random)
    i += 1

7. Binary conversion

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#Arbitrary decimal to decimal
def other_to_decimal(hex, num):
    #Convert integer to list,
    num_str = str(num)
    #Map () converts the elements (list type) in the list object to the set type
    num_list = list(map(int, num_str))
    #List reverse order
    num_list = num_list[::-1]
    print(list(map(int, num_str)))
 
    #Get number of digits
    digit = len(num_list)
    num_decimal = 0
 
    #Accumulate
    for i in range(digit):
        numi = num_list[i]
        # print(numi, hex**i)
        num_decimal += numi*(hex**i)   #The power exponent of each digit is accumulated
 
    return num_decimal
 
#Decimal to arbitrary base
def decimal_to_other(hex, num):
    #Get number of digits
    digit = len(str(num))
 
    num_hex = []
    quotient = 1
 
    #Divide and the remainder is included in the list num_ hex
    while quotient:
        #Surplus and quotient
        quotient = num // hex
        remainder = num % hex
        # print(quotient, remainder)
        #The remainder is included in the list
        num_hex.append(remainder)
        #Do the next cycle
        num = quotient
 
    #The reverse order of the list can be realized through slicing and sort() function
    num_hex = num_hex[::-1]
    # num_hex.sort(reverse=True)
 
    #If it exceeds decimal, convert it into letters with ASCII code
    for i in range(len(num_hex)):
        if num_hex[i] > 9:
            num_hex[i] = chr(int(num_hex[i])+87)
    # print(num_hex)
 
    #Convert list to string
    result = (''.join('%s' %m for m in num_hex))
    return result
 
 
Type = bool(input("Decimal to decimal, please enter 1, any decimal to decimal, please enter 0 \ n"))
if Type:
    hex = int(input("How many decimal digits do you need to convert to? Please enter a positive integer \ n"))
    num = int(input(The number to be converted is:))
    print(The conversion result is:, decimal_to_other(hex, num))
else:
    hex = int(input("How many decimal digits do you need to convert to decimal? Please enter a positive integer \ n year"))
    num = int(input(The number to be converted is:))
    print(The conversion result is:, other_to_decimal(hex, num))

This is the end of this article about the seven classic basic cases of Python. For more information about Python classic cases, please search the previous articles of developeppaper or continue to browse the relevant articles below. I hope you will support developeppaper in the future!