Python 用于通知的字符串匹配算法代码

Python 用于通知的字符串匹配算法代码,python,algorithm,Python,Algorithm,调试我正在调试的以下问题、post问题和代码参考。我的问题是,我认为这如果条件检查,如果没有必要,可以安全地删除?如果我错了,请随时纠正我。谢谢 if len(first) > 1 and first[0] == '*' and len(second) == 0: return False 给定两个字符串,其中第一个字符串可能包含通配符,第二个字符串是普通字符串。编写一个函数,如果两个字符串匹配,则返回true。第一个字符串中允许使用以下通配符 * --> Matches

调试我正在调试的以下问题、post问题和代码参考。我的问题是,我认为这如果条件检查,如果没有必要,可以安全地删除?如果我错了,请随时纠正我。谢谢

if len(first) > 1 and first[0] == '*' and  len(second) == 0:
    return False
给定两个字符串,其中第一个字符串可能包含通配符,第二个字符串是普通字符串。编写一个函数,如果两个字符串匹配,则返回true。第一个字符串中允许使用以下通配符

* --> Matches with 0 or more instances of any character or set of characters.
? --> Matches with any one character.
例如,
g*ks
geek
匹配。字符串
ge?ks*
geeksforgeks
匹配(注意第一个字符串末尾的
*
)。但是
g*k
gee
不匹配,因为第二个字符串中不存在字符
k

# Python program to match wild card characters

# The main function that checks if two given strings match.
# The first string may contain wildcard characters
def match(first, second):

    # If we reach at the end of both strings, we are done
    if len(first) == 0 and len(second) == 0:
        return True

    # Make sure that the characters after '*' are present
    # in second string. This function assumes that the first
    # string will not contain two consecutive '*'
    if len(first) > 1 and first[0] == '*' and  len(second) == 0:
        return False

    # If the first string contains '?', or current characters
    # of both strings match
    if (len(first) > 1 and first[0] == '?') or (len(first) != 0
        and len(second) !=0 and first[0] == second[0]):
        return match(first[1:],second[1:]);

    # If there is *, then there are two possibilities
    # a) We consider current character of second string
    # b) We ignore current character of second string.
    if len(first) !=0 and first[0] == '*':
        return match(first[1:],second) or match(first,second[1:])

    return False
提前感谢,,
Lin

表示
if
语句对函数的正确运行至关重要。移除它将产生灾难性的后果

例如,假设
first=“*a”
second=“
。换句话说,该函数被称为
match(“*a”,”)
。然后,
if
语句将导致函数返回
False
(这是正确的,因为
秒中没有
a
)。如果不使用
if
语句,代码将转到第行

return match(first[1:],second) or match(first,second[1:])

调用
match(第一个[1:],第二个)
将求值为
match(“a”),然后返回
False
。但是当代码调用
match(first,second[1:])
时,调用相当于
match(“*a”,”)
,结果是无限递归。

顺便说一句,我不知道我的格式有什么问题,我用括号将代码标记为源代码,但看起来是3行Python程序匹配通配符的主要功能是检查两个给定字符串是否匹配。第一个字符串可能包含通配符“未以正确的格式正确显示。如果有人能帮忙看一看,那就太好了。谢谢。仅供参考,这看起来像是你在尝试手动实施全球化。也许我们可以看看,哪些已经做到了这一点?或者,如果您实际上正在扫描文件系统,也可以使用?进行后续操作,这样,如果您只需要处理
*
,而不需要处理字符类通配符,您就可以复制和修改它。@ShadowRanger,谢谢您的建议,非常有知识。:)但这样一个无限循环会不会导致我的房子爆炸或者我的街道被洪水淹没@N.Wouda好吧,如果无限递归让你的计算机消耗更多的电能,而这会使当地的电力变压器过载,导致火灾,消防车意外撞上消防栓,那么是的,你的房子可能同时着火和洪水。感谢用户3386109的建议,请将你的回答标记为回答。:)