哈利波特碰巧收集到了一些零碎的,写着单词的小纸条,但是令人费解的是很多单词都是重复的。让我们编写一个python函数,帮助他厘清线索吧。记得需要保持原单词的先后顺序不变哦。
示例:
输入:"Wingardium Leviosa Wingardium Wingardium Leviosa Expelliarmus Wingardium Leviosa Expelliarmus"
输出:"Wingardium Leviosa Expelliarmus"
输入:"Hogwarts is the best Hogwarts is the best Hogwarts is the best"
输出:"Hogwarts is the best"
题目难度:简单
题目来源:codewars
def remove_duplicate_words(s:str) -> str:
pass
assert remove_duplicate_words("Wingardium Leviosa Wingardium Wingardium Leviosa Expelliarmus Wingardium Leviosa Expelliarmus") == "Wingardium Leviosa Expelliarmus"
assert remove_duplicate_words("Hogwarts is the best Hogwarts is the best Hogwarts is the best") == "Hogwarts is the best"
def remove_duplicate_words(s: str) -> str:
result = []
[result.append(i) for i in s.split(" ") if i not in result]
return " ".join(result)
assert remove_duplicate_words(
"Wingardium Leviosa Wingardium Wingardium Leviosa Expelliarmus Wingardium Leviosa Expelliarmus") == "Wingardium Leviosa Expelliarmus"
assert remove_duplicate_words(
"Hogwarts is the best Hogwarts is the best Hogwarts is the best") == "Hogwarts is the best"
参考题解
def remove_duplicate_words(s):
return ' '.join(dict.fromkeys(s.split()))
思路:巧用dict字典的内置方法来实现去重。
def remove_duplicate_words(s):
existed = []
for word in s.split():
if word not in existed:
existed.append(word)
return ' '.join(existed)
assert remove_duplicate_words("Wingardium Leviosa Wingardium Wingardium Leviosa Expelliarmus Wingardium Leviosa Expelliarmus") == "Wingardium Leviosa Expelliarmus"
assert remove_duplicate_words("Hogwarts is the best Hogwarts is the best Hogwarts is the best") == "Hogwarts is the best"