string - Apply edit to strings
问题描述
I have an practice that gives input and wants to get the 'hello'
by deleting letters and if it get print 'YES'
and if not print 'NO'
.python 3
i write this but i do not know why it is not work sometime
def edit(x):
for h in x:
if h in ('a','q','z','w','s','x','d','c','r','f','v','t','g','b','y','n','u','j','m','i','k','p'):
y = x.replace(h,'')
return y
x =input()
x1='a'.join(x)
y = edit(x1)
if y==('hello'):
print('YES')
elif y.count('l')>=2 and y.count('h')>=1 and y.count('e')>=1 and y.count('o')>=1:
if y.startswith('h') and y.endswith('o'):
y1=y.replace('h','')
if y1.startswith('e'):
y2=y1.replace('e','')
if y2.startswith('l') and y2.endswith('o'):
print('YES')
else:
print('NO')
for example
aahhelllo
YES
asdxhhhellooooo
Process finished with exit code 0
解决方案
错误在您的edit(x)
函数中。它遍历x
变量中字符串的字符,并检查该字符是否在 22 的列表中;如果是这样,它将从字符串中删除所选字符的所有实例并将结果存储在y
变量中。
注意:在每次迭代中,它都会使用x
变量;它不接受y
,这是之前修改的结果,但它一次又一次地接受原始输入参数。最后,您y
从执行的最后一次修改中获得。
其中"aahhelllo"
只有一个字符要删除:'a'
,因此只进行了一次替换,其结果是"hhello"
,正如预期的那样。
OTOH,"aasdxhhhellooooo"
有四个字符要删除,所以:
- 在第一次迭代
y
中被赋值"aasdxhhhellooooo".replace('a','')
为"sdxhhhellooooo"
; - 在第二次迭代中,您
'a'
再次删除(因为它没有从 中删除x
); - 在您分配的第三个
y="aasdxhhhellooooo".replace('s','')
中是"aadxhhhellooooo"
; - 依此类推,直到对 进行最后一次修改
h=='x'
,这使得y="aasdxhhhellooooo".replace('x','')
,也就是"aasdhhhellooooo"
。
这就是edit(x)
第二种情况下返回的结果。
推荐阅读
- swift - 快速获取表格视图单元格值为零
- c - free() 在这种情况下如何工作?
- excel - 需要密码才能在 excel 365 中共享/发送电子邮件
- laravel - Laravel 7 Spatie 返回相同的角色
- azure-active-directory - 在 CloudShell 中使用 MSAL
- apache-kafka - @KafkaListener : 事件的行为和跟踪处理
- python - pythonanywhere:错误代码:未处理的异常
- knn - 如何通过绘制 KNN 弯头来确定 DBSCAN 的最佳 epsilon 值(以米为单位)
- android - 材质日期选择器自定义样式白色样式
- reactjs - 物料表选择行导出