python programming question bank and answer analysis, python classic programming questions and answers

Hello everyone, the editor is here to answer the following questions for you, python programming question bank and answer analysis, python classic programming questions and answers, let us take a look now!

Topic 1: Number of daffodils

Narcissistic number is also known as pluperfect digital invariant (PPDI), narcissistic number, self-exponentiation number, Armstrong number or Armstrong number.

The narcissus number is a 3-digit number in which the sum of the 3rd powers of the digits in each digit is equal to itself. For example: 1^3 + 5^3+ 3^3 = 153 How to install third-party libraries in Python, and how to install the PIL module in Python .

for i in range(100, 1000):  
    i1 = i // 100       # 取百位数字 123//100=1  
    i2 = i // 10 % 10   # 取十位数字 123//10=12  12%10=2  
    i3 = i % 10         # 取个位数字 123%10=3  
  
    if i1 ** 3 + i2 ** 3 + i3 ** 3 == i:  
        print(f"{i}是水仙花数")  
        # 153 是水仙花数  
        # 370 是水仙花数  
        # 371 是水仙花数  
        # 407 是水仙花数  


Topic 2: Number of four-leaf roses

The four-leaf rose number is a 4-digit power number. An autoexponential number is an n-digit number in which the sum of the nth powers of the digits in each digit is equal to itself.

(For example: when n is 3, there is 1^3 + 5^3 + 3^3 = 153. 153 is an autoexponential number when n is 3. The 3-digit autoexponential number is called the daffodil number. ).

for i in range(1000,10000):  
    i1 = i // 1000      # 取千位数字 1234//1000=1  
    i2 = i // 100 % 10  # 取百位数字 1234//100=12  12%10=2  
    i3 = i // 10 % 10   # 取十位数字 1234//10=123  123%10=3  
    i4 = i % 10         # 取个位数字 1234%10=4  
    # print(i,i1,i2,i3,i4)  
  
    if i1 ** 4 + i2 ** 4 + i3 ** 4 + i4 ** 4 == i:  
        print(f'{i}是四叶玫瑰数')  
        # 1634 是四叶玫瑰数  
        # 8208 是四叶玫瑰数  
        # 9474 是四叶玫瑰数  


Question 3: Output strings in reverse order

  • Writing method 1: Slicing method
str = input("请输入字符串")  
print(str[::-1])  


  • Writing method 2: Loop conversion
str = input("请输入字符串")  
list = []  
for x in range(len(str) -1,-1,-1):  
    list.append(str[x])  
print(''.join(list))  


Topic 4: Number guessing game

demand analysis:

Randomly generate an integer within 100. There are 10 chances to start the game and enter the guessed number.

  • If the guess is too small, the prompt is: The guess is too small.

  • If the guess is too high, it will prompt: The guess is too big.

  • If you guess correctly, it will prompt: Guess it correctly and the game will end.

  • If you haven't guessed correctly after 10 chances, prompt: Game over, no guess.

import random as rd  
  
number = rd.randint(0,100)  
for i in range(10):  
    choice = int(input("请输入你要猜测的数字:"))  
    if choice > number:  
        print("你猜大了")  
    elif choice < number:  
        print("你猜小了")  
    else:  
        print("你猜对了,真棒!")  
        print(f'你一共用了{i + 1}次机会')  
        break  
    print(f'还剩{9 - i}次机会')  
else:  
    print('游戏结束,你没有猜到')  


Topic 5: One hundred chickens and one hundred coins

demand analysis:

Roosters cost 5 yuan each, hens 3 yuan each, and 3 chicks cost 1 yuan. Now you are asked to buy 100 chickens (three types of chickens) with 100 yuan. Ask how many roosters, hens, and chicks you want to buy. Only?

Math equation:

  • Suppose you buy x number of roosters, y number of hens, and z number of chicks.

  • x+y+z= 100

  • 5x+3y+z/3 = 100

