[Python Experimental Design] BMI calculation / Integer division / Monte Carlo approximation of pi / Enumeration method to verify 6174 conjecture / Joseph ring / Rotary lottery / Ability value / Caesar encryption

Table of Contents

1. [Calculate BMI Index]

2. [Input integers to divide]

3. [Monte Carlo method to calculate the approximate value of pi]

4. [Use enumeration method to verify 6174 conjecture]

5. [Simulated counting game (Joseph Ring Problem)]

6. [Simulated Roulette Lottery Game]

7. [Ability Value Accumulation]

8. [Principle and Implementation of Caesar Encryption Algorithm]


1. [Calculate BMI Index]

Input: height tall and weight kilo

Output: Body’s BMI index and BMI grade “underweight, normal, overweight, obese, severely obese”

Flowchart:

# 2.1- Obesity index BMI calculation
# Enter Xiao Ming’s height of 1.75m and weight of 80.5kg. Please help Xiao Ming calculate his BMI index according to the BMI formula (weight divided by height squared). The calculation rules are:
# 18.5< Too light
# 18.5-25 normal
# 25-28 Overweight
# 28-32 Obesity
# >32 Severe obesity

def My_BMI(tall, kilo):
    BMI = kilo / pow(tall, 2)
    if 0 <= BMI < 18.5:
        print('BMI is {0:.2f}: too light'.format(BMI))
    elif 18.5 <= BMI < 25:
        print('BMI is {0:.2f}: normal'.format(BMI))
    elif 25 <= BMI < 28:
        print('BMI is {0:.2f}: too heavy'.format(BMI))
    elif 28 <= BMI < 32:
        print('BMI is {0:.2f}: obesity'.format(BMI))
    elif 32 <= BMI < 50:
        print('BMI is {0:.2f}: severe obesity'.format(BMI))
    else:
        print('Input error'.format(BMI))


x = float(input("Please enter your height:"))
y = float(input("Please enter your weight:"))
My_BMI(x, y)

operation result:

As shown in the picture above, enter Xiao Ming’s height of 1.75 and weight of 80.5. After my BMI algorithm, the BMI index is 26.29, which is judged to be overweight. The experimental results are consistent with expectations and the algorithm is correct.

2. [Input integers to divide]

Input two integers and print the result of their division. If the input is not an integer or the divisor is 0, exception handling is performed. Define a function and use Python’s built-in isinstance(x, int) function to determine whether the input is an integer. If the divisor and dividend are both integers, divide normally. If not, determine whether the divisor or the dividend is not an integer, and perform exception processing output judgment.

flow chart:

# Input two integers and print the result after dividing them. If the input is not an integer or the divisor is 0, perform exception handling.

def My_Divi(x, y):
    if isinstance(x, int) and isinstance(y, int) and y != 0: # If the dividend x and the divisor y are both integers
        num = x/y
        print(num)
    elif not isinstance(x, int):
        print("The dividend {0} is not an integer".format(x))
    elif not isinstance(y, int):
        print("Divisor {0} is not an integer".format(y))
    elif y == 0:
        print("The divisor is 0")
    else:
        print("Error")


num1 = eval(input("Please enter the dividend:"))
num2 = eval(input("Please enter the divisor:"))
My_Divi(num1, num2)

operation result:

Input the dividend 32 and the divisor 4 to get 8. The output is normal. Next, try to output something that is not an integer.

In the figure above, if the dividend 23.5 is entered and it is not an integer, an exception will be thrown.

In the picture above, if the divisor 3.5 is entered, which is not an integer, an exception will be thrown.

In the picture above, if the divisor 0 is entered, an exception will be thrown. After testing, the experimental results are consistent with expectations and the algorithm is correct.

3. [Monte Carlo method to calculate the approximate value of pi]

The Monte Carlo method approximates pi. According to my understanding of the design idea: it is a computer simulation of scattering a handful of beans in a square and calculating the number of beans falling in a circle. According to the ratio of round beans/square beans, the pi can be approximatedπ, Calculation formula derivation:

flow chart:

# Calculate the approximate value of pi using the Monte Carlo method
import random
from tqdm import tqdm # Progress bar


def MY_Pi(N): # Throw N times in the square in total
    count = 0 # Count the number of times it falls within the circle
    for i in tqdm(range(N)): # Throw N times in total
        x = random.uniform(-1, 1) # Random floating point number
        y = random.uniform(-1, 1)
        if pow(x, 2) + pow(y, 2) <= 1: # inside the circle
            count + = 1 # If it falls within the circle, the counter increases by 1
    pi = 4 * count/N
    print("Use Monte Carlo method, execute {0} times, approximate pi={1}".format(N, pi))


k = int(input("Please enter the number of executions:"))
MY_Pi(k)

operation result:

After executing the Monte Carlo algorithm 10,000 times, the approximate pi ratio is 3.138

