单词加字符的字谜

问题描述 投票:0回答:1

我正在 Python 环境中工作。 我有一个宏观任务要解决,但现在我有一个巨大的问题要解决微观任务:在text中找到word的“B-anagram”,但是“B-anagram”MUST包括一个角色。

一个例子是文本“the-astronautis-t&kingpict/res.”和单词“artos”。 我想从函数中收到的“B 字谜”是:

  • “astro”包含“astro”+“n” -> “astro”是“artos”的字谜词,“n”是加号。
  • “strona”包含“stroa”+“n” -> “stroa”是“artos”的字谜,“n”是加号。

加号字符可以是文本中单词字符之间的任何字符,因此在此示例中,对于单词“sitt”,“B 字谜”是“tis-t”,其中“-”是加号字符。

有人可以澄清我的想法吗,我已经挣扎了好几天了:-(.

我尝试过使用单词长度,从文本中单词第一个字母的第一个索引开始搜索,并向左和向右搜索 len(word)+1,但我一直得到错误的结果。 我也尝试使用 set(text)-set(word) 但这样当我有类似的东西时: 文本“pythonyinncc”和单词“yinc”由于设置,“B-anagram”“yinnc”不会返回。 我无法导入外部库。

python anagram
1个回答
0
投票

我问了chatgpt并给了我这个:

def is_b_anagram(word1, word2):
    # Check if the second word has one more character than the first word
    if len(word2) != len(word1) + 1:
        return False

    # Sort both words alphabetically
    sorted_word1 = ''.join(sorted(word1))
    sorted_word2 = ''.join(sorted(word2))


    # Check if the sorted second word is an anagram of the sorted first word
    for i in range(len(sorted_word2)):
        if sorted_word2[:i] + sorted_word2[i+1:] == sorted_word1:
            return True

    return False
© www.soinside.com 2019 - 2024. All rights reserved.