Algorithm ideas

  • Taking the rooster as the breakthrough point, a rooster costs 5 yuan, and you can only buy 20 at most for 100 yuan.

  • Since you have to buy three types of chickens, the number of roosters must be less than 20.

  • Hens cost 3 yuan each. Use all 100 to buy hens. The maximum number cannot exceed 33.

  • Let the number of roosters be x, the number of hens y, and the number of chickens z

  • As long as 5x+3y+z/3=100 and x+y+z==100 are satisfied, the result of this combination can be output.

count = 0  
for x in range(1,20):  
    for y in range(1,33):  
        z = 100 - x -y  
        if z > 0 and 5 * x + 3 * y + z / 3 == 100:  
            count += 1  
            print("="*60)  
            print(f'第{count}种买法,公鸡买了{x}只,母鸡买了{y}只,小鸡买了{z}只')  
            # == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==  
            # 第1种买法,公鸡买了4只,母鸡买了18只,小鸡买了78只  
            # == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==  
            # 第2种买法,公鸡买了8只,母鸡买了11只,小鸡买了81只  
            # == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==  
            # 第3种买法,公鸡买了12只,母鸡买了4只,小鸡买了84只  


Topic 6: Upgraded version of leap year problem

Enter the year, month and day, output whether the date is a leap year, and output the day of the year that the date is.

Leap year judgment conditions:

  • Divisible by 4 and not divisible by 100

  • Divisible by 400

  • If any one of the two conditions is met, it is a leap year.

Algorithm idea:

  • Receive the year, month and day input by the user and create a list that saves the days in 12 months

  • Determine whether it is a leap year based on the year. If it is, set February to 29 days, otherwise set February to 28 days.

  • According to the month and date, it is the day of the year

year = int(input("请输入年份"))  
month = int(input("请输入月份"))  
day = int(input("请输入日期"))  
  
date_list = [31,29,31,30,31,30,31,31,30,31,30,31]  
count_day = day  
if year % 4 == 0 and year % 100 !=0 or year % 400 == 0:  
    print(f'{year}年是闰年')  
    date_list[1]=29  
else:  
    print(f'{year}年是平年')  
    date_list[1]=28  
  
for i in range(month-1):  
    count_day += date_list[i]  
  
print(f'{year}年{month}月{day}日是当年的第{count_day}天')  


Topic 7: Monkey eating peach problem

demand analysis:

  • The monkey picked a few peaches on the first day and ate half of them immediately. When he was not satisfied, he ate one more.

  • The next morning I ate half of the remaining peaches and one more.

  • From then on, every morning I ate half and one of the leftovers from the previous day. When I wanted to eat again on the morning of the 10th day, I saw that there was only one peach left.

  • Find out how many peaches it picked in total.

This question can be solved backwards using recursive thinking.

  • On the 10th day, there was only one left before eating, which means that on the 9th day, half of the food was eaten and another one was eaten, and there was still one left.

  • Suppose there are p peaches before eating on the 9th day

  • It can be obtained: p/2 - 1 = 1, and the number of peaches on the ninth day is p=4.

  • By analogy, you can calculate how many peaches were picked on the first day.

Algorithm idea:

  • The number of peaches before eating on the 10th day is initialized to p=1

  • Loop from 9 to 1 9 times. According to the above formula, back it up as p=(p+1)*2 to get the number of peaches before eating on the first day.

p = 1  
print(f'第10天还剩下{p}个桃子')  
for i in range(9,0,-1):  
    p = (p + 1) * 2  
    print(f'第{i}天还剩下{p}个桃子')  
print(f'第一天一共摘了{p}个桃子')  
  
# 第10天还剩下1个桃子  
# 第9天还剩下4个桃子  
# 第8天还剩下10个桃子  
# 第7天还剩下22个桃子  
# 第6天还剩下46个桃子  
# 第5天还剩下94个桃子  
# 第4天还剩下190个桃子  
# 第3天还剩下382个桃子  
# 第2天还剩下766个桃子  
# 第1天还剩下1534个桃子  
# 第一天一共摘了1534个桃子  


Topic 8: Bubble sorting

The origin of the bubble sort algorithm: The name of this algorithm comes from the fact that smaller elements will slowly "float" to the top of the array through exchange (in ascending or descending order), just like the carbon dioxide bubbles in carbonated drinks will eventually float to the top. , hence the name "bubble sort"

