2012-11-13 1 views
1

가능한 중복을 가능한 문자열 목록을 작성 계속 :
Using itertools.product and want to seed a value파이썬에서

내가 문자열의 일관된 목록을 생성이 코드를 가지고있다.

import itertools 
choices = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789" 
for length in range(0,20): 
    for entry in itertools.product(choices, repeat = length): 
     string = ''.join(entry) 
     print string 

마지막으로 알려진 문자열에서이 스크립트를 계속 실행하고 싶습니다. 어떻게 이것이 가능합니까?

+1

"마지막으로 알려진"을 정의 하시겠습니까? – StoryTeller

+2

관련성이 있습니다. http://stackoverflow.com/questions/9864809/using-itertools-product-and-want-to-seed-a-value – abought

답변

2

당신이 마지막으로 알려진 문자열로 변수 string 세트가 가정 (또는 ''은 처음부터 시작하기) :이 인쇄 할 첫 번째 요소가 마지막으로 알려진 문자열입니다

import itertools 
choices = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789" 
for length in range(len(string), 20): 
    itr = itertools.product(choices, repeat = length) 
    if string != '' and length == len(string): 
     itr = itertools.dropwhile(tuple(string).__ne__, itr) 
    for entry in itr: 
     string = ''.join(entry) 
     print string 

참고. 마지막 문자열을 건너 뛰고 다음 문자열을 인쇄하여 시작하려면 if 문 안에 next(itr)을 입력하면됩니다.

이것은 스크립트의 여러 번 실행을 중단 한 곳이나 생성기 솔루션이 적용되지 않는 다른 시나리오에서 다시 시작하려고한다고 가정합니다. 발전기를 사용할 수 있으면해야합니다.

4
import itertools 
def choices(): 
    choices = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789" 
    for length in range(0,20): 
     for entry in itertools.product(choices, repeat = length): 
      string = ''.join(entry) 
      yield string 

choice_seq = choices() 
print next(choice_seq) 
print next(choice_seq) 

발전기의 요점은 그들과 함께 상태를 유지한다는 것입니다.

0

"저장된 상태"는 현재 길이이고 itertools.product의 현재 상태입니다. 그 두 가지는 절인 수 있습니다. 여기에 몇 가지 의사 코드가 있습니다 :

import itertools 
import pickle 

choices = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789" 

def tryWithStateSave(currentlength, currentproduct): 
    try: 
     for entry in currentproduct: 
      string = ''.join(entry) 
      print string 
    except KeyboardInterrupt: 
     pickle.dump((currentlength, currentproduct), <saved state file>) 
     raise 

if <a saved state file exists>: 
    currentlength, currentproduct = pickle.load(<the saved state file>) 
    tryWithStateSave(currentlength, currentproduct) 
    currentlength += 1 
else: 
    currentlength = 0 

for length in range(currentlength+1,20): 
    tryWithStateSave(length, itertools.product(choices, repeat = length))