【发布时间】:2015-02-04 09:37:09
【问题描述】:
我有一个任务,我需要读取输入并检查该输入是否出现在某些单词中。例如:
Who are your friends? Fred Bill Sue Simone
What is the message? Should you make tea?
Sue could have written this.
它打印“Sue could have write this 因为字母“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.
我了解到代码不会检查名称中的字母是否连续出现,而是检查名称是否包含在任何单词中。我该如何解决这个问题?
【问题讨论】:
-
如果
join之前还有一个单词,第二个例子的输出是什么,比如:'zzz'?