After inputting and executing the Monte Carlo algorithm 100,000 times, the approximate pi ratio is 3.14148. From the running results, we can see that the more times you toss the beans, the closer it is to piπ. After testing, the experimental results are consistent with expectations. Yes, the algorithm is correct.

Four. [Use enumeration method to verify 6174Conjecture]

For any four-digit number (the four-digit numbers may be large or small and cannot be exactly the same), rearrange it into four-digit numbers from large to small, then arrange it into four-digit numbers from small to large, and then subtract it from the large number. Eliminate the small ones, and then perform the same arrangement and subtraction on the obtained result, up to 7 times, and you will finally get the result 6174.

As the name suggests, the enumeration method is to loop through four-digit numbers that are not all the same and verify the 6174 algorithm for each four-digit number. Then I defined the 6174 verification algorithm. This function is to increase the four-digit number to the maximum within 8 steps. Small sort, subtract and sort from small to large, judge whether the subtraction results in 6174, if not, use the subtracted number as the new number and repeat the sorting and subtraction. If it exceeds 8 steps and does not get 6174, it is regarded as a guess error and the program ends immediately. If all four digits are enumerated and 6174 is obtained, the guess is correct.

flow chart:

# Use enumeration method to verify the 6174 conjecture: 6174 conjecture. In 1955, D.R. Kaprekar studied a transformation of four-digit numbers:
# Given a four-digit number k0, rearrange its four numbers from large to small into a four-digit number m, and then subtract its reverse number rev(m) to get the number k1=m-rev(m ),
# Then, continue to repeat the above transformation on k1 to get the number k2. If this continues, Capjeka discovered that no matter how big a four-digit k0 is, as long as the four numbers are not exactly the same, the above transformation will occur up to 7 times. Four digits 6174
def My_sort(n): # Sort the numbers from large to small
    s = str(n) # s is a string of n
    s_bu = '0' * (4 - len(s)) + s # Fill in numbers with less than four digits with zeros
    s_sort = ''.join(sorted(s_bu, reverse=True)) # Return the sorted numbers
    return s_sort


def My_6174(n):
    step=1
    old_n = n
    print('Verification:', old_n)
    while step <= 8: # Keep looping
        n = int(n) # Change n to an integer
        m = int(My_sort(n)) # Sort n from large to small
        m_re = int(str(m)[::-1]) # Convert m into a string and then reverse it into an integer
        k = m - m_re # new difference
        print("{0} - {1} = {2}".format(m, m_re, k))
        if k == 6174: # If it is 6174, break out of the loop
            break
        else:
            n = k # use the difference as the new number
        step + = 1 # Add one to the number of steps
    if k == 6174 and step <= 8:
        print('{0} performed the algorithm {1} times and got 6174'.format(old_n, step))
        return True
    else:
        print('Verification 6174 failed')
        return False


Flag=True
i = 999

while Flag and i < 9999: # If correct, it will always be verified
    i+=1
    if len(set(str(i))) == 1: # Skip if all numbers are the same
        continue
    else: # Otherwise, verify
        Flag = My_6174(i)

if Flag == True:
    print('Verification of 6174 in four digits did not fail!! The guess is correct!')
elif Flag == False:
    print('Failed to verify 6174 among the four digits!! Wrong guess!')

operation result:

After clicking Run, the program automatically enumerates four-digit numbers that are not all the same, performs 6174 algorithm verification, traverses guesses from 1000 to 9998, and outputs the algorithm several times to get 6174.

When the verification reaches 9998, the program ends, and the output does not fail to verify 6174 among the four digits. All are successful, the conjecture is correct, the experimental results are consistent with expectations, and the algorithm is correct.

5. [Simulated Numbering Game (Joseph Ring Problem)]

Through my own drawing in the early stage, I simulated this counting game. 8 children counted 3 and then quit, leaving child No. 7 in the end.

As shown in the picture below, the blogger simulated a counting game process. 8 children formed a circle. Each child had a number. Each child reported 3 and exited the circle (not participating in the subsequent counting). ), after four rounds of counting and elimination, child No. 7 is left.

Then you need to write code to simulate and implement the counting game. My idea is to simulate the Joseph ring through a list, define a pointer, and every time the pointer accumulates (reports the number) to a multiple of the number, the number in the list will pop up, and the length of the list will be used as each round.

Input: How many children participate in the counting game, and how many children exit the circle after reporting.

Output: The number of children left at the end.

Flowchart:

# Simulated counting game (Joseph Ring Problem)
# There are n people in a circle, numbered sequentially starting from 1, starting from the first person and counting from 1 to k (assuming k=3),
# The person who reported k exits the circle; then the circle shrinks, and the game continues from the next person, asking which number is the original one left at the end.

def My_baoshu(n, k):
    t = [1] # Generate original list--circle
    for i in range(1, n):
        t.append(i + 1)
    count = 0 #define count pointer
    while len(t) != 1:
        t_new = t[:]
        print(list(t_new))
        for j in range(0, len(t_new)): # Loop through the new list
            count + = 1
            if count % k == 0: # Pop up when k is reported
                t.remove(t_new[j]) # Remove the clicked number from the original list
    print('What is left is the original {0} number'.format(list(t)))