From front to back (that is, starting from the element with the smaller subscript), the values ​​of adjacent elements are compared in sequence. If it is found that the value is larger than the last one, the positions are swapped, so that the element with the larger value gradually moves from the front to the back.

Suppose there is a list [29,12,19,37,14] that you want to sort in ascending order

Round 1: The initial list is [29,12,19,37,14]
  • Compare 29 > 12 Swap positions: [12,29,19,37,14]

  • Compare 29 > 19 Swap positions: [12,19,29,37,14]

  • Compare 29 > 37 not greater than, no exchange: the list remains the same as above

  • Compare 37 > 14 Swap positions: [12,19,29,14,37]

Second round: The list inherits from the previous round as [12,19,29,14,37]
  • Compare 12 > 19 not greater than, no exchange: the list remains the same as above

  • Compare 19 > 29 not greater than, no exchange: the list remains the same as above

  • Compare 29 > 14 Swap positions: [12,19,14,29,37]

The third round: The list inherits the previous round as [12,19,14,29,37]
  • Compare 12 > 19 not greater than, no exchange: the list remains the same as above

  • Compare 19 > 14 Swap positions: [12,14,19,29,37]

Round 4: List inheritance from the previous round is [12,14,19,29,37]
  • Compare 12 > 14 not greater than, no exchange: the list remains the same as above

  • List sorting completed: [12,14,19,29,37]

  
import numpy as np  
  
pop_list = np.random.randint(100,size=6)  
  
# pop_list = [82,15,15,41,37,31]  
# pop_list = [29,12,19,37,14]  
  
count = len(pop_list)  
print('没排序之前的列表',pop_list)  
  
for i in range(count-1):  
    for j in range(count-i-1):  
        if pop_list[j] > pop_list[j + 1]: # 如果要降序就是改成 < 号  
            pop_list[j],pop_list[j+1] = pop_list[j+1],pop_list[j]  
print('排好序的列表为',pop_list)  
# 排好序的列表为 [15, 15, 31, 37, 41, 82]  
# 排好序的列表为 [12, 14, 19, 29, 37]  


Question 9: Binary search method

The dichotomy method is a relatively efficient search method

Recall the number-guessing game I played before. A positive integer x less than 100 is given in advance for you to guess. During the guessing process, you will be given tips for judging the size. How can you guess it quickly? The game we made before gave 10 chances. If we learn the binary search method, no matter what the number is, it only takes 7 times at most to guess the number.

  • binary search method

First guess 50, if the guess is correct, end; if the guess is higher, guess in the smaller direction, and then guess 25; if the guess is smaller, guess in the larger direction, and then guess 75;...remove half of each guess. number, so that we can gradually approach the pre-given number. This idea is the dichotomy method.

Application of dichotomy

  • Must be an ordered sequence.

  • There are requirements for the amount of data.

  • The amount of data is too small to be suitable for binary search, and the efficiency improvement is not obvious compared with direct traversal.

  • It is not suitable to use binary search if the amount of data is too large, because the array requires continuous storage space. If the amount of data is too large, it is often impossible to find continuous memory space to store such large-scale data.

Algorithm idea:

Suppose there is an ordered list: [5,7,11,22,27,33,39,52,58]

Is the number 11 in this list, and if so, what is its index value?

  • First, we compare the middle positions 27 and 11 of the ordered list. We find that 11 is less than 27.

  • So we exclude the numbers to the right of 27, and the remaining list is: [5,7,11,22]

  • Then we take the 7 and 11 in the middle of [5,7,11,22] and compare it and find that 11 is greater than 7, so we exclude the numbers to the left of 7 and the retained list is: [11,22]

  • Finally we take the middle position between 11 and 22

  • It has just reached 11. At this time, the index value of 11 can be returned. If it is not found, it will prompt that it does not exist.

