为什么这个代码不适用于所有输入

2024-10-01 09:20:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写python代码,将两个字符串作为输入,并检查第二个字符串的所有字符是否都存在于第一个字符串中。如果是,那么输出是第二个字符串。如果不是,则输出字符串“This not work”。我已经针对各种输入测试了这个过程,它通常是有效的,但并不总是有效的。例如,如果我的两个输入分别是“helo”和“olhe”,那么输出是“This not work”,而应该是“olhe”,因为“olhe”中的所有字符都出现在“helo”中

这是我的密码

def fix_machine(debris,product):
    n = 1
    while True:
          first_element = product[0:n]
          find_first_element = debris.find(first_element)
          if first_element == product:
               return product
               break
          n = n + 1
          if find_first_element == -1:
               return "This does not work"
               break

为什么这不起作用呢?你知道吗


Tags: 字符串returnifnotelementfindproductthis
3条回答

据我所知,你只想比较两个包含不同字符的字符串。你知道吗

为此,我建议将这两个字符串转换为set,然后提供(与list)元素的无顺序比较。你知道吗

def check_string(first_str, second_str):
    # convert strings to sets in order to compare characters
    if set(first_string) == set(second_string):
        return second_str
    else:
        return 'This does not work.'


first_string = 'helo'
second_string = 'olhe'    
print(check_string(first_string, second_string))
# prints True

first_string = 'helo'
second_string = 'hello'    
print(check_string(first_string, second_string))
# prints True

first_string = 'helo'
second_string = 'helofoo'    
print(check_string(first_string, second_string))
# prints 'This does not work.'

您可以将此作为一个更优雅的解决方案,假设您严格地希望所有第二个字符串都出现在第一个字符串中。你知道吗

def fix_machine(first, second):
    for character in second:
        if character not in first:
            return False
    return second

这将为您的代码返回正确的输入。我不完全确定你的代码有什么问题,因为我还没有通过。你知道吗

编辑:阿尔伯特有一个更优雅的解决方案,他的参考

我同意您应该使用一个调试器(如果您还没有设置IDE,可以尝试PyCharm)来逐步检查代码,看看哪里出错了。很难解释出哪里出了问题,但我认为这与first_element = product[0:n]有关。这将返回越来越大的字符串段。i、 在第二次穿越的时候。你知道吗

这里有另一种写作方式

def fix_machine(debris, product):
    all_present = all(letter in debris for letter in product)
    return product if all_present else 'This does not work'

相关问题 更多 >