n = int(input("Please enter how many people to participate:"))
k = int(input("Please enter the number of exit circles reported:"))
My_baoshu(n, k)

operation result:

As can be seen from the picture, enter 8 children to participate in counting and form a circle. After reporting 3, you exit the circle. The remaining numbers in the first round are [1, 2, 4, 5, 7] and the remaining numbers in the second round are [2, 4, 7] , 8] The remaining [4, 7] in the third round, and finally only the child number [7] is left, which is consistent with the circle diagram we initially simulated. The experimental results are in line with expectations, and the algorithm is correct.

6. [Simulated Roulette Lottery Game]

Simulate the turntable lottery game, enter the number of people in the lottery, and customize the lottery to win the first, second, and third prizes. The probabilities are 10%, 20%, and 70% respectively.

flow chart:

# Simulated Roulette Lottery Game
# First Prize, Second Prize, Third Prize
# First Prize【0--0.1】
#Second Prize【0.1--0.3】
# Third Prize【0.3--1】

import random
from tqdm import tqdm


def My_gift(n):
    count = [0, 0, 0]
    for i in tqdm(range(n)):
        k = random.uniform(0, 1)
        if 0 <= k < 0.1:
            count[0] + = 1
        elif 0.1 <= k < 0.3:
            count[1] + = 1
        elif 0.3 <= k < 1:
            count[2] + = 1
        else:
            print("Error")
    print("Number of first prizes{0}Number of second prizes{1}Number of third prizes{2}".format(count[0], count[1], count[2]))


x = int(input("Please enter the number of draws:"))
My_gift(x)

operation result:

Input the simulated lottery 1,000 times, and the output was 106 first prizes, 198 second prizes, and 696 third prizes. The experimental results are in line with expectations and the algorithm is correct.

Seven. [Ability Value Accumulation]

There are 365 days in a year. If you study hard and the ability value increases by 1% compared to the previous day, and when you let it go, it decreases by 1% compared to the previous day. Programming calculates the difference between the two situations. Here I assume that the initial score is 100 points and I work hard every day. Compare increasing by 1% with letting it drop by 1% every day. The main idea here is iteration. Every day, you need to increase or decrease by 1% or decrease by 1% based on the previous day. This process can be achieved through Python programming.

flow chart:

# 7. There are 365 days in a year. If the ability value increases by 1% compared to the previous day when you study hard, and decreases by 1% compared to the previous day when you let it go, program to calculate the difference between the two situations.

def My_Study(day):
    num_pro = 100
    num_des = 100
    for i in range(day):
        num_pro = num_pro * 1.01
        num_des = num_des * 0.99
    diff = (num_pro - num_des) / num_pro * 100
    print("{0} Days later, the results of studying well: {1:.2f}; the results of laissez-faire are {2:.2f}; the results of studying well and laissez-faire are compared: {3:.2f}%".format (day, num_pro, num_des, diff))


x = int(input('Please enter how many days:'))
My_Study(x)

operation result:

Input for 365 days, based on the original 100 points, increase by 1% every day, and the final score is 3778.34 points, but let go of 1% every day, and finally only have 2.55 points, a difference of 99.93%. The experimental results are in line with expectations, and the algorithm is correct.

8. [Caesar Encryption Algorithm Principle and Implementation]

The Caesar cipher was first used by the ancient Roman military commander Gaius Julius Caesar to transmit encrypted messages in the army, so it is called the Caesar cipher. This is a displacement encryption method that only performs displacement encryption on 26 (upper and lower case) letters. The rules are quite simple and can be easily cracked. The Caesar cipher is replaced by permuting the plaintext and ciphertext alphabets, with the ciphertext letters being represented by shifting the plaintext alphabet a fixed number of positions to the left or right.

flow chart:

import string


def My_kaisa(s, k):
    low = string.ascii_lowercase # lowercase letters
    up = string.ascii_uppercase # uppercase letters
    before = string.ascii_letters # Alphabet before transformation
    after = low[k:] + low[:k] + up[k:] + up[:k]
    table = ''.maketrans(before, after)
    new_s = s.translate(table)
    print("The string before and after Caesar's encryption: {0}-->The string after Caesar's encryption {1}".format(s, new_s))


m = input("Please enter the encryption character:")
n = int(input("Please enter the number of Caesar encryption moves:"))
My_kaisa(m, n)

As shown in the figure, after inputting [Hello My Name is Akaxi] and performing Caesar encryption (moving three letter units), the output is [Khoor Pb Qdph lv Dndal]. The experimental results are in line with expectations and the algorithm is correct.

2023.10.23

Yubei Xiantao Data Valley

syntaxbug.com © 2021 All Rights Reserved.