Python常见代码题及解法详解355


Python 凭借其简洁易读的语法和丰富的库,成为许多程序员的首选语言。然而,掌握一门编程语言不仅仅是了解语法规则,更重要的是能够运用这些规则解决实际问题。本文将深入探讨一些常见的 Python 代码题,并提供详细的解法和代码示例,帮助读者提升 Python 编程能力。

一、 字符串操作

字符串操作是 Python 编程中非常常见的一类问题。以下是一些例子:

1. 反转字符串:

编写一个函数,将输入的字符串反转。例如,输入 "hello",输出 "olleh"。
def reverse_string(s):
return s[::-1]
print(reverse_string("hello")) # 输出 olleh

2. 判断回文字符串:

编写一个函数,判断输入的字符串是否为回文串(正读反读都一样)。例如,"madam" 和 "racecar" 是回文串。
def is_palindrome(s):
s = () #忽略大小写
return s == s[::-1]
print(is_palindrome("madam")) # 输出 True
print(is_palindrome("hello")) # 输出 False

3. 字符串计数:

编写一个函数,统计字符串中每个字符出现的次数。
from collections import Counter
def count_chars(s):
return Counter(s)
print(count_chars("hello")) # 输出 Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})


二、 列表和数组操作

列表和数组是 Python 中常用的数据结构,对其操作也是面试和编程中经常遇到的。

1. 列表排序:

编写一个函数,对输入的列表进行排序(升序或降序)。
def sort_list(lst, reverse=False):
(reverse=reverse)
return lst
print(sort_list([3, 1, 4, 1, 5, 9, 2, 6])) # 输出 [1, 1, 2, 3, 4, 5, 6, 9]
print(sort_list([3, 1, 4, 1, 5, 9, 2, 6], reverse=True)) # 输出 [9, 6, 5, 4, 3, 2, 1, 1]

2. 列表去重:

编写一个函数,去除列表中重复的元素,并保持原有顺序。
def remove_duplicates(lst):
return list((lst))
print(remove_duplicates([1, 2, 2, 3, 4, 4, 5])) # 输出 [1, 2, 3, 4, 5]

3. 查找最大/最小值:

编写一个函数,查找列表中的最大值和最小值。
def find_min_max(lst):
return min(lst), max(lst)
print(find_min_max([1, 5, 2, 8, 3])) # 输出 (1, 8)


三、 算法题

一些算法题能够很好地考察编程能力和逻辑思维。

1. 斐波那契数列:

编写一个函数,计算斐波那契数列的第 n 个数。
def fibonacci(n):
if n

2025-05-13


上一篇:Python缓存文件:提升程序性能的实用指南

下一篇:深入理解Python中的normal函数:类型提示、异常处理及最佳实践