Python
100 道 Python 编程题及其答案,分为简单、中等和偏难三个级别:
简单级别 (30 题)
- 打印"Hello, World!"
print("Hello, World!")
- 计算两个数的和
def add(a, b):
return a + b
print(add(3, 4)) # 输出: 7
- 判断奇偶数
def is_even(n):
return n % 2 == 0
print(is_even(4)) # 输出: True
print(is_even(5)) # 输出: False
- 计算列表元素的平均值
def average(numbers):
return sum(numbers) / len(numbers)
print(average([1, 2, 3, 4, 5])) # 输出: 3.0
- 反转字符串
def reverse_string(s):
return s[::-1]
print(reverse_string("hello")) # 输出: "olleho"
- 计算阶乘
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
print(factorial(5)) # 输出: 120
- 斐波那契数列
def fibonacci(n):
fib_seq = [0, 1]
for i in range(2, n):
fib_seq.append(fib_seq[-1] + fib_seq[-2])
return fib_seq
print(fibonacci(10)) # 输出: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
- 最大公约数
def gcd(a, b):
while b:
a, b = b, a % b
return a
print(gcd(54, 24)) # 输出: 6
- 字符串是否为回文
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("racecar")) # 输出: True
print(is_palindrome("hello")) # 输出: False
- 生成随机数
import random
print(random.randint(1, 100))
- 列表求和
def sum_list(lst):
return sum(lst)
print(sum_list([1, 2, 3, 4])) # 输出: 10
- 统计字符串中字母出现的次数
def count_letters(s):
return {char: s.count(char) for char in set(s)}
print(count_letters("hello")) # 输出: {'h': 1, 'e': 1, 'l': 2, 'o': 1}
- 去除列表中的重复元素
def remove_duplicates(lst):
return list(set(lst))
print(remove_duplicates([1, 2, 2, 3, 4, 4, 5])) # 输出: [1, 2, 3, 4, 5]
- 冒泡排序
def bubble_sort(lst):
n = len(lst)
for i in range(n):
for j in range(0, n-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
return lst
print(bubble_sort([5, 1, 4, 2, 8])) # 输出: [1, 2, 4, 5, 8]
- 倒序输出列表
def reverse_list(lst):
return lst[::-1]
print(reverse_list([1, 2, 3, 4, 5])) # 输出: [5, 4, 3, 2, 1]
- 找出列表中的最大值和最小值
def min_max(lst):
return min(lst), max(lst)
print(min_max([1, 2, 3, 4, 5])) # 输出: (1, 5)
- 计算直角三角形的斜边
def hypotenuse(a, b):
return (a**2 + b**2) ** 0.5
print(hypotenuse(3, 4)) # 输出: 5.0
- 字符串长度
def string_length(s):
return len(s)
print(string_length("hello")) # 输出: 5
- 合并两个列表
def merge_lists(lst1, lst2):
return lst1 + lst2
print(merge_lists([1, 2], [3, 4])) # 输出: [1, 2, 3, 4]
- 列表元素的平方
def square_elements(lst):
return [x**2 for x in lst]
print(square_elements([1, 2, 3, 4])) # 输出: [1, 4, 9, 16]
- 生成一个包含指定范围内所有偶数的列表
def even_numbers(start, end):
return [x for x in range(start, end+1) if x % 2 == 0]
print(even_numbers(1, 10)) # 输出: [2, 4, 6, 8, 10]
- 将列表中的所有字符串转换为大写
def uppercase_strings(lst):
return [x.upper() for x in lst]
print(uppercase_strings(["hello", "world"])) # 输出: ["HELLO", "WORLD"]
- 将列表中的所有数字转换为字符串
def numbers_to_strings(lst):
return [str(x) for x in lst]
print(numbers_to_strings([1, 2, 3])) # 输出: ["1", "2", "3"]
- 从字符串中移除所有元音字母
def remove_vowels(s):
vowels = "aeiouAEIOU"
return "".join([char for char in s if char not in vowels])
print(remove_vowels("hello world")) # 输出: "hll wrld"
- 计算一个字符串中所有数字的和
def sum_of_digits(s):
return sum(int(char) for char in s if char.isdigit())
print(sum_of_digits("a1b2c3")) # 输出: 6
- 将一个列表切分为指定大小的子列表
def split_list(lst, size):
return [lst[i:i+size] for i in range(0, len(lst), size)]
print(split_list([1, 2, 3, 4, 5, 6], 2)) # 输出: [[1, 2], [3, 4], [5, 6]]
- 将一个数字列表转换为它们的平方根列表
import math
def sqrt_elements(lst):
return [math.sqrt(x) for x in lst]
print(sqrt_elements([1, 4, 9, 16])) # 输出: [1.0, 2.0, 3.0, 4.0]
- 判断一个列表中的所有元素是否唯一
def all_unique(lst):
return len(lst) == len(set(lst))
print(all_unique([1, 2, 3, 4])) # 输出: True
print(all_unique([1, 2, 2, 3])) # 输出: False
- 从列表中移除所有指定的值
def remove_all(lst, value):
return [x for x in lst if x != value]
print(remove_all([1, 2, 3, 2, 4], 2)) # 输出: [1, 3, 4]
- 合并两个字典
def merge_dicts(dict1, dict2):
result = dict1.copy()
result.update(dict2)
return result
print(merge_dicts({"a": 1, "b": 2}, {"b": 3, "c": 4})) # 输出: {"a": 1, "b": 3, "c": 4}
中等级别 (50 题)
- 统计文件中的单词数
def count_words(file_path):
with open(file_path, 'r') as file:
text = file.read()
words = text.split()
return len(words)
print(count_words("example.txt"))
- 二分查找
def binary_search(lst, target):
left, right = 0, len(lst) - 1
while left <= right:
mid = (left + right) // 2
if lst[mid] == target:
return mid
elif lst[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
print(binary_search([1, 2, 3, 4, 5], 3)) # 输出: 2
- 斐波那契数列(递归)
def fibonacci_recursive(n):
if n <= 1:
return n
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
print(fibonacci_recursive(10)) # 输出: 55
- 判断素数
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
print(is_prime(29)) # 输出: True
print(is_prime(15)) # 输出: False
- 阶乘(递归)
def factorial_recursive(n):
if n == 0:
return 1
return n * factorial_recursive(n-1)
print(factorial_recursive(5)) # 输出: 120
- 合并两个有序列表
def merge_sorted_lists(lst1, lst2):
result = []
i = j = 0
while i < len(lst1) and j < len(lst2):
if lst1[i] < lst2[j]:
result.append(lst1[i])
i += 1
else:
result.append(lst2[j])
j += 1
result.extend(lst1[i:])
result.extend(lst2[j:])
return result
print(merge_sorted_lists([1, 3, 5], [2, 4, 6])) # 输出: [1, 2, 3, 4, 5, 6]
- 矩阵转置
def transpose_matrix(matrix):
return [list(row) for row in zip(*matrix)]
matrix = [
[1, 2, 3], [4, 5, 6], [7, 8, 9]
]
print(transpose_matrix(matrix)) # 输出: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
- 计算文件的 SHA256 哈希值
import hashlib
def file_sha256(file_path):
sha256_hash = hashlib.sha256()
with open(file_path, "rb") as f:
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
print(file_sha256("example.txt"))
- 实现栈数据结构
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
return self.stack.pop()
def peek(self):
return self.stack[-1]
def is_empty(self):
return len(self.stack) == 0
s = Stack()
s.push(1)
s.push(2)
print(s.pop()) # 输出: 2
print(s.peek()) # 输出: 1
- 实现队列数据结构
class Queue:
def __init__(self):
self.queue = []
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
return self.queue.pop(0)
def front(self):
return self.queue[0]
def is_empty(self):
return len(self.queue) == 0
q = Queue()
q.enqueue(1)
q.enqueue(2)
print(q.dequeue()) # 输出: 1
print(q.front()) # 输出: 2
- 列表中第 K 大的元素
def kth_largest(lst, k):
return sorted(lst, reverse=True)[k-1]
print(kth_largest([3, 2, 1, 5, 6, 4], 2)) # 输出: 5
- 合并字典
def merge_dicts(dict1, dict2):
return {**dict1, **dict2}
print(merge_dicts({"a": 1}, {"b": 2})) # 输出: {'a': 1, 'b': 2}
- 找出列表中的众数
from collections import Counter
def mode(lst):
data = Counter(lst)
return data.most_common(1)[0][0]
print(mode([1, 2, 2, 3, 3, 3])) # 输出: 3
- 计算字符串的编辑距离
def edit_distance(s1, s2):
m, n = len(s1), len(s2)
dp = [[0] * (n+1) for _ in range(m+1)]
for i in range(m+1):
for j in range(n+1):
if i == 0:
dp[i][j] = j
elif j == 0:
dp[i][j] = i
elif s1[i-1] == s2[j-1]:
dp[i][j] = dp[i-1][j-1]
else:
dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
return dp[m][n]
print(edit_distance("kitten", "sitting")) # 输出: 3
- 计算字符串的最长公共子序列
def lcs(s1, s2):
m, n = len(s1), len(s2)
dp = [[0] * (n+1) for _ in range(m+1)]
for i in range(1, m+1):
for j in range(1, n+1):
if s1[i-1] == s2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
return dp[m][n]
print(lcs("abcde", "ace")) # 输出: 3
- 实现一个简单的银行账户类
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self.balance
def withdraw(self, amount):
if amount > self.balance:
return "Insufficient funds"
self.balance -= amount
return self.balance
account = BankAccount("John Doe", 100)
print(account.deposit(50)) # 输出: 150
print(account.withdraw(75)) # 输出: 75
- 约瑟夫环问题
def josephus_problem(n, k):
people = list(range(1, n+1))
index = 0
while len(people) > 1:
index = (index + k - 1) % len(people)
people.pop(index)
return people[0]
print(josephus_problem(7, 3)) # 输出: 4
- 判断两个字符串是否为变位词
def are_anagrams(s1, s2):
return sorted(s1) == sorted(s2)
print(are_anagrams("listen", "silent")) # 输出: True
print(are_anagrams("hello", "world")) # 输出: False
- 实现一个基本的 LRU 缓存机制
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.cache = OrderedDict()
self.capacity = capacity
def get(self, key):
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key, value):
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.capacity
:
self.cache.popitem(last=False)
lru_cache = LRUCache(2)
lru_cache.put(1, 1)
lru_cache.put(2, 2)
print(lru_cache.get(1)) # 输出: 1
lru_cache.put(3, 3)
print(lru_cache.get(2)) # 输出: -1
- 查找列表中的所有独特元素
def unique_elements(lst):
return list(set(lst))
print(unique_elements([1, 2, 2, 3, 4, 4, 5])) # 输出: [1, 2, 3, 4, 5]
- 实现一个基本的发布-订阅模式
class Publisher:
def __init__(self):
self.subscribers = set()
def subscribe(self, subscriber):
self.subscribers.add(subscriber)
def unsubscribe(self, subscriber):
self.subscribers.remove(subscriber)
def notify(self, message):
for subscriber in self.subscribers:
subscriber.update(message)
class Subscriber:
def __init__(self, name):
self.name = name
def update(self, message):
print(f"{self.name} received message: {message}")
pub = Publisher()
sub1 = Subscriber("Subscriber 1")
sub2 = Subscriber("Subscriber 2")
pub.subscribe(sub1)
pub.subscribe(sub2)
pub.notify("Hello, Subscribers!")
- 实现一个简单的命令行计算器
def calculator():
while True:
try:
expr = input("Enter expression (or 'exit' to quit): ")
if expr.lower() == 'exit':
break
print(eval(expr))
except Exception as e:
print(f"Error: {e}")
calculator()
- 统计字符串中的字符频率
from collections import Counter
def char_frequency(s):
return dict(Counter(s))
print(char_frequency("hello world")) # 输出: {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd':
1}
- 实现一个简单的链表
class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def insert(self, value):
new_node = ListNode(value)
if not self.head:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node
def display(self):
current = self.head
while current:
print(current.value, end=" -> ")
current = current.next
print("None")
ll = LinkedList()
ll.insert(1)
ll.insert(2)
ll.insert(3)
ll.display() # 输出: 1 -> 2 -> 3 -> None
- 找出列表中的第二大元素
def second_largest(lst):
unique_elements = list(set(lst))
unique_elements.sort(reverse=True)
return unique_elements[1]
print(second_largest([1, 2, 3, 4, 5])) # 输出: 4
- 统计文件中的行数
def count_lines(file_path):
with open(file_path, 'r') as file:
return sum(1 for _ in file)
print(count_lines("example.txt"))
- 实现一个简单的观察者模式
class Observer:
def update(self, message):
raise NotImplementedError
class ConcreteObserver(Observer):
def __init__(self, name):
self.name = name
def update(self, message):
print(f"{self.name} received: {message}")
class Subject:
def __init__(self):
self.observers = []
def attach(self, observer):
self.observers.append(observer)
def detach(self, observer):
self.observers.remove(observer)
def notify(self, message):
for observer in self.observers:
observer.update(message)
subject = Subject()
observer1 = ConcreteObserver("Observer 1")
observer2 = ConcreteObserver("Observer 2")
subject.attach(observer1)
subject.attach(observer2)
subject.notify("Hello Observers!")
- 求一个字符串中的最长回文子串
def longest_palindromic_substring(s):
def expand_around_center(s, left, right):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return s[left+1:right]
longest = ""
for i in range(len(s)):
odd_palindrome = expand_around_center(s, i, i)
even_palindrome = expand_around_center(s, i, i+1)
longest = max(longest, odd_palindrome, even_palindrome, key=len)
return longest
print(longest_palindromic_substring("babad")) # 输出: "bab" 或 "aba"
- 实现一个简单的状态机
class StateMachine:
def __init__(self):
self.state = "A"
def on_event(self, event):
if self.state == "A":
if event == "toB":
self.state = "B" elif self.state == "B":
if event == "toA":
self.state = "A" def __str__(self):
return self.state
sm = StateMachine()
print(sm) # 输出: A
sm.on_event("toB")
print(sm) # 输出: B
sm.on_event("toA")
print(sm) # 输出: A
- 实现一个简单的排序算法(选择排序)
def selection_sort(lst):
for i in range(len(lst)):
min_idx = i
for j in range(i+1, len(lst)):
if lst[j] < lst[min_idx]:
min_idx = j
lst[i], lst[min_idx] = lst[min_idx], lst[i]
return lst
print(selection_sort([64, 25, 12, 22, 11])) # 输出: [11, 12, 22, 25, 64]
- 将两个有序列表合并为一个新的有序列表
def merge_sorted_lists(lst1, lst2):
merged_list = []
i = j = 0
while i < len(lst1) and j < len(lst2):
if lst1[i] < lst2[j]:
merged_list.append(lst1[i])
i += 1
else:
merged_list.append(lst2[j])
j += 1
while i < len(lst1):
merged_list.append(lst1[i])
i += 1
while j < len(lst2):
merged_list.append(lst2[j])
j += 1
return merged_list
print(merge_sorted_lists([1, 3, 5], [2, 4, 6])) # 输出: [1, 2, 3, 4, 5, 6]
- 找出列表中所有出现次数超过 n/2 的元素
def majority_element(lst):
counts = {}
for num in lst:
counts[num] = counts.get(num, 0) + 1
majority_count = len(lst) // 2
return [num for num, count in counts.items() if count > majority_count]
print(majority_element([3, 3, 4, 2, 4, 4, 2, 4, 4])) # 输出: [4]
- 找出两个列表的交集
def intersection(lst1, lst2):
return list(set(lst1) & set(lst2))
print(intersection([1, 2, 2, 1], [2, 2])) # 输出: [2]
- 判断一个字符串是否为合法的括号序列
def is_valid_parentheses(s):
stack = []
mapping = {")": "(", "}": "{", "]": "["}
for char in s:
if char in mapping:
top_element = stack.pop() if stack else '#' if mapping[char] != top_element:
return False
else:
stack.append(char)
return not stack
print(is_valid_parentheses("()[]{}")) # 输出: True
print(is_valid_parentheses("(]")) # 输出: False
- 计算列表中所有数的乘积
def product(lst):
result = 1
for num in lst:
result *= num
return result
print(product([1, 2, 3, 4])) # 输出: 24
- 将字符串转为驼峰命名法
def to_camel_case(s):
s = s.replace("-", " ").replace("_", " ")
return s.split()[0] + ''.join(word.capitalize() for word in s.split()[1:])
print(to_camel_case("the-stealth-warrior")) # 输出: theStealthWarrior
print(to_camel_case("The_Stealth_Warrior")) # 输出: TheStealthWarrior
- 判断一个字符串是否为回文
def is_palindrome(s):
s = ''.join(filter(str.isalnum, s)).lower()
return s == s[::-1]
print(is_palindrome("A man, a plan, a canal: Panama")) # 输出: True
print(is_palindrome("race a car")) # 输出: False
- 找出列表中第一个缺失的正整数
def first_missing_positive(nums):
nums = [num for num in nums if num > 0]
num_set = set(nums)
i = 1
while i in num_set:
i += 1
return i
print(first_missing_positive([3, 4, -1, 1])) # 输出: 2
- 找出两个列表的差集
def difference(lst1, lst2):
return list(set(lst1) - set(lst2))
print(difference([1, 2, 3], [2, 3, 4])) # 输出: [1]
- 生成斐波那契数列的前 n 个数
def fibonacci(n):
fib_sequence = [0, 1]
while len(fib_sequence) < n:
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence[:n]
print(fibonacci(10)) # 输出: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
- 找出列表中的所有重复元素
def duplicates(lst):
from collections import Counter
return [item for item, count in Counter(lst).items() if count > 1]
print(duplicates([1, 2, 2, 3, 4, 4, 5])) # 输出: [2, 4]
- 将二进制数转换为十进制数
def binary_to_decimal(binary):
return int(binary, 2)
print(binary_to_decimal("1101")) # 输出: 13
- 将十进制数转换为二进制数
def decimal_to_binary(decimal):
return bin(decimal)[2:]
print(decimal_to_binary(13)) # 输出: 1101
- 计算两个日期之间的天数
from datetime import datetime
def days_between_dates(date1, date2):
date_format = "%Y-%m-%d" a = datetime.strptime(date1, date_format)
b = datetime.strptime(date2, date_format)
delta = b - a
return delta.days
print(days_between_dates("2023-01-01", "2024-01-01")) # 输出: 365
- 统计一个数字在列表中出现的次数
def count_occurrences(lst, number):
return lst.count(number)
print(count_occurrences([1, 2, 2, 3, 4, 2, 5], 2)) # 输出: 3
- 生成一个包含 n 个随机整数的列表
import random
def random_integers(n, lower_bound, upper_bound):
return [random.randint(lower_bound, upper_bound) for _ in range(n)]
print(random_integers(5, 1, 10)) # 输出: 一个包含 5 个 1 到 10 之间的随机整数的列表
- 计算两个字符串的汉明距离
def hamming_distance(s1, s2):
return sum(c1 != c2 for c1, c2 in zip(s1, s2))
print(hamming_distance("karolin", "kathrin")) # 输出: 3
- 将列表分成指定大小的块
def chunk_list(lst, chunk_size):
return [lst[i:i + chunk_size] for i in range(0, len(lst), chunk_size)]
print(chunk_list([1, 2, 3, 4, 5, 6, 7, 8], 3)) # 输出: [[1, 2, 3], [4, 5, 6], [7, 8]]
- 生成指定范围内的素数列表
def primes_in_range(start, end):
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
return [n for n in range(start, end + 1) if is_prime(n)]
print(primes_in_range(10, 50)) # 输出: [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
- 找出列表中的所有独特元素
def unique_elements(lst):
return list(set(lst))
print(unique_elements([1, 2, 2, 3, 4, 4, 5])) # 输出: [1, 2, 3, 4, 5]
- 判断一个数是否为丑数(Ugly Number)
def is_ugly(num):
if num <= 0:
return False
for p in [2, 3, 5]:
while num % p == 0:
num //= p
return num == 1
print(is_ugly(6)) # 输出: True
print(is_ugly(14)) # 输出: False
- 计算一个数的阶乘
def factorial(n):
if n == 0:
return 1
result = 1
for i in range(1, n + 1):
result *= i
return result
print(factorial(5)) # 输出: 120
- 生成一个包含前 n 个素数的列表
def first_n_primes(n):
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
primes = []
num = 2
while len(primes) < n:
if is_prime(num):
primes.append(num)
num += 1
return primes
print(first_n_primes(10)) # 输出: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
- 找出两个有序列表的中位数
def find_median_sorted_arrays(nums1, nums2):
merged = sorted(nums1 + nums2)
mid = len(merged) // 2
if len(merged) % 2 == 0:
return (merged[mid - 1] + merged[mid]) / 2
else:
return merged[mid]
print(find_median_sorted_arrays([1, 3], [2])) # 输出: 2.0
print(find_median_sorted_arrays([1, 2], [3, 4])) # 输出: 2.5
- 实现一个基本的二叉搜索树
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, value):
new_node = TreeNode(value)
if not self.root:
self.root = new_node
return
current = self.root
while True:
if value < current.value:
if current.left is None:
current.left = new_node
return
current = current.left
else:
if current.right is None:
current.right = new_node
return
current = current.right
def search(self, value):
current = self.root
while current:
if current.value == value:
return True
elif value < current.value:
current = current.left
else:
current = current.right
return False
def inorder_traversal(self, node, visit):
if node:
self.inorder_traversal(node.left, visit)
visit(node.value)
self.inorder_traversal(node.right, visit)
bst = BinarySearchTree()
bst.insert(5)
bst.insert(3)
bst.insert(7)
bst.insert(2)
bst.insert(4)
bst.insert(6)
bst.insert(8)
print(bst.search(4)) # 输出: True
print(bst.search(9)) # 输出: False
bst.inorder_traversal(bst.root, print) # 输出: 2 3 4 5 6 7 8
- 计算一个数的数字和
def digit_sum(n):
return sum(int(digit) for digit in str(n))
print(digit_sum(12345)) # 输出: 15
- 找出列表中的最大和最小元素
def max_and_min(lst):
return max(lst), min(lst)
print(max_and_min([3, 5, 1, 2, 4, 8])) # 输出: (8, 1)
- 判断一个字符串是否为变位词(Anagram)
def is_anagram(s1, s2):
return sorted(s1) == sorted(s2)
print(is_anagram("listen", "silent")) # 输出: True
print(is_anagram("hello", "world")) # 输出: False
- 找出列表中第 k 大的元素
def kth_largest_element(lst, k):
return sorted(lst, reverse=True)[k - 1]
print(kth_largest_element([3, 2, 1, 5, 6, 4], 2)) # 输出: 5
- 计算一个数的各个位数的积
def digit_product(n):
product = 1
for digit in str(n):
product *= int(digit)
return product
print(digit_product(1234)) # 输出: 24
``` 91. **判断一个数是否为回文数**
```python
def is_palindrome_number(n):
return str(n) == str(n)[::-1]
print(is_palindrome_number(121)) # 输出: True
print(is_palindrome_number(123)) # 输出: False
- 生成一个随机密码
import string
import random
def generate_password(length):
characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(characters) for _ in range(length))
print(generate_password(12)) # 输出: 一个 12 位的随机密码
- 实现一个简单的 LRU 缓存
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.cache = OrderedDict()
self.capacity = capacity
def get(self, key):
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(self, key, value):
if key in self.cache:
self.cache.move_to_end(key)
self.cache[key] = value
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
lru_cache = LRUCache(2)
lru_cache.put(1, 1)
lru_cache.put(2, 2)
print(lru_cache.get(1)) # 输出: 1
lru_cache.put(3, 3)
print(lru_cache.get(2)) # 输出: -1
- 生成一个唯一的随机字符串
import uuid
def unique_random_string():
return str(uuid.uuid4())
print(unique_random_string()) # 输出: 一个唯一的随机字符串
``` 95. **计算两个数的最大公约数**
```python
def gcd(a, b):
while b:
a, b = b, a % b
return a
print(gcd(48, 18)) # 输出: 6
- 计算两个数的最小公倍数
def lcm(a, b):
def gcd(a, b):
while b:
a, b = b, a % b
return a
return abs(a * b) // gcd(a, b)
print(lcm(4, 5)) # 输出: 20
``` 97. **找出字符串中的所有排列**
```python
from itertools import permutations
def string_permutations(s):
return [''.join(p) for p in permutations(s)]
print(string_permutations("abc")) # 输出: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
- 计算一个数的斐波那契数列位置的值
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return b
print(fibonacci(10)) # 输出: 55
- 将秒数转换为小时、分钟和秒
def convert_seconds(seconds):
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
return hours, minutes, seconds
print(convert_seconds(3661)) # 输出: (1, 1, 1)
- 查找两个字符串的最长公共子序列
def longest_common_subsequence(s1, s2):
dp = [[0] * (len(s2) + 1) for _ in range(len(s1) + 1)]
for i in range(1, len(s1) + 1):
for j in range(1, len(s2) + 1):
if s1[i - 1] == s2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[-1][-1]
print(longest_common_subsequence("abcde", "ace")) # 输出: 3
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】