Python实现Mexican Wave功能异常:无法生成正确的大写交替数组
Mexican Wave函数问题排查
我正在尝试编写代码完成Kata任务:创建一个将字符串转换为Mexican Wave的函数,传入字符串后返回一个数组,其中大写字母代表站立的人。
我的尝试代码:
def wave(people): newstring = [*people] final=[] for i in range(len(newstring)): newstring[i].title() final.append("" .join(newstring)) return final
预期返回:
wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
实际返回:
['hello', 'hello', 'hello', 'hello', 'hello']
问题原因
你代码里的newstring[i].title()没有起作用,因为Python的字符串是不可变类型——调用title()或upper()这类方法时,不会修改原字符串/字符,而是返回一个新的、处理后的字符串。你只调用了方法,但没把返回值赋值回newstring[i],所以原列表里的字符始终是原始的小写状态,每次拼接出来的都是原字符串。
另外还有一个隐藏问题:就算你完成了赋值,下一次循环时前一个大写的字符会保持大写,最终生成Hello→HEllo→HELlo这类错误结果,因为你没有把修改后的字符还原。
修正方案
基础修正(解决当前问题)
给newstring[i]赋值处理后的字符,循环后再还原原状态:
def wave(people): newstring = [*people] final=[] for i in range(len(newstring)): # 将处理后的字符赋值回列表 newstring[i] = newstring[i].title() final.append("".join(newstring)) # 还原字符为原始状态,避免下一次循环叠加大写 newstring[i] = newstring[i].lower() return final
更简洁的写法(推荐)
不需要转列表,直接用字符串切片拼接,跳过空格(符合Kata任务隐含要求:空格位置不生成wave项):
def wave(people): final = [] for i in range(len(people)): if people[i].isspace(): continue # 切片拼接:取i之前的部分 + 大写的i位字符 + i之后的部分 wave_str = people[:i] + people[i].upper() + people[i+1:] final.append(wave_str) return final
内容的提问来源于stack exchange,提问作者radriaansNES
相关产品推荐
相关产品推荐

