首页 > 解决方案 > 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

标签: string

解决方案


错误在您的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)第二种情况下返回的结果。


推荐阅读