使用python创建自己的数字系统

2024-09-29 22:21:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个猜测密码的小程序

我制作这个程序只是为了学习,我想通过制作一个真正有意义的程序来提高我的python技能

例如:

using_characts = "abcdefghijklmnopqrstuvwxyz" # I have other characters in my alphabetic system

我想做的是这样的:

for char in myCharacters:
    print(char)
    for char_1 in myCharacters:
        print(char + char_1)
        for char_2 in myCharacters:
            print(char + char_1 + char_2)
            ...etc

这使得该方法非动态,同时也很难实现。 输出应如下所示:

a

b

c

d

e

f

..etc

aa

ab

ac

..etc

ba

bb

bc

..etc

Tags: in程序密码forhave技能etc意义
3条回答

所以,其他答案给了你可能会工作的代码,但我想解释一个通用的方法。此算法使用堆栈跟踪下一个需要生成的内容,并继续生成,直到达到指定的最大长度

from collections import deque
from typing import Deque, Iterator, Optional


def generate_next_strings(chars: str, base: str = "") -> Iterator[str]:
    # This function appends each letter of a given alphabet to the given base.
    # At its first run, it will generate all the single-length letters of the
    # alphabet, since the default base is the empty string.
    for c in chars:
        yield f"{base}{c}"


def generate_all_strings(chars: str, maxlen: Optional[int] = None) -> Iterator[str]:
    # We "seed" the stack with a generator. This generator will produce all the
    # single-length letters of the alphabet, as noted above.
    stack: Deque[Iterator[str]] = deque([generate_next_strings(chars)])

    # While there are still items (generators) in the stack...
    while stack:
        # ...pop the next one off for processing.
        next_strings: Iterator[str] = stack.popleft()

        # Take each item from the generator that we popped off,
        for string in next_strings:
            # and send it back to the caller. This is a single "result."
            yield string

            # If we're still generating strings -- that is, we haven't reached
            # our maximum length -- we add more generators to the stack for the
            # next length of strings.
            if maxlen is None or len(string) < maxlen:
                stack.append(generate_next_strings(chars, string))

你可以用print("\n".join(generate_all_strings("abc", maxlen=5)))试试

您可以使用^{},但您确实应该用一个小数字来限制自己。为更高的数字生成笛卡尔乘积可能需要很长时间:

from itertools import chain, product
chars = "abcdefghijklmnopqrstuvwxyz"
limit = 2
for perm in chain.from_iterable(product(chars, repeat=i) for i in range(1, limit+1)):
    print("".join(perm))
a
b
c
.
.
.
aa
ab
ac
.
.
.
zy
zz

给你,这会有用的。如果你想让我解释任何部分,请告诉我

import itertools

using_characts = "abc"

for str_length in range(1,len(using_characts)+1):
    for q in itertools.product(using_characts,repeat=str_length):
        print("".join(q))

相关问题 更多 >

    热门问题