SoFunction
Updated on 2025-04-13

Some common Python simple algorithms are prone to errors and answer summary

Question 1: What function would you use when Python grabs remote pictures to local?

Answer:requestsIn the library()Function combinationopen()function.

Analysis: Use(url)To obtain image resources on the network, then useopen('filename', 'wb')Open a local file in binary writing mode and usewrite()The method writes the obtained content to the file. For example:

import requests

url = '/'
response = (url)
with open('local_image.jpg', 'wb') as file:
    ()

Question 2: How to implement inversion of strings in Python?

Answer: Use slice operations.

Analysis: In Python, strings can be easily reversed through the slicing function of strings. It can be achieved by using slices with a step size of -1. The sample code is as follows:

s = "Hello, World!"
reversed_s = s[::-1]
print(reversed_s)

The output will be!dlroW ,olleH

Question 3: How to check if all elements in a list are the same?

Answer: Use sets.

Analysis: You can convert the list into a collection. If the converted collection length is 1, it means that all elements in the list are the same. The sample code is as follows:

lst = [1, 1, 1, 1]
if len(set(lst)) == 1:
    print("All elements are the same.")
else:
    print("Elements are not the same.")

Question 4: How to generate a random password in Python?

Answer: UserandomModules andstringModule.

Analysis: These two modules can be used in combination to generate random passwords containing uppercase letters, lowercase letters, numbers and special characters. The sample code is as follows:

import random
import string

def generate_password(length=12):
    characters = string.ascii_letters +  + 
    password = ''.join((characters) for i in range(length))
    return password

print(generate_password())

Question 5: How to read CSV files in Python?

Answer: UsecsvModule.

Analysis:csvThe module provides a very simple way to read CSV files. AvailableObjects to read CSV files line by line. The sample code is as follows:

import csv

with open('', newline='') as csvfile:
    reader = (csvfile)
    for row in reader:
        print(row)

Question 6: How to implement singleton pattern in Python?

Answer: Use class variables and private constructors.

Analysis: Singleton pattern can be implemented by setting the constructor of the class to private and using a class variable inside the class to store a unique instance of the class. The sample code is as follows:

class Singleton:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance

# Test singleton modeobj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2)  # Output: True

Question 7: How to find duplicate elements in lists in Python?

Answer: Use the properties of sets.

Analysis: You can convert the list into a collection, then compare the elements of the original list and the collection to find elements that are not in the collection, that is, repeating elements. The sample code is as follows:

lst = [1, 2, 2, 3, 4, 4, 5]
seen = set()
duplicates = []
for item in lst:
    if item in seen:
        (item)
    else:
        (item)
print(duplicates)  # Output: [2, 4]

Question 8: How to implement bubble sorting algorithm in Python?

Answer: Use nested loops to compare adjacent elements and swap their positions.

Analysis: The outer loop traverses all elements of the list, and the inner loop is responsible for comparing the size of the current element with the next element and exchanging them if needed. The sample code is as follows:

def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n-i-1):
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]
    return arr

print(bubble_sort([64, 34, 25, 12, 22, 11, 90]))

The output will be[11, 12, 22, 25, 34, 64, 90]

Question 9: How to calculate the difference in the number of days between two dates in Python?

Answer: UsedatetimeModule.

Analysis: You can convert date strings todatetimeObject, then use the subtraction operator to calculate the difference between two dates. The sample code is as follows:

from datetime import datetime

date_format = "%Y-%m-%d"
date1 = ('2022-01-01', date_format)
date2 = ('2022-01-15', date_format)
delta = date2 - date1
print()  # Output: 14

Question 10: How to convert JSON strings to dictionary in Python?

Answer: UsejsonModularloads()function.

Analysis:()Functions can parse strings in JSON format into Python dictionary. The sample code is as follows:

import json

json_str = '{"name": "John", "age": 30, "city": "New York"}'
data = (json_str)
print(data)  # Output: {'name': 'John', 'age': 30, 'city': 'New York'}

Question 11: How to implement dictionary traversal in Python?

Answer: Use the items method or iterate the key directly. Analysis: You can traverse all key-value pairs through the dictionary items method, or iterate directly over the dictionary's keys. Here are the example codes for two methods:

my_dict = {'a': 1, 'b': 2, 'c': 3}

# Use items methodfor key, value in my_dict.items():
    print(key, value)

# Iterate the key directlyfor key in my_dict:
    print(key, my_dict[key])

