我有一个任务,我需要阅读输入并检查输入是否出现在某些单词中。例如:
Who are your friends? Fred Bill Sue Simone
What is the message? Should you make tea?
Sue could have written this.
它会打印“S U E可能写这个,因为字母“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.
我知道代码不会检查名称中的字母是否连续出现,而是检查名称是否在任何单词中。我该怎么解决?
最佳答案
def find_char(string, char):
start_index = 0
while True:
yield string.lower().find(char, start_index) # checks for the char in the string
start_index += 1 # increments the index to find further in the word,
# eg:
# Bob constructed[index 0]
# ob constructed[index 1]
# b constructed[index 2]
def find_it(friends, message):
friends = friends.split()
for friend in friends:
sequence_check = []
for char in friend.lower():
gen = find_char(message, char) # creates the find_char generator
for _ in message: # limits the search to the length of the word
char_index = next(gen) # try to find the index
if char_index not in sequence_check: # if not in the sequence
sequence_check.append(char_index) # add it to it
break
if -1 in sequence_check: # this check if every character of the name is in the word
continue
if sorted(sequence_check) == sequence_check: # this part check if it's in a sequence.
print (friend + ' could have written ' + message)
find_it('James Nicky Jake', "join and make enough cash today!")
find_it('Fred Bill Sue Simone', "Should you make tea?")
find_it("Bob", "Bob constructed Balloon Town")
输出:
James could have written join and make enough cash today!
Jake could have written join and make enough cash today!
Sue could have written Should you make tea?
Bob could have written Bob constructed Balloon Town
重做一遍,现在干净多了。
大部分工作都是在find_char函数中完成的,该函数是一个生成器,它在每次迭代中减少了搜索空间,因此它不会在序列中找到位置Bob作为[0,1,0],而是[0,1,2]。
任何问题,请随便问。