令人惊叹!这 20 段 Python 代码请务必记住

2024-12-31 08:25:10   小编

令人惊叹!这 20 段 Python 代码请务必记住

在 Python 编程的世界里,掌握一些关键的代码片段可以极大地提高工作效率和编程能力。以下是为您精心挑选的 20 段令人惊叹的 Python 代码,务必记住它们!

  1. 快速排序算法
def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quick_sort(left) + middle + quick_sort(right)
  1. 斐波那契数列生成
def fibonacci(n):
    fib_seq = [0, 1]
    while len(fib_seq) < n:
        fib_seq.append(fib_seq[-1] + fib_seq[-2])
    return fib_seq
  1. 计算列表元素的平均值
def average(lst):
    return sum(lst) / len(lst)
  1. 检查回文
def is_palindrome(s):
    return s == s[::-1]
  1. 合并两个已排序的列表
def merge_sorted_lists(list1, list2):
    merged_list = []
    i = j = 0
    while i < len(list1) and j < len(list2):
        if list1[i] < list2[j]:
            merged_list.append(list1[i])
            i += 1
        else:
            merged_list.append(list2[j])
            j += 1
    merged_list.extend(list1[i:])
    merged_list.extend(list2[j:])
    return merged_list
  1. 找出列表中的最大值和最小值
def find_max_min(lst):
    return max(lst), min(lst)
  1. 字符串反转
def reverse_string(s):
    return s[::-1]
  1. 计算阶乘
def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)
  1. 冒泡排序
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]
  1. 二分查找
def binary_search(arr, x):
    low = 0
    high = len(arr) - 1

    while low <= high:
        mid = (low + high) // 2

        if arr[mid] == x:
            return mid
        elif arr[mid] < x:
            low = mid + 1
        else:
            high = mid - 1

    return -1
  1. 生成随机密码
import random
import string

def generate_password(length):
    all_characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(random.choice(all_characters) for i in range(length))
    return password
  1. 计算两个日期之间的天数差
from datetime import date

def days_between_dates(date1, date2):
    return (date2 - date1).days
  1. 矩阵转置
def transpose_matrix(matrix):
    return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
  1. 统计字符串中单词的出现次数
def word_count(s):
    words = s.split()
    word_count_dict = {}
    for word in words:
        if word in word_count_dict:
            word_count_dict[word] += 1
        else:
            word_count_dict[word] = 1
    return word_count_dict
  1. 素数判断
def is_prime(n):
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True
  1. 汉诺塔问题
def hanoi(n, source, auxiliary, destination):
    if n == 1:
        print(f"Move disk 1 from {source} to {destination}")
        return
    hanoi(n - 1, source, destination, auxiliary)
    print(f"Move disk {n} from {source} to {destination}")
    hanoi(n - 1, auxiliary, source, destination)
  1. 链表节点类
class Node:
    def __init__(self, data=None):
        self.data = data
        self.next = None
  1. 二叉树节点类
class TreeNode:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None
  1. 读取文件并统计单词数量
def count_words_in_file(file_path):
    word_count = {}
    with open(file_path, 'r') as file:
        for line in file:
            words = line.split()
            for word in words:
                if word in word_count:
                    word_count[word] += 1
                else:
                    word_count[word] = 1
    return word_count
  1. 发送电子邮件
import smtplib
from email.mime.text import MIMEText

def send_email(subject, body, to_email, from_email, password):
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = to_email

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(from_email, password)
    server.sendmail(from_email, to_email, msg.as_string())
    server.quit()

这些 Python 代码涵盖了各种常见的编程任务和算法,熟练掌握它们将使您在编程之路上更加得心应手。不断练习和运用这些代码,您的 Python 编程技能必将得到显著提升!

TAGS: 编程技巧 令人惊叹 Python 代码 务必记住

欢迎使用万千站长工具!

Welcome to www.zzTool.com