gpt4 book ai didi

Python - 检查字母是否出现在连续的单词中

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:49 24 4
gpt4 key购买 nike

我有一项任务需要读取输入并检查该输入是否出现在某些单词中。例如:

Who are your friends? Fred Bill Sue Simone
What is the message? Should you make tea?
Sue could have written this.

它打印“Sue 可能已经写了这个,因为字母“S”、“U”和“E”出现在每个连续的单词中。另一个例子是:

Who are your friends? James Nicky Jake
What is the message? join and make enough cash today!
James could have written this.
Jake could have written this.

两个名字都被打印出来,因为他们的两个字母在每个单词中都是连续出现的。我有以下代码:

friends = input("Who are your friends? ").split()
message = input("What is the message? ").split()

name = []
other = []

for friend in friends:
for f in friend.lower():
for word in message:
print("checking if", f, "is in", word.lower())
if f in word.lower():
print("Adding", f, " to name list")
name.append(f)
break
else:
other.append(f)
continue

joinedResult = ''.join(name)

for person in friends:
if person.lower() in joinedResult:
print(person, "could have written this.")

它对第一个例子很完美,但对于第二个例子,它打印了所有三个名字:

James could have written this.
Nicky could have written this.
Jake could have written this.

我了解到代码不会检查名称中的字母是否连续出现,而是检查名称是否在任何单词中。我该如何解决这个问题?

最佳答案

您可以使用 zip 执行此操作和 all() :

friends = input("Who are your friends? ").split()
message = input("What is the message? ").lower().split()

for friend in friends:
if len(friend) <= len(message):
if all(x in y for x, y in zip(friend.lower(), message)):
print(friend, "could have written this.")

演示:

>>> 
Who are your friends? Fred Bill Sue Simone
What is the message? Should you make tea?
Sue could have written this.
>>>
Who are your friends? James Nicky Jake
What is the message? join and make enough cash today!
James could have written this.
Jake could have written this.

关于Python - 检查字母是否出现在连续的单词中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27329063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com