给定一个字符串。我们的任务是在给定的字符串中找到第一个重复的单词。为了实现这个问题,我们使用 Python 集合。从集合中,我们可以得到 Counter() 方法。

算法

Repeatedword(n)
/* n 是字符串 */
步骤 1:首先将给定的字符串用空格分隔成单词。
步骤 2:现在将单词列表转换为字典。
步骤 3:遍历单词列表并检查哪个第一个单词的频率 >1

示例代码

# 从集合中查找字符串中第一个重复的单词
import Counter
def duplicateword(n):
   # 首先将给定的字符串用空格分隔成单词
   w = n.split(' ')
   con = Counter(w)
   for key in w:
      if con[key]>1:
         print ("REPEATED WORD IS ::>",key)
         return
# 驱动程序
if __name__ == "__main__":
   n=input("Enter the String ::")
   repeatedword(n)

输出

Enter the String ::We are all peaceful soul and blissful soul and loveful soul happy soul
REPEATED WORD IS ::> soul

相关文章

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