python - 如何解决以下 Python 代码冻结问题?
问题描述
我有一个 Python 问题,我需要将输入作为函数中的字符串,并需要返回一个字符串,其中每个备用字母都是小写字母和大写字母的序列。例如:传递给函数的字符串:AmsTerdam
那么返回的字符串应该是AmStErDaM
. 它可以从任何情况开始,即小写或大写。
我仍处于 Python 的学习阶段,并提出了以下建议,但不知何故,当我尝试执行时,代码挂起。谁能帮我解决这个问题?
def myfunc(NAME='AmsTerdam'):
leng=len(NAME)
ind=1
newlist=[]
while ind <= leng:
if ind%2==0:
newlist.append(NAME[ind-1].upper())
else:
newlist.append(NAME[ind-1].lower())
str(mylist) # Can we typecast a list to a string?
return newlist
OUT=myfunc('Ankitkumarsharma')
print('Output: {}'.format(OUT))
如果无法进行类型转换,以下是否正确?
def myfunc(NAME='AmsTerdam'):
leng=len(NAME)
ind=1
newstr=''
while ind <= leng:
if ind%2==0:
newstr=newstr+NAME[ind-1].upper()
else:
newstr=newstr+NAME[ind-1].lower()
return newstr
OUT=myfunc('AmsTerdam')
print('Output: {}'.format(OUT))
解决方案
本质上,您编写了一个 while true 循环,没有中断条件。
按照您之前的逻辑,我们可以重写您的循环并假设ind=1
总是如此,我们得到:
def myfunc(NAME='AmsTerdam'):
leng=len(NAME)
newstr=''
while 1 <= leng:
if ind%2==0:
newstr=newstr+NAME[ind-1].upper()
else:
newstr=newstr+NAME[ind-1].lower()
return newstr
这意味着如果len(name) > 1
,循环将永远运行。解决这个问题,我们得到以下函数,它将终止。
def myfunc(NAME='AmsTerdam'):
leng=len(NAME)
newstr=''
ind=1
while ind <= leng:
if ind%2==0:
newstr=newstr+NAME[ind-1].upper()
else:
newstr=newstr+NAME[ind-1].lower()
ind+=1
return newstr
推荐阅读
- android - 我可以用什么来制作像笔记应用程序这样的应用程序,其中有意外数量的笔记
- flutter - Flutter:如何更改另一个 dart 文件中变量的状态?
- flutter - 如何在 Flutter 中为 DropdownButton 的每个项目显示一个图标和文本?
- wordpress - 从 LearnPress 插件 (wordpress) 中删除“课程”选项卡
- python - 如何通过在字典中成对通过两个列表在 Python 中创建文本文档
- discord.py - 你如何创建一个不和谐的机器人来创建包含视频预览的嵌入
- java - 找不到我的主要错误,在 java 中调试
- python - 有没有更好的算法来比较每个图像与文件夹中的其他图像?
- r - 如何在R中的计数ggplot条形图中添加一个变量的百分比
- google-cloud-platform - GPU配额更新需要多少时间?