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

我有一个任务,我需要读取输入并检查输入是否发生在某些单词中.例如:

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.

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

最佳答案

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]顺序.

有任何疑问,请随时提出.

点赞