The first purely algorithmic approach
arr_list = [5,7,11,22,27,33,39,52,58]  
number = 11  
count = 0  
left = 0  
right = len(arr_list)-1  
while left<=right:  
    middle = (left+right)//2  
    count += 1  
    if number > arr_list[middle]:  
        left = middle +1  
    elif number < arr_list[middle]:  
        right = middle - 1  
    else:  
        print(f'数字{number}已找到,索引值为{middle}')  
        break  
else:  
    print(f'数字{number}没有找到')  
print(f'一共用了{count}次查找')  
  
# 数字11已找到,索引值为2, 一共用了3次查找  


The second method of recursive function
arr_list = [5,7,11,22,27,33,39,52,58]  
  
def binary_search(number,left,right):  
    if left <= right:  
        middle = (left + right) // 2  
        if number < arr_list[middle]:  
            right = middle - 1  
        elif number > arr_list[middle]:  
            left = middle + 1  
        else:  
            return middle  
        return binary_search(number,left,right)  
    else:  
        return -1  
  
print(binary_search(11,0,len(arr_list)-1))  


Topic 10: Selection sorting

Basic idea: Find the smallest element from the unsorted sequence and put it in the first position, then find the smallest element from the remaining unsorted sequence and put it in the second position, and so on until all elements are sorted.

  • If the list is [6, 8, 3, 5, 9, 10, 7, 2, 4, 1], first find 1 and minimum swap it to the 1st position

  • Get the list [1, 8, 3, 5, 9, 10, 7, 2, 4, 6], followed by 2 minimum transpositions to the 2nd position

  • Get the list [1, 2, 3, 5, 9, 10, 7, 8, 4, 6], followed by 3, the minimum position remains unchanged

  • Get the list [1, 2, 3, 5, 9, 10, 7, 8, 4, 6], followed by 4 minimum transposition to the 4th position

  • Get the list [1, 2, 3, 4, 9, 10, 7, 8, 5, 6], followed by 5 minimum transposition to the 5th position

  • Get the list [1, 2, 3, 4, 5, 10, 7, 8, 9, 6], followed by 6 minimum transposition to the 6th position

  • Get the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], followed by 7, the minimum position remains unchanged

  • Get the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], followed by 8, the minimum position remains unchanged

  • Get the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], followed by 9, the minimum position remains unchanged

  • Get the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], followed by 10. The minimum position remains unchanged and the sorting is completed.

import random as rd  
  
sec_list = [rd.randint(1,100) for i in range(8)]  
# sec_list = [91,30,93,98,26,98,20,90]  
length = len(sec_list)  
print(f'未排序的列表为:{sec_list}')  
  
for i in range(length -1):  
    min_index = i  
    for j in range(i + 1,length):  
        if sec_list[min_index] > sec_list[j]:  
            min_index = j  
    sec_list[min_index],sec_list[i] = sec_list[i],sec_list[min_index]  
    print(f'第{i+1}轮排好序是:{sec_list}')  
print(f'最终排好序的列表为:{sec_list}')  
  
# 未排序的列表为:[91, 30, 93, 98, 26, 98, 20, 90]  
# 第1轮排好序是:[20, 30, 93, 98, 26, 98, 91, 90]  
# 第2轮排好序是:[20, 26, 93, 98, 30, 98, 91, 90]  
# 第3轮排好序是:[20, 26, 30, 98, 93, 98, 91, 90]  
# 第4轮排好序是:[20, 26, 30, 90, 93, 98, 91, 98]  
# 第5轮排好序是:[20, 26, 30, 90, 91, 98, 93, 98]  
# 第6轮排好序是:[20, 26, 30, 90, 91, 93, 98, 98]  
# 第7轮排好序是:[20, 26, 30, 90, 91, 93, 98, 98]  
# 最终排好序的列表为:[20, 26, 30, 90, 91, 93, 98, 98]  


Topic 11: Rock Paper Scissors

  • When the game starts, both the user and the computer have 100 points in the initial state. A win is +10 points, and a loss is -10 points.

  • When the user scores 0 points, the game ends, prompting that the game is over and the game is lost.

  • When the user reaches 200 points, the game ends, prompting the game to end, winning the game, and outputting the current score in each round.

  • 1 stands for scissors 2 stands for rock 3 stands for paper

import random as rd  
  
