Jes*_*ero 4 python algorithm python-3.x
好吧,基本上我必须检查一个字符串是否与另一个字符串具有相同的字母。这两个字符串都是通过input()获得的。
我不想再次检查某个字母是否在另一个字符串中,因此如果我已经检查了该字母,我想跳到下一个字母。
我现在的代码是这样的:
str1, str2 = list(input()), list(input())
if len(str1) > len(str2):
str = str1
else:
str = str2
for x in str:
c = 0
if x in str2:
c += 1
if c != 0:
print("Both have the same letters!")
else:
print("Nope there are some letters missing..")
Run Code Online (Sandbox Code Playgroud)
我不知道我是否应该使用列表而不是使用计数器..请详细解释解决方案或一些高质量的指导将非常感激!<3
将字符串转换为单个符号集会删除重复的符号,因此我们可以简单地比较它们:
if set(str1) == set(str2):
print("Both have the same letters!")
else:
print("Nope there are some letters missing..")
Run Code Online (Sandbox Code Playgroud)
笔记:
由于集合中元素的顺序并不重要,我们甚至可以比较它们,例如
if set(str1) <= set(str2): # <= means "is subset" in this context
print("All symbols in str1 are in str2, too.")
Run Code Online (Sandbox Code Playgroud)
或者
if set(str1) < set(str2): # < means "is a proper subset" in this context
print("All symbols in str1 are in str2, too, "
"but str2 has at least 1 symbol not contained in str1.")
Run Code Online (Sandbox Code Playgroud)