Question 12: How to determine whether a number is an even number in Python?

Answer: Use the modulo operator %. Analysis: In Python, you can use the modulo operator % to determine whether a number can be divided by 2, thereby determining whether it is an even number. Here is the sample code:

number = 4
if number % 2 == 0:
    print(f"{number}It's an even number")
else:
    print(f"{number}不It's an even number")

Question 13: How to implement string splicing in Python?

Answer: Use addition operators or format strings. Analysis: You can directly use the addition operation to match the string, or use the method of formatting the string to splice the string. Here are the example codes for two methods:

str1 = "Hello"
str2 = "World"

# Use addition operatorscombined_str = str1 + " " + str2
print(combined_str)  #Output: Hello World
# Use format stringscombined_str = f"{str1} {str2}"
print(combined_str)  # Output:Hello World

Question 14: How to delete elements from list?

Answer: Use remove method or del statement or list comprehension. Analysis: You can use the remove method of the list to delete the specified element, or use the del statement to delete the element through the index, or use the list comprehension to create a new list that does not contain a certain element. Here are the example code for three methods:

numbers = [1, 2, 3, 4, 5]

# Use the remove method(3)
print(numbers)  # Output: [1, 2, 4, 5]
# Use del statementnumbers = [1, 2, 3, 4, 5]
del numbers[2]
print(numbers)  # Output: [1, 2, 4, 5]
# Use list comprehensionnumbers = [1, 2, 3, 4, 5]
numbers = [x for x in numbers if x != 3]
print(numbers)  # Output: [1, 2, 4, 5]

Question 15: How to merge two lists in Python?

Answer: Use the addition operator or extend method. Analysis: You can match and combine two lists through simple addition operations, or use the list's extend method. Here are the example codes for two methods:

list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Use addition operatorsmerged_list = list1 + list2
print(merged_list)  # Output: [1, 2, 3, 4, 5, 6]
# Use the extend methodlist1 = [1, 2, 3]
(list2)
print(list1)  # Output:[1, 2, 3, 4, 5, 6]

Question 15: How to find out the minimum and maximum values ​​in the list?

Answer:Use built-inminandmaxfunction。 Analysis: Python provides convenient built-in functions to find the minimum and maximum values ​​in a list. Here is the sample code:

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
min_value = min(numbers)
max_value = max(numbers)

print("Minimum value:", min_value)  # Output: Minimum value: 1print("Maximum value:", max_value)  # Output:Maximum value: 9

Question 16: How to check whether a string contains a substring in Python?

Answer: Use the in keyword. Parsing: In Python, you can simply use the in keyword to check whether a string contains another substring. Here is the sample code:

main_string = "Hello, world!"
sub_string = "world"

if sub_string in main_string:
    print("Substring exists in the main string")
else:
    print("The substring does not exist in the main string")

Question 17: How to implement key-value pair exchange of dictionaries in Python?

Answer: Use dictionary derivation. Analysis: You can realize the exchange of key-value pairs by traversing the dictionary's terms and exchanging keys and values ​​in the dictionary derivation formula. It should be noted that if there are duplicate values ​​in the dictionary, data will be lost after the exchange. The sample code is as follows:

original_dict = {'a': 1, 'b': 2, 'c': 3}
swapped_dict = {value: key for key, value in original_dict.items()}
print("Original dictionary:", original_dict)
print("Swapped dictionary:", swapped_dict)

Output:

Original dictionary: {'a': 1, 'b': 2, 'c': 3}
Swapped dictionary: {1: 'a', 2: 'b', 3: 'c'}

Question 18: How to calculate the greatest common divisor of two numbers in Python?

Answer: Use the Round-Transaction Division (Euclidean Algorithm). Analysis: Round-turn phase division is an ancient and efficient method to calculate the greatest common divisor (GCD) of two positive integers. The sample code is as follows:

def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a

num1 = 48
num2 = 18
print(f"The GCD of {num1} and {num2} is {gcd(num1, num2)}")

Question 19: How to implement list sorting in Python?

Answer: Use the sort() method of the list or the built-in function sorted(). Analysis: The list object has a sort() method that sorts the list in-place and can specify ascending or descending order. In addition, you can also use the built-in function sorted(), which returns a new sorted list without changing the original list. The sample code is as follows:

# Sort ascending order using the sort() method of the listmy_list = [3, 1, 4, 1, 5]
my_list.sort()
print("Sorted list (in place):", my_list)