print('=' * 60)  
print(' ' * 20, '剪刀石头布游戏')  
print('1代表剪刀 2代表石头 3代表布')  
  
game_info = {1: "剪刀", 2: "石头", 3: "布"}  
score = 100  
  
while True:  
    robots_choice = rd.randint(1, 3)  
    user_choice = input("请出拳")  
    if user_choice not in '123':  
        print('出拳错误,请重新出拳')  
        continue  
    user_choice = int(user_choice)  
    print('*' * 60)  
    print(f'电脑出{game_info[robots_choice]}')  
    print(f'你出{game_info[user_choice]}')  
    print('*' * 60)  
    if user_choice == 1 and robots_choice == 3 or user_choice == 2 \  
            and robots_choice == 1 or user_choice == 3 and robots_choice == 2:  
        score += 10  
        print(f'你赢得本轮游戏,当前分数为{score}')  
    elif user_choice == robots_choice:  
        print(f'本轮游戏平局,当前分数为{score}')  
    else:  
        score -= 10  
        print(f'你输了本轮游戏,当前分数{score}')  
    if score >= 200:  
        print('游戏结束,你赢得比赛')  
        break  
    elif score <= 0:  
        print('游戏结束,你输了')  
        break  


Topic 12: Happy Numbers

Under a given number, the sum of the squares of all the digits of the number is calculated. The new number obtained is the sum of the squares of all the digits again. Repeat this process, and the final result must be 1.

For example, the number: 19

  • Round 1: (1_1)+(9_9) =1 + 81 = 82

  • Round 2: (8_8)+(2_2) =64 + 4 = 68

  • Round 3: (6_6)+ (8_8) =36 + 64 = 100

  • Round 4: (1_1) + (0_0) + (0*0) = 1

def sum_square(n):  
    sum = 0  
    for i in str(n):  
        sum += int(i) ** 2  
    return sum  
  
list1 = []  
n = int(input('请输入数字:'))  
while sum_square(n) not in list1:  
    n = sum_square(n)  
    list1.append(n)  
  
if n == 1:  
    print('是快乐数')  
else:  
    print('不是快乐数')  


Topic 13: Guess age (1)

Xiao Ming took his two younger sisters to participate in the Lantern Festival Lantern Festival. When someone asked them how old they were, they said playfully: "The product of our ages is 6 times the sum of our ages." Xiao Ming added: "They are not twins, and the age difference must not be more than 8 years." Please write down the age of Xiao Ming's younger sister.

for i in range(1,100):  
    for j in range(1,i):  
        if i*j == 6*(i+j) and i-j<8:  
            print(i,j)  
  
# 15 10  


Question 14: Guess age (2)

The American mathematician N. Wiener was mentally precocious and entered college at the age of 11. He was invited to give lectures at Tsinghua University in China from 1935 to 1936.

Once, he attended an important meeting, and his young face attracted attention.

So someone asked him his age, and he replied:

"The cube of my age is a 4-digit number. The 4th power of my age is a 6-digit number. These 10 numbers contain exactly 10 numbers from 0 to 9, each occurring exactly once."

Can you please estimate how young he was at that time?

for i in range(10,30):  
    i3 = str(i ** 3)  
    i4 = str(i ** 4)  
    if len(i3) == 4 and len(i4) == 6:  
        if len(set(i3+i4)) == 10:  
            print(i)  
            print(i3 + i4)  
  
# 18  
# 5832104976 舍去  


Topic 15: Implementation of split algorithm

