2015-02-23 4 views
2
def permutations(iterable, r=None): 
    # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC 
    # permutations(range(3)) --> 012 021 102 120 201 210 
    pool = tuple(iterable) 
    n = len(pool) 
    r = n if r is None else r 
    if r > n: 
     return 
    indices = list(range(n)) 
    cycles = list(range(n, n-r, -1)) 
    yield tuple(pool[i] for i in indices[:r]) 
    while n: 
     for i in reversed(range(r)): 
      cycles[i] -= 1 
      if cycles[i] == 0: 
       indices[i:] = indices[i+1:] + indices[i:i+1] 
       cycles[i] = n - i 
      else: 
       j = cycles[i] 
       indices[i], indices[-j] = indices[-j], indices[i] 
       yield tuple(pool[i] for i in indices[:r]) 
       break 
     else: 
      return 

got = permutations(getAllTheLetters(),4) 
cnt = 0 
for i in got: 
    cnt += 1 
    print ''.join(i) 

print cnt 

выше оленья кожа отдавания «ZZZZ» или «ZZZ»
мне нужно что-то вроде ниже, где он дает: а, б, в, г .. аа , ab, ac, .. aaa, aab ...питон: получать все возможные алфавита до до заданной длины

, но do_perm() жестко закодирован в цикл четыре раза, который я не хочу делать.

def getAllTheLetters(begin='a', end='z'): 
    beginNum = ord(begin) 
    endNum = ord(end) 
    yield '' 
    for number in xrange(beginNum, endNum+1): 
     yield chr(number) 

def do_perm(l): 
    s = set() 
    for a in getAllTheLetters(): 
     for b in getAllTheLetters(): 
      for c in getAllTheLetters(): 
       for d in getAllTheLetters(): 
        to_add = "%s%s%s%s" % (a,b,c,d) 
        if to_add != "": 
         s.add(to_add) 

    return s 

got = do_perm(1) 
cnt = 0 
for i in sorted(got): 
    cnt +=1 
    print i 
print cnt 
+0

Вы хотите 'itertools.combinations_with_replacement', а не' itertools.permutations'. –

ответ

4

Вы можете просто использовать itertools.product, как этот

from itertools import product 

def get_strings(letters, max_length): 
    for i in range(1, max_length + 1): 
     for value in product(letters, repeat=i): 
      yield "".join(value) 

И когда вы вызываете его как этот

print(list(get_strings("ab", 2))) 

вы получите

['a', 'b', 'aa', 'ab', 'ba', 'bb'] 

Если вы хотите получить все значения от a к z, вы можете вызвать get_strings, как этот

from string import ascii_lowercase 
print(list(get_strings(ascii_lowercase, 4))) 

Примечание: Это создаст ад много строк, так что ваш компьютер может перестать отвечать на запросы. Если вы просто хотите итерации по строкам, используйте цикл for с get_strings, как показано ниже, и не создавайте список.

for current_string in get_strings(ascii_lowercase, 4): 
    # Process the current_string 
Смежные вопросы