# Use sorted() function to sort in descending ordersorted_list = sorted(my_list, reverse=True)
print("Sorted list (new list):", sorted_list)

#Output# Sorted list (in place): [1, 1, 3, 4, 5]
# Sorted list (new list): [5, 4, 3, 1, 1]

Question 20: How to get the current date and time in Python?

Answer: Use the datetime module. Analysis: Python's datetime module provides rich date and time processing functions. To get the current date and time, you can use the() function. The sample code is as follows:

from datetime import datetime

now = ()
print("Current date and time:", now)

Question 21: How to read the contents of a text file in Python?

Answer: Use the built-in function open(). Analysis: In Python, you can open the file by calling the built-in function open() and passing in the file path and pattern (for example, 'r' stands for read-only mode), and then use the read() or readlines() method of the file object to read the content. The sample code is as follows:

# Open the file in read-only modewith open('', 'r') as file:
    content = ()
    print(content)

Question 22: How to use Python to find the longest common substring?

def longest_common_substring(str1, str2):
    m = len(str1)
    n = len(str2)
    # Create a two-dimensional array to store solutions to subproblems    dp = [[0] * (n + 1) for _ in range(m + 1)]
    max_length = 0
    end_index = 0
    
    #Fill dp array    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if str1[i - 1] == str2[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
                if dp[i][j] > max_length:
                    max_length = dp[i][j]
                    end_index = i
            else:
                dp[i][j] = 0
    
    # Extract the longest common substring from the original string    longest_common_substr = str1[end_index - max_length: end_index]
    return longest_common_substr

# Test codestr1 = "abcde"
str2 = "bcd"
print("Longest Common Substring:", longest_common_substring(str1, str2))

Question 23: How to implement the algorithm that selects sorting implementation in Python?

def selection_sort(arr):
    n = len(arr)
    for i in range(n):
        # Assume that the current position i is the smallest        min_index = i
        # Check whether the following elements are smaller than the current location        for j in range(i + 1, n):
            if arr[j] < arr[min_index]:
                min_index = j
        # If smaller elements are found, swap        if min_index != i:
            arr[i], arr[min_index] = arr[min_index], arr[i]
    return arr

# Test codearr = [64, 25, 12, 22, 11]
sorted_arr = selection_sort(arr)
print("Sorted array:", sorted_arr)

Question 24: How to implement the insertion sorting algorithm in Python?

def insertion_sort(arr):
    # Iterate through all elements starting from the second element    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        # Compare the current element to the element before it. If the previous element is larger than the current element, move the previous element back one by one        while j >= 0 and key < arr[j]:
            arr[j + 1] = arr[j]
            j -= 1
        # Put the current element in the correct position        arr[j + 1] = key
    return arr

# Test codearr = [12, 11, 13, 5, 6]
sorted_arr = insertion_sort(arr)
print("Sorted array:", sorted_arr)

Question 25: How to output a nine-nine multiplication table in Python

for i in range(1, 10):
    for j in range(1, i + 1):
        print(f"{j} * {i} = {j * i}", end="\t")
    print()


# 1 * 1 = 1	
# 1 * 2 = 2	2 * 2 = 4	
# 1 * 3 = 3	2 * 3 = 6	3 * 3 = 9	
# 1 * 4 = 4	2 * 4 = 8	3 * 4 = 12	4 * 4 = 16	
# 1 * 5 = 5	2 * 5 = 10	3 * 5 = 15	4 * 5 = 20	5 * 5 = 25	
# 1 * 6 = 6	2 * 6 = 12	3 * 6 = 18	4 * 6 = 24	5 * 6 = 30	6 * 6 = 36	
# 1 * 7 = 7	2 * 7 = 14	3 * 7 = 21	4 * 7 = 28	5 * 7 = 35	6 * 7 = 42	7 * 7 = 49	
# 1 * 8 = 8	2 * 8 = 16	3 * 8 = 24	4 * 8 = 32	5 * 8 = 40	6 * 8 = 48	7 * 8 = 56	8 * 8 = 64	
# 1 * 9 = 9	2 * 9 = 18	3 * 9 = 27	4 * 9 = 36	5 * 9 = 45	6 * 9 = 54	7 * 9 = 63	8 * 9 = 72	9 * 9 = 81	

Summarize

This is the article about some common Python simple algorithms that are prone to error questions and answers. For more related Python algorithms, please search for my previous articles or continue browsing the related articles below. I hope you can support me in the future!