split is a very useful method built into python strings

  • It can cut a string into the list we want by delimiter

  • For example, now we have the string life-is-short-you-need-python. Each word is separated by the delimiter "-"

  • When we call the string split method and pass in our delimiter "-", then we will get a list in which each element is actually a substring cut out by the delimiter.

  • So how to implement this algorithm? Python's built-in split method is implemented in C language. Today we are going to write a function to achieve the same function as split.

  • Let's first talk about how to implement the algorithm. This algorithm requires us to iterate the string. We first define an initialization pointer, because when we slice, we need to start from where to slice.

  • So we first need to initialize a pointer. We can define a pointer variable with a default value of 0. Then we start iterating over the string.

  • When we encounter the first delimiter, will we get the index of the current delimiter? At this time, we will slice the string from the initial pointer to the end of the delimiter.

  • Because our strings are left-closed and right-open, and your end index is the index of the delimiter, so it will only cut to life, and we will add it to the list.

  • Immediately after adding it, we need to modify the position of the initialized pointer. Where should we modify it? Modify to the next position of the separator we encountered for the first time, which is i, and then continue to iterate

  • After iteration, the second delimiter is found. Is there another index of the delimiter? At this time, we continue to slice the string. The starting position of the slice is the pointer of your i position, and the ending position is the second - The pointer follows the rules of left closing and right opening, so our word is can also be added to the list

  • This goes until the end. When we iterate to the last character n, we find that there is no horizontal bar separator behind it. At this time, we need to process it and judge it. If the character we iterate to is The last character, then when we slice it, where should we cut it from?

  • Starting from p, if we cut to n, we can only get python, and cut one less n, so to the position of n + 1, well, if we know this process, we can use code to implement this algorithm.

def split_s(string, sep="", num=0):  
    split_words = []  
    last_index = 0  
    count = 0  
    for index, char in enumerate(string):  
        if count == num and num > 0:  
            split_words.append(string[last_index:len(string)])  
            break  
        if char == sep:  
            split_words.append(string[last_index:index])  
            last_index = index + 1  
            count += 1  
        elif index + 1 == len(string):  
            split_words.append(string[last_index:index + 1])  
    return split_words  
  
print(split_s("life-is-short-you-need-python",'-'))  
# ['life', 'is', 'short', 'you', 'need', 'python']  
  
print(split_s("life-is-short-you-need-python",'-',2))  
# ['life', 'is', 'short-you-need-python']  


Topic 16: Dayan Sequence

In ancient Chinese literature, the "Dayan Sequence" has been recorded, which is mainly used to explain the Tai Chi derivation principle in traditional Chinese culture. Its first few are: 0, 2, 4, 8, 12, 18, 24, 32, 40 , 50... The rule is: the even-numbered items are the square of the serial number divided by 2, and the odd-numbered items are the squared serial number minus 1 and divided by 2. Print the first 100 terms of the Dayan Sequence

for x in range(1,101):  
    if x % 2 == 0: # 偶数  
        a = int((x ** 2) / 2)  
    else: # 奇数  
        a = int((x ** 2 - 1) / 2)  
    print(a)  
# 0  
# 2  
# 4  
# 8  
# 12  
# 18  
# 24  
# 32  
# 40  
# 50  


Topic 17: Word Analysis

Xiaolan is learning a magical language. The words in this language are all composed of lowercase English letters. Some words are very long, far exceeding the length of normal English words. Xiao Lan couldn't remember some words after learning them for a long time. He was planning not to memorize these words completely, but to distinguish words according to which letters appeared most often in the words.

Now, please help Xiao Lan. After giving him a word, help him find the letter that appears the most and the number of times this letter appears. In fact, it means that after you enter a string, you can get the letter that appears the most and the number of times it appears in the current string.

输入:HelloWorld  
输出:  
l # 小写字母 l  
3 # 小写字母 l,出现了3次,出现次数最多  


  • We can loop and iterate the current string, and then use each current character of the string as a key value and store it in the dictionary. If the current key is in the dictionary, we add one to it.

  • If it is not there, we will initialize its number to 1, and finally we will find the most frequent key value and value value from the dictionary.

def analyse_words(words):  
    word_dict = {}  
    for i in words:  
        if i in word_dict:  
            word_dict[i] += 1  
        else:  
            word_dict[i] = 1  
    max_key = max(word_dict,key=word_dict.get)  
    print(max_key)  
    print(word_dict[max_key])  
    # l  
    # 3  
analyse_words('helloworld')  


Question 18: Use stack to print diamond shape

Enter the side length n and print the rhombus corresponding to the side length.

analyze:

  • print a few lines

  • Print several spaces and stars per line

  • The first few lines are added to the stack before printing, and the next few lines are printed using the last-in-first-out principle of the stack.

