首页 / 资讯中心 / 文章详情

Python入门经典题目实战应用指南

Python入门经典题目实战应用指南 ★ FEATURED ARTICLE
前言入门阶段刷的那些经典题——反转字符串、判断回文、统计词频、字符串去重、单词计数——看着零散其实考的是同一批基本功索引与切片、循环与条件、字典与计数器、以及排序。把这些基本功用对题目本身往往只有几行用错就会写出又长又慢的代码。这里要澄清一个常见的做法误区很多教程把字符串去重判断回文写成手写双层循环然后说这是算法思维。但 Python 的标准库为这类需求准备了更合适的工具——切片[::-1]、dict.fromkeys、collections.Counter、sorted。先用对工具再谈优化这是本文的基调。本文挑选几道最有代表性的入门题每题给出可直接运行的写法并说明它考的知识点。代码基于 Python 3.8 及以上。Python 2.7 已于 2020 年 1 月 1 日停止维护本文一律用 Python 3 的写法。一、反转与回文反转是一行的事切片[::-1]用负步长从后往前取。# 适用于 Python 3.8s helloprint(s[::-1]) # ollehdef is_palindrome(s: str) - bool:return s s[::-1]print(is_palindrome(level)) # Trueprint(is_palindrome(Level)) # False 大小写不同如果要忽略大小写和空格的回文判定先归一化再比# 适用于 Python 3.8def is_loose_palindrome(s: str) - bool:normalized [ch.lower() for ch in s if ch.isalnum()]t .join(normalized)return t t[::-1]print(is_loose_palindrome(A man, a plan, a canal: Panama)) # Trueisalnum()过滤掉标点和空格lower()抹平大小写。注意反转用[::-1]比手写循环清晰得多。二、词频统计统计每个字符或每个单词出现多少次是入门高频题。collections.Counter就是为这件事准备的Counter(iterableNone, /, **kwds)# 适用于 Python 3.8from collections import Counterprint(Counter(hello))# Counter({l: 2, h: 1, e: 1, o: 1})words the cat the hat the.split()c Counter(words)print(c.most_common(2)) # [(the, 3), (cat, 1)]print(c[dog]) # 0 缺键返回 0不抛异常Counter有两个好用的点取不存在的键返回0普通字典会抛KeyError以及most_common(n)直接给出出现最多的前 n 项。要按大小写无关统计先统一成casefold()# 适用于 Python 3.8from collections import Countertext The the THEprint(Counter(w.casefold() for w in text.split())) # Counter({the: 3})三、字符串去重且保持顺序去掉重复字符如果还要求保留第一次出现的顺序用dict.fromkeys最简洁。它按插入顺序建键重复的键自然只保留一份# 适用于 Python 3.8s abracadabraprint(.join(dict.fromkeys(s))) # abrcd推演一下dict.fromkeys(abracadabra)依次插入a、b、r、c、d后面重复的a、b、a只更新值、不改变位置所以键是a、b、r、c、d拼回字符串就是abrcd。这个写法依赖字典保持插入顺序——这一点从 Python 3.7 起是语言保证3.6 是实现细节不应依赖。只想去重不管顺序也可以用set但要清楚set不保证顺序别指望结果稳定。四、单词计数与字符分类统计单词个数split()不带参数就能处理连续空格# 适用于 Python 3.8sentence Python is fun print(sentence.split()) # [Python, is, fun]print(len(sentence.split())) # 3分类统计各类字符的个数字典加is*判断即可# 适用于 Python 3.8def classify(s: str) - dict:result {digit: 0, alpha: 0, space: 0, other: 0}for ch in s:if ch.isdigit():result[digit] 1elif ch.isalpha():result[alpha] 1elif ch.isspace():result[space] 1else:result[other] 1return resultprint(classify(abc 123!中))# {digit: 3, alpha: 4, space: 1, other: 1}abc 123!中字母是a、b、c和中isalpha()对汉字返回True共 4 个数字 3 个空格 1 个!1 个。五、排序记住 sort 与 sorted 的区别按词频排序、按字典序排序是常见收尾动作。函数是否原地返回值list.sort(...)原地排序返回Nonesorted(iterable, key..., reverse...)生成新列表返回排好序的新列表# 适用于 Python 3.8words [banana, apple, cherry]print(sorted(words)) # [apple, banana, cherry]print(sorted(words, keylen)) # [apple, banana, cherry] 按长度print(sorted(words, reverseTrue)) # [cherry, banana, apple]nums [3, 1, 2]result nums.sort() # 注意返回 Noneprint(result) # Noneprint(nums) # [1, 2, 3] 原列表被就地改了sort返回None是入门阶段最容易踩的坑之一写成nums nums.sort()会把列表直接变成None。实战词频排行榜把上面的点拼成一个完整的小程序读一段文本统计出现最多的单词按次数从高到低输出。# 适用于 Python 3.8from collections import Counterimport reTEXT Python is great. Python is simple.Python is readable, and Python is fun!def top_words(text: str, n: int 3):# 用正则取出所有字母或数字组成的词统一小写words re.findall(r[A-Za-z], text.casefold())counter Counter(words)# most_common 已按次数降序次数相同的再按字典序排保证结果稳定return sorted(counter.items(), keylambda kv: (-kv[1], kv[0]))[:n]for word, count in top_words(TEXT, 3):print(f{word}: {count})# is: 4# python: 4# and: 1re.findall把标点排除干净casefold()统一大小写Counter计数最后sorted用(-次数, 词)作为键主序按次数降序取负号实现降序次序按词升序这样即使次数相同输出也稳定不跳动。常见坑点用手写循环反转字符串❌out ; for ch in s: out ch out又慢又长✅s[::-1]一步到位sort()的返回值当结果❌nums [3, 1, 2]; nums nums.sort()nums变成None✅nums.sort()就地排序不返回值要新列表用nums sorted(nums)用set去重还指望顺序❌.join(set(abracadabra))输出顺序不保证✅ 要保序用.join(dict.fromkeys(s))依赖 3.7 起字典保序的语言保证普通字典取不存在的键❌d {}; d[x] 1→KeyError✅ 计数用collections.Counter或用d.get(x, 0) 1split()和split( )混用❌a b.split( )得到[a, , b]多出空串✅ 按空白分词用无参split()连续空白会合并忽略大小写导致词频被拆散❌Counter(The the THE.split())得到三个不同的键✅ 先casefold()或lower()再统计列表推导式里直接改原列表❌for w in words: words.remove(w)边遍历边改结果不可预期✅ 用推导式生成新列表[w for w in words if w]沿用 Python 2 的写法❌ 用print语句、dict.iteritems()、xrange、unicode✅ Python 3 里print是函数、遍历字典用.items()、range本身惰性Python 2.7 已于 2020 年 1 月 1 日 EOL总结经典题推荐工具关键点反转字符串s[::-1]负步长切片判回文s s[::-1]需要时先casefold()归一化词频统计collections.Counter缺键返回 0most_common(n)保序去重.join(dict.fromkeys(s))3.7 起字典保序是语言保证单词计数s.split()无参时连续空白算一个字符分类字典 is*方法isalpha()对汉字也为真排序sorted(...)/list.sort()sort就地且返回None入门题的价值不在于题目多难而在于它逼你熟悉切片、字典、计数器、排序这几件常用工具。大多数经典题在 Python 里都有一行或几行的标准写法先掌握这些写法再去理解背后的复杂度等到需要自己实现时你已经知道标准库是怎么做的了。真正的坑往往不在算法而在sort()返回None、set不保序、split( )留空串这些细节上。
阅读完成 · 觉得有帮助?
咨询建站