gpt4 book ai didi

python - Is_prime 函数通过 python 中的正则表达式(来自 perl)

转载 作者:太空狗 更新时间:2023-10-29 20:26:49 25 4
gpt4 key购买 nike

我读过 this article其中 /^1?$|^(11+?)\1+$/ Perl 正则表达式用于测试数字是否为质数。

过程:

s = '1' * your_number

如果 s 与正则表达式匹配,则它不是质数。如果不是,则为素数。

您如何将该正则表达式转换为 Python 的 re 模块?

最佳答案

它按原样工作(除了边缘没有斜线,Python 不需要斜线):

pattern = r'^1?$|^(11+?)\1+$'
re.match(pattern, '1'*10) #matches
re.match(pattern, '1'*11) #doesn't match

此处唯一需要的非标准正则表达式功能是反向引用 (\1),Perl 和 Python 均支持这些功能。

关于python - Is_prime 函数通过 python 中的正则表达式(来自 perl),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2225027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com