def diamond(n):  
    stack = []  
    for i in range(1, 2 * n):  
        if i <= n:  
            p_str = ' ' * (n - i) + '*' * (2 * i - 1)  
            if i != n:  
                stack.append(p_str)  
            print(p_str)  
        else:  
            print(stack.pop())  
  
diamond(5)  
  
# 为了区分我把空格换成了点  
# ....*  
# ...***  
# ..*****  
# .*******  
# *********  
# .*******  
# ..*****  
# ...***  
# ....*  


Question 19: In-depth understanding of recursive functions

  • What is a recursive function? A recursive function is a function that calls itself within its function body. Executing a recursive function will call itself repeatedly, entering a new level each time.

  • Note: Recursive functions must have an end condition.

Three elements for designing a recursive function:

  • Make it clear what your function wants to do

  • Find the end condition of recursion

  • Find the equivalence relation of a function

def p(n):  
    if n == 0:  
        return  
    print('递归前->',n)  
    p(n-1)  
    print('递归后->',n)  
p(5)  
  
# 递归前-> 5  
# 递归前-> 4  
# 递归前-> 3  
# 递归前-> 2  
# 递归前-> 1  
# 递归后-> 1  
# 递归后-> 2  
# 递归后-> 3  
# 递归后-> 4  
# 递归后-> 5  


Topic 20: Fibonacci recursive function

The Fibonacci sequence, also known as the golden section sequence, was introduced by mathematician Leonardo Fibonacci using rabbit reproduction as an example, so it is also called the "rabbit sequence". is such a sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34,…

In this sequence, the first two items are both numbers 1. Starting from the third item, each number is the sum of the previous two numbers.

Mathematical expression: f(n) = f(n-1)+f(n-2)

def fib(n):  
    if n<=2:  
        return 1  
    return fib(n-1)+fib(n-2)  
  
print(fib(10)) # 55  
print(fib(2)) # 1  


The relationship between recursion and stack. The principle of recursive function: each call will push the current call into the stack. Finally, according to the principle of last in, first out, it will keep returning to the execution process of the recursive program. We know that the call of the recursive program is a Layers down, and the return process is just the opposite, up layer by layer.

In other words: the first function call returns last, and the last function call returns first. This is the same as the "last in first out" order of the stack. Therefore, when implementing recursive calls, the stack is usually used to save the on-site data of each call:

When a function is called, the system will push the on-site data at the time of the call into the system call stack. The on-site data pushed onto the stack is called a stack frame. When the function returns, the return address must be obtained from the top of the call stack, the scene must be restored, the stack frame must be popped, and the address must be returned.

Question 21: Find the maximum of three numbers

It is known that the numbers a, b, and c are 10, 6, and 18 respectively. Find the largest number among a, b, and c (without using functions, lists, etc.). We know that the function max can directly obtain the maximum value, or the number can be Adding it to the list can also get the maximum number through sorting. We simply use the if branch to achieve this.

a, b, c = 10, 6, 18  
if a > b:  
    max_num = a  
else:  
    max_num = b  
if max_num < c:  
    max_num = c  
  
print(max_num) # 18  


Topic 22: The sum of factors "complete number"

  • What is a factor? Factors are all numbers that can divide the number, including 1 but not the number itself. For example, the factors of 8 are 1, 2, and 4

  • What is a perfect number? If a number is exactly equal to the sum of its factors, the number is called a "perfect number". Print out a perfect number within 1000, for example, 6=1+2+3, 6 is a "perfect number"

def factor_sum(n):  
    s_sum = 0  
    for i in range(1, n):  
        if n % i == 0:  
            s_sum += i  
    return s_sum  
  
for j in range(1, 1000):  
    if j == factor_sum(j):  
        print(j)  
        # 6  
        # 28  
        # 496  


Question 23: Recursive factorial summation

The factorial of a positive integer is the product of all positive integers less than or equal to that number, and the factorial of 0 is 1

For example, 5!=1_2_3_4_5 calculates 1!+2!+3!+4!+5!+…+10! Mathematical expression: f(n) = n*f(n-1):

