2017-03-08 34 views
0

我想查找長度在1-4個字符之間的字母字符串。按順序遍歷多個字符列表

我開始通過52個字母列表迭代:

letters = string.ascii_letters 

我則需要通過同一個目錄遍歷該字符串的接下來的三個字符,直到我發現我要找的字符串。

如果每個_代表的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 
+0

歡迎SO Kyap!儘管我們非常樂意提供幫助,但您必須先向我們展示您首先完成的工作。 SO通常不是代碼寫入服務。 – AlG

+0

您能否包含一些示例數據或僞代碼?我在閱讀您的問題時遇到問題 –

+0

請參閱http://stackoverflow.com/questions/7074051/what-is-the-best-way-to-generate-all-possible-three-letter-strings。 – kennytm

回答

0

這樣的事情也許是:

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") 
+0

完美!也很簡單。我希望我能夠爲此提出邏輯。 – Kyap

2

你可以做這樣的事情:

 

    import string 
    import itertools 

    data = string.ascii_lowecase 

    for i in itertools.permutations(data, 4): 

     if i == 'your_string': 
      #do something 
     else: 
      pass 

+0

使用itertools.permutation不能很好地工作,因爲我必須考慮1,2和3個字母字符,而不僅僅是4個字母的排列。 – Kyap

+0

您可以使用outerloop來維持字符串長度,然後使用itertools.permutation。 –