1. List sorting

def que6() :
    # 6. Enter three integers x, y, z to form a list, please print the n numbers in ascending order.
    Lists have a sort method, so make them into lists.
    li = np.random.randint(-100.100, size=10)
    # In-place conversion
    li = li.tolist()
    Sort (
    li_sort = sorted(li, reverse = False)
    print('Sort the result by {}'.format(li_sort))

    Sort by sort

    # Bubble sort
    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 function) :
    def insertSort_1(m) :
        result = []

        Insert single element k into the list li
        def to_insert(li, k) :
            # identifier
            tab = False

            Find the insertion position
            # The number of loops should be at least greater than the list length +1. None also counts as one (empty list).
            for i in range(len(li) + 1) :# change identifier to mark 'next loop after traversal', i.e. compare with 'empty card'
                if i == (len(li)):
                    tab = True

                If the position is found before the li[-1] comparison is complete, compare the cards from left to right
                if not tab and k < li[i]:
                    li.insert(i, k)
                    break
            # If the loop is complete, repeat the loop once, i.e. replace the empty card directly without comparing with the empty card.
            if tab:
                li.append(k)
            return li
        # walk through the 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(directly nested loop) :
    def insertSort2(m) :
        m = m.copy()
        result = m[:1]
        for index_choose in range(1.len(m)):
            Index_choose +1 = append
            # Compare the cards in your hand 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')
                ifindex_insert ! = index_chooseand 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('Selection sort:',selectSort(li))
    print('Bubble sort:',bubbleSort(li))
que6()
Copy the code

2. Swap dictionary keys

# 1. Transpose 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 the key by value
    def method3(d) :
        d = d.copy()
        Find the value by key
        def match(dic, b) :
            return [k for k,v in dic.items() if v == b]
        # key = key-none
        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))

        4-1 # method
        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: {}'.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()
Copy the code

3. Delete duplicate elements from the list

# No one to answer your questions? We have created a Python learning community: 531509025
# Find like-minded friends, help each other, there are good video learning tutorials and PDF e-books in the group!

List =[1,2,5,4, 5,6,8,0,2,5]
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:',method2(a))
Copy the code

4. Output prime numbers

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):
                    # Divisible, then out of the loop
                    if (i % m) == 0:
                        # print(i, m)
                        break
                    Otherwise count +1
                    else:
                        count += 1
                    Divisible complete (0/n)
                    if count == i - 2:
                        prime_list.append(i)

                    print(count, i, m)

    return (prime_list)

num = int(input('Want to output 2 to what? '))
print(prime(num))
Copy the code

5. What is the day of the year

def que3() :
    # 3. Enter date, year, month, and year. :
    # Leap year judge function
    def judge_leap(num) :
        date = [31.28.31.30.31.30.31.31.30.31.30.31]
        A leap in four years and not in four years
        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 "2018.02.12" :'))
    date_list = (list(map(int, (date.split('. ')))))
    # count the number of 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 \n' of the {} year..format(date_list[1], date_list[2], date_list[0], day))
# que3()
Copy the code

6. Guess the Numbers

# Re-guess the numbers
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      # Judge the result
i = 0           # number of cycles
frequency = 3   # limit the number of cycles

# Prompt total guess times, remaining times
print('WARNING: You have [{}] chances You guess '.format(frequency), end = '-- && > > --')
print('【{}】 chances left now:\n'.format(frequency - i +1))

while result andi ! = frequency:# guess Numbers
    num = int(input('Please guess a int_number:\n'))
    result = judge_num(num, num_random)
    i += 1
Copy the code

7. Base conversion

Convert any base to decimal
def other_to_decimal(hex, num) :
    # integer to list,
    num_str = str(num)
    # map () converts elements in a List object (of type List) to sets
    num_list = list(map(int, num_str))
    # list in reverse order
    num_list = num_list[::-1]
    print(list(map(int, num_str)))

    Get the number of digits
    digit = len(num_list)
    num_decimal = 0

    # accumulation
    for i in range(digit):
        numi = num_list[i]
        # print(numi, hex**i)
        num_decimal += numi*(hex**i)   # sum the power of each digit

    return num_decimal

Change from decimal to arbitrary base
def decimal_to_other(hex, num) :
    Get the number of digits
    digit = len(str(num))

    num_hex = []
    quotient = 1

    The remainder counts into the list num_hex
    while quotient:
        # mod and quotient
        quotient = num // hex
        remainder = num % hex
        # print(quotient, remainder)
        The remainder counts toward the list
        num_hex.append(remainder)
        The quotient does the next loop
        num = quotient

    Reverse list order, implemented by slicing and sort()
    num_hex = num_hex[::-1]
    # num_hex.sort(reverse=True)

    If it exceeds decimal, convert it to letters using ASCII codes
    for i in range(len(num_hex)):
        if num_hex[i] > 9:
            num_hex[i] = chr(int(num_hex[i])+87)
    # print(num_hex)

    # Lists are converted to strings
    result = (' '.join('%s' %m for m in num_hex))
    return result


Type = bool(input("For decimal to any base, enter 1; for decimal to any base, enter 0\n"))
if Type:
    hex = int(input("How many bases do I need to convert decimal to? Please enter a positive integer \n"))
    num = int(input("The numbers to be converted are :"))
    print(The conversion result is:, decimal_to_other(hex, num))
else:
    hex = int(input("How many bases do I need to convert to decimal? Please enter a positive integer \n years"))
    num = int(input("The numbers to be converted are :"))
    print(The conversion result is:, other_to_decimal(hex, num))
Copy the code