def factor(n):  
    if n < 2:  
        return 1  
    return n * factor(n - 1)  
  
s_sum = 0  
for i in range(1, 11):  
    s_sum += factor(i)  
print(s_sum)  # 4037913  


Question 24: Valid parentheses

Given a string that only includes '(', ')', '{', '}', '[', ']', determine whether the string is valid.

A valid string must satisfy:

  • The opening bracket must be closed by a closing bracket of the same type

  • Opening brackets must be closed in the correct order

  • The empty string is considered a valid string

  • Example 1:

enter:"()"

Output: True

  • Example 2:

enter:"()[]{}"

Output: True

  • Example 3:

enter:"(]"

Output: False

  • Example 4:

enter:"([)]"

Output: False

  • Solution 1: String replacement method: Find pairs of (), [], {} in the string. After finding them, replace them with empty ones. Use a while loop to continuously determine whether there are pairs of parentheses, brackets, and braces. If they exist, Just use replace to replace it with nothing until it can no longer be replaced, and then judge whether the current string is empty. If it is empty, it means the string is valid. If it is not empty, it means the string is invalid.
def valid_str(string):  
    if len(string) % 2 == 1:  
        return False  
    while '()' in string or '[]' in string or '{}' in string:  
        string = string.replace('()', '')  
        string = string.replace('[]', '')  
        string = string.replace('{}', '')  
    return string == ''  
  
print(valid_str('()'))  # True  
print(valid_str('()[]{}'))  # True  
print(valid_str('()[]{[()]}'))  # True  
print(valid_str('()[]{[(}]}'))  # False  


  • Solution 2: Use the last-in-first-out principle of the stack to first define an empty stack and loop through the current stack. When we encounter a left bracket, we add the current left bracket to the stack. When we encounter a right bracket, we add it to the top of the stack. The elements are compared to see if they are paired parentheses. If so, the current element is popped off the stack until the string traversal is completed. Let's see if the string is empty. If it is empty, the string is Valid. If it is not empty, the string is invalid.
def valid_str(string):  
    if len(string) % 2 == 1:  
        return False  
    stack = []  
    char_dict = {  
        ')': '(',  
        '}': '{',  
        ']': '['  
    }  
    for char in string:  
        if char in char_dict:  
            # 右括号  
            if not stack or char_dict[char] != stack.pop():  
                return False  
        else:  
            # 左括号  
            stack.append(char)  
    return not stack  
  
print(valid_str('(){}[({[]})]'))  # True  
print(valid_str('(){}[({[)})]'))  # False  
print(valid_str(''))  # True  


Question 25: Two solutions to palindrome numbers

Palindrome numbers are integers that are the same in forward order (from left to right) and reverse order (from right to left). For example, 1221 is a palindrome, but 1222 is not.

  • Solution 1: Compare by reversing the strings
def is_palindrome(x):  
    if x < 0 or x > 0 and x % 10 == 0:  
        return False  
    str_x = str(x)  
    return str_x == str_x[::-1]  
  
print(is_palindrome(121))  # True  
print(is_palindrome(120))  # False  


  • Solution 2: Reverse half of the number and compare it with the first half of the number

process

  • For an integer x, reverse the second half and save it to the variable reverted

  • Each time the loop x%10 gets the last number

  • Then x/10 removes the number at the end

  • Loop end condition x<=reverted

  • Number length (odd number) 12321

  • Number length (even number) 1221

def is_palindrome(x):  
    if x < 0 or x > 0 and x % 10 == 0:  
        return False  
    reverted = 0  
    while x > reverted:  
        # 我们看下 1221  
        # 第一次循环我们需要把末尾数字1取出来 第二次取末尾数字2 我们需要把21变成12  
        reverted = reverted * 10 + x % 10  
        # 把x的末尾数字删除掉  
        x //= 10  
    return x == reverted or x == reverted // 10  
  
print(is_palindrome(1221))  # True  
print(is_palindrome(1223))  # False  
print(is_palindrome(123321))  # True  


Guess you like

Origin blog.csdn.net/chatgpt002/article/details/133034014