技术文摘
令人惊叹!这 20 段 Python 代码请务必记住
2024-12-31 08:25:10 小编
令人惊叹!这 20 段 Python 代码请务必记住
在 Python 编程的世界里,掌握一些关键的代码片段可以极大地提高工作效率和编程能力。以下是为您精心挑选的 20 段令人惊叹的 Python 代码,务必记住它们!
- 快速排序算法
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)
- 斐波那契数列生成
def fibonacci(n):
fib_seq = [0, 1]
while len(fib_seq) < n:
fib_seq.append(fib_seq[-1] + fib_seq[-2])
return fib_seq
- 计算列表元素的平均值
def average(lst):
return sum(lst) / len(lst)
- 检查回文
def is_palindrome(s):
return s == s[::-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
- 找出列表中的最大值和最小值
def find_max_min(lst):
return max(lst), min(lst)
- 字符串反转
def reverse_string(s):
return s[::-1]
- 计算阶乘
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 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]
- 二分查找
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
- 生成随机密码
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
- 计算两个日期之间的天数差
from datetime import date
def days_between_dates(date1, date2):
return (date2 - date1).days
- 矩阵转置
def transpose_matrix(matrix):
return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
- 统计字符串中单词的出现次数
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
- 素数判断
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
- 汉诺塔问题
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)
- 链表节点类
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
- 二叉树节点类
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
- 读取文件并统计单词数量
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
- 发送电子邮件
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 编程技能必将得到显著提升!
- Go 语言成为 DevOps 时代的理想编程语言,JS 退位
- 大数据揭示:2018 年应学习的技术
- 京东京麦:微服务架构中的高可用网关及容错实践
- 程序员的故事:午餐不免费
- 询问 2300 个开发者,总结 JavaScript 的十项要点
- 如何优化遗留代码库,你了解吗?
- JavaScript:既“老”又潮,别再黑它
- 十大编程挑战网站助您速升编程能力
- 单层基础神经网络用于手写字识别的实现
- 前端领域 2017 年的变化与 2018 年的期待
- 2017 年编程语言排名:PHP 居第 8,Java 列第 3!
- 前端本地存储超全讲解
- FastDFS 并发存疑:一次问题排查经历
- 王健林旗下万达网科超千名员工被集体裁员 已接通知
- 美团点评高可用数据库架构的演进之路:屡踩坑洼