【问题标题】:Iterate through multiple lists of characters in order按顺序遍历多个字符列表
【发布时间】:2017-07-29 03:39:29
【问题描述】:

我想找到一个长度在 1-4 个字符之间的字母字符串。

我首先遍历 52 个字母的列表:

letters = string.ascii_letters

然后,我需要在同一个列表中迭代字符串的下 3 个字符,直到找到我要查找的字符串。

如果每个 _ 代表 52 个字母的列表,我基本上需要这样做,同时在每次迭代时检查匹配:

_
_ _
_ _ _
_ _ _ _

我将如何最好地构建一系列循环来做到这一点?


如果问题的前提看起来令人困惑,那么这是针对暴力破解的问题。我只是简单地提取了我正在努力解决的问题的一部分。


编辑:这是我到目前为止所要做的。

#we know the salt is the 2-digit '50'
#we know the key is limited to 4 alphabetical letters
#cycle through all possibilities of the key till we match the hash

letters = string.ascii_letters
lcounter = 0
i = 0
j = 0
k = 0
l = 0
tryhash = "a"
word = [letters[i]]

while(tryhash != hash):
    for c in letters:
        word = [letters[i]]  #this does not work as the additional letters need to be appended to word after the first lcounter loop
        tryword = ''.join(word)
        tryhash = crypt.crypt(tryword, "50")

        if (tryhash == hash):
            print(word)
            break

        i += 1

        if (lcounter > 0) and (i == 52):
            i = 0
            if (lcounter == 1) and (j == 0):
                word.insert(lcounter, letters[j])
            j += 1

            if (lcounter > 1) and (k == 52):
                j = 0
                if (lcounter == 2) and (k == 0):
                    word.insert(lcounter, letters[k])
                k += 1

                if (lcounter > 2) and (k == 52):
                    k = 0
                    if (lcounter == 3) and (l == 0):
                        word.insert(lcounter, letters[l])
                    l += 1

    lcounter += 1

【问题讨论】:

  • 欢迎来到 SO Kyap!虽然我们非常乐意提供帮助,但您必须先向我们展示您所做的事情。 SO 不是(通常)代码编写服务。
  • 您能提供一些示例数据或伪代码吗?我无法阅读您的问题
  • 感谢您的欢迎。我已经添加了我的代码。至于可能的重复,它非常相似,但是该问题的答案(使用 itertools.permutation)效果不佳,因为它必须考虑 1,2 和 3 个字母字符,而不仅仅是 4 个字母的排列。跨度>

标签: python


【解决方案1】:

可能是这样的:

my_string = "some"
for letter1 in string.ascii_letters:
    if letter1 == my_string:
        print("success")
    for letter2 in string.ascii_letters:
        if letter1 + letter2 == my_string:
            print("success")
        for letter3 in string.ascii_letters:
            if letter1 + letter2 + letter3 == my_string:
                print("success")
            for letter4 in string.ascii_letters:
                if letter1 + letter2 + letter3 + letter4 == my_string
                    print("success")

【讨论】:

  • 完美!也很简单。我希望我能够想出这个逻辑。
【解决方案2】:

你可以这样做:

导入字符串 导入迭代工具 数据 = string.ascii_lowecase 对于 i 在 itertools.permutations(data, 4) 中: 如果我 == 'your_string': #做一点事 别的: 经过

【讨论】:

  • 使用 itertools.permutation 效果不佳,因为我必须考虑 1,2 和 3 个字母字符,而不仅仅是 4 个字母的排列。
  • 你可以使用外循环来保持字符串长度,然后使用 itertools.permutation。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-01
  • 2013-07-13
  • 2013-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多