因此,我已经能够创建以下程序,该程序将两个字符串进行比较以查看它们是否是彼此的字谜。
def anagrams( string1, string2 ):
if sorted(string1.lower()) == sorted(string2.lower()):
return True
else:
return False
但是,我的问题是,如果两个输入字符串完全相同,我希望不返回True值。例如:
anagrams('silent','silent')
这将输出True,但我不希望它这样做,我应该进行哪些更改以实现此目的?
答案 0 :(得分:3)
只需检查字符串是否不同:
@VaadinServletConfiguration
输出
foreach (Task t in tasks)
{
Context context = t.ConstructContext(condition);
context.CommonProperty = "value";
context.MethodToOverride();//Do different things based on the context type
}
public asbtract class Task
{
//whatever might be in here
public abstract Context ConstructContext();
}
public class TaskA : Task
{
//NOTE: In my opinion condition should be internal to TaskA and no one else should know about and you should remove the parameter from the method
// but I don't know where you get it from so I'm leaving it here
public override Context ConstructContext(bool condition)
{
if (condition)
{
return new ContextA() { Task = this};
}
else
{
return new ContextA2() { Task = thid };
}
}
}
public class TaskB : Task
{
public override Context ConstructContext(bool condition)
{
//ignore condition which implies it shouldn't really be passed
return new ContextB() {Task = this};
}
}
//etc...
您可以使用Counter而不是进行排序:
def anagrams(string1, string2):
if sorted(string1.lower()) == sorted(string2.lower()) and string1.lower() != string2.lower():
return True
else:
return False
result = anagrams('silent', 'silent')
print(result)
输出
False
更新
按照@RoadRunner的建议,您可以这样做:
from collections import Counter
def anagrams(string1, string2):
if string1.lower() != string2.lower() and Counter(string1.lower()) == Counter(string2.lower()):
return True
else:
return False
print(anagrams('silent', 'silent'))
print(anagrams('silent', 'sitlen'))
答案 1 :(得分:0)
def anagrams( string1, string2 ):
if sorted(string1.lower()) == sorted(string2.lower()) and string1.lower() != string2.lower():
return True
else:
return False
print(anagrams('silent','silent'))