1.判断是不是回文数:
x = int(input("请输入一个正整数:")) x = str(x) if x == x[::-1]:print("是回文数。") else:print("不是回文数。")
2.冒泡排序
# 冒泡排序: # [30,8,-10, 50,1,3,2,9,-2] # 第一次:找到最大值 # |[8,-10,30, 1,3,2,9,-2,50] # 第二次:找到最大值 # 【-10,8,1,3,2,9,-2,30,50] # 第三次: # [-10,1,3, 2,8,-2, 9,30,50] # 第四次: # [-10,1, 2,3, -2,8,9,30,50] # 第五次: # [-10,1,2, -2,3,8,9,30,50] # 第六次: # [-10,1,-2,2,3,8,9,30,50] # 第七次: # [-10,-2,1 2,3, 8,9,30,50]def mp_sort(nums):for i in range(len(nums) - 1):for j in range(len(nums) - 1 - i):if nums[j] > nums[j + 1]:nums[j], nums[j + 1] = nums[j + 1], nums[j]return numsnums = [3, 8, -10, 50, 1, 3, 2, 9, -2] nums = mp_sort(nums) print(nums)
3.选择排序:
选择排序:
[30,8,-10,50,1,3,2,9,-2]
第一次:找到最小值
[-10, 8,30,50,1,3,2,9,-2]
第二次:找到最小值
[-10,-2,30,50,1,3, 2,9,8]
第三次:
[-10, -2,1,50, 30, 3,2,9,8]
第四次:
[-10,-2,1,2,30,3,50,9,8]
第五次:
[-10,-2,1,2,3,30,50,9,8]
第六次:
[-10,-2,1, 2,3, 8,50,9,30]
第七次:
[-10,-2,1, 2, 3, 8, 9,50,30]
from typing import List def select_sort(nums:list):for i in range(len(nums) - 1):for j in range(i + 1, len(nums)):if nums[j] < nums[i]:nums[j], nums[i] = nums[i], nums[j]return nums nums = [30, 8, -10, 50, 1, 3, 2, 9, -2] nums = select_sort(nums) print(nums)
4.插入排序:
def insert_sort(nums:list):for i in range(len(nums) - 1):for j in range(i + 1, 0, -1):if nums[j] < nums[j - 1]:nums[j], nums[j - 1] = nums[j - 1], nums[j]nums = [2, 7, 8, 9, 5, 55, 66, 77, 44, 10] insert_sort(nums) print(nums)