我试图编写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
为什么这不起作用呢?你知道吗
据我所知,你只想比较两个包含不同字符的字符串。你知道吗
为此,我建议将这两个字符串转换为
set
,然后提供(与list
)元素的无顺序比较。你知道吗您可以将此作为一个更优雅的解决方案,假设您严格地希望所有第二个字符串都出现在第一个字符串中。你知道吗
这将为您的代码返回正确的输入。我不完全确定你的代码有什么问题,因为我还没有通过。你知道吗
编辑:阿尔伯特有一个更优雅的解决方案,他的参考
我同意您应该使用一个调试器(如果您还没有设置IDE,可以尝试PyCharm)来逐步检查代码,看看哪里出错了。很难解释出哪里出了问题,但我认为这与
first_element = product[0:n]
有关。这将返回越来越大的字符串段。i、 在第二次穿越的时候。你知道吗这里有另一种写作方式
相关问题 更多 >
编程相关推荐