社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  MattDMo  »  全部回复
回复总数  2

以下是你的问题集的第三个标准的解决方案。

import string
from more_itertools import windowed

alphabet = string.ascii_lowercase
numbers = string.digits

passwords = ["Mz2a%yc98B", "a1b2g3D!", "Tr0ub4dor?"]

def find_triplets(charset: set, target: str) -> bool:
    if len(charset) < 3:
        return False
    else:
        chars = "".join(sorted(charset))
        triplets = ["".join(tpl) for tpl in windowed(chars, 3)]
        return any(triplet in target for triplet in triplets)

for pwd in passwords:
    # we use sets to get rid of duplicatess
    alpha = set()
    nums = set()
    for char in pwd:
        if char.isalpha():
            alpha.add(char.lower())
        elif char.isdigit():
            nums.add(char)
        else:
            pass # we don't care about symbols here
    if find_triplets(alpha, alphabet) or find_triplets(nums, numbers):
        print(f"Your password {pwd} contains 3 consecutive letters or numbers")
    else:
        print(f"Your password {pwd} is good enough, I guess")

在设置代码之后,我们首先定义一个函数来生成3个字符的字符串( triplets )从输入 charset ,然后将其排序并转换为字符串本身。这使用了 windowed() 来自非常有用的第三方的功能 more_itertools 单元函数返回 True 如果它在序列中找到任何匹配连续序列的三胞胎 target 绳子,还有 False 如果没有,那就简单了。

接下来,我们重复我们的密码列表(您使用的 input() 在代码中,这很好)。首先,我们逐个字符迭代密码字符串,并将它们添加到适当的集合中(字母字符的情况下使用小写)。然后我们打电话给 find_triplets() 函数测试字母或数字的连续运行,并相应地打印消息。

很明显,你会想改变一些,以适应你的任务,但我会让你自己决定。

还有一种方法是使用 re.search() 但是我认为 any(triplet in target for triplet in triplets) 更像是蟒蛇。

4 年前
回复了 MattDMo 创建的主题 » python中的循环有问题

你的问题从这句话开始:

f = file.write(input("Probes:"))

首先, input() 总是返回一个字符串,所以如果以后想将其与整数进行比较,需要使用 int() .

然而,更大的问题是,您没有指定 输入() 对…的声明 f ,您正在为 file.write() .这样的服务会更好:

f = int(input("Probes:"))
file.write(f)
...

此外,正如上面的评论所解释的,您不需要 x a .但是请记住 range() 除非另有说明,否则从0开始生成值。