数字和字母的组合

发布于 2024-10-12 05:36:03 字数 847 浏览 5 评论 0原文

#!/usr/bin/python
import random
lower_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
upper_a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

all = []
all = " ".join("".join(lower_a) + "".join(upper_a) + "".join(num))
all = all.split()
x = 1
c = 1
while x < 10:
    y = []
    for i in range(c):
            a = random.choice(all)
            y.append(a)
    print "".join(y)
    x += 1
    c += 1

我现在输出的内容如下:

5
hE
HAy
1kgy
Pt6JM
2pFuCb
Jv5osaX
5q8PwWAO
SvHWRKfI5

如何让它系统地遍历给定长度的字母(大写和小写)的每个组合,然后在该长度上加 1 并重复该过程?

#!/usr/bin/python
import random
lower_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
upper_a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

all = []
all = " ".join("".join(lower_a) + "".join(upper_a) + "".join(num))
all = all.split()
x = 1
c = 1
while x < 10:
    y = []
    for i in range(c):
            a = random.choice(all)
            y.append(a)
    print "".join(y)
    x += 1
    c += 1

What I have now outputs something like the following:

5
hE
HAy
1kgy
Pt6JM
2pFuCb
Jv5osaX
5q8PwWAO
SvHWRKfI5

How can I make it systematically go through every combination of letters (upper and lowercase) for a given length, then add 1 to that length and repeat the process?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

迷你仙 2024-10-19 05:36:03

最好不要重新创建标准库中已有的功能。

看一下标准库模块 itertools 。特别是 combinations() , permutations(),和 product() 函数。

import itertools

lower_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
upper_a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

all = lower_a + upper_a + num

for r in range(1, 3):
    for s in itertools.product(all, repeat=r):
         print ''.join(s)

如果您的 Python 版本较旧,您可能无法访问这些函数。但是,如果您查看 Python 2.6 的文档,您可以了解如何在 Python 中实现所有这些功能。例如,itertools.product 的实现如下:

def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

您也可以尝试递归解决方案:

lower_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
upper_a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

all = lower_a + upper_a + num

def recursive_product(myList, length, myString = ""):
    if length == 0:
        print myString
        return
    for c in myList:
        recursive_product(myList, length-1, myString + c)
    
for r in range(1, 3):
    recursive_product(all, r)

It's best not to recreate functionality that is already in the standard library.

Take a look at the standard library module itertools. Particularly the combinations(), permutations(), and product() functions.

import itertools

lower_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
upper_a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

all = lower_a + upper_a + num

for r in range(1, 3):
    for s in itertools.product(all, repeat=r):
         print ''.join(s)

If your version of Python is old you may not have access to these functions. However if you take a look in the documentation for Python 2.6, you can see how all of these functions can be implemented in Python. For instance, the implementation of itertools.product is given as:

def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

You could also try a recursive solution instead:

lower_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
upper_a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

all = lower_a + upper_a + num

def recursive_product(myList, length, myString = ""):
    if length == 0:
        print myString
        return
    for c in myList:
        recursive_product(myList, length-1, myString + c)
    
for r in range(1, 3):
    recursive_product(all, r)
怕倦 2024-10-19 05:36:03

pythonic 方式 ;)

打印所有组合:


from itertools import combinations

symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
          "abcdefghijklmnopqrstuvwxyz"
          "0123456789"
max_length = len(symbols)

for length in xrange(1, max_length + 1):
    for word in map(''.join, combinations(symbols, length)):
        print word

更好的是,创建一个生成组合的生成器对象,以便稍后可以决定如何处理它们,而不必存储 2 ** 62 字符串 (< code>7.6040173890593902e+35 字节)在内存中。


from itertools import combinations, product

symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
          "abcdefghijklmnopqrstuvwxyz"
          "0123456789"
max_length = len(symbols)

# generator of all combinations
def words1(chars=symbols, max_len=max_length):
    for length in xrange(1, max_length + 1):
        for word in map(''.join, combinations(symbols, length)):
            yield word

# generator of all combinations allowing repetitions
def words1(chars=symbols, max_len=max_length):
    for length in xrange(1, max_length + 1):
        for word in map(''.join, product(*[symbols]*length)):
            yield word


for word in words1():
    #do something with word
    print word

combinationsproduct 以及许多其他函数都返回迭代器而不是列表,以节省内存:


>>> print combinations('0123456789',2)
<itertools.combinations object at 0x13e34b0>
>>> print list(combinations('0123456789',2))
[('0', '1'), ('0', '2'), ('0', '3'), ('0', '4'), ('0', '5'), ('0', '6'), ('0', '7'), ('0', '8'), ('0', '9'), ('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('1', '6'), ('1', '7'), ('1', '8'), ('1', '9'), ('2', '3'), ('2', '4'), ('2', '5'), ('2', '6'), ('2', '7'), ('2', '8'), ('2', '9'), ('3', '4'), ('3', '5'), ('3', '6'), ('3', '7'), ('3', '8'), ('3', '9'), ('4', '5'), ('4', '6'), ('4', '7'), ('4', '8'), ('4', '9'), ('5', '6'), ('5', '7'), ('5', '8'), ('5', '9'), ('6', '7'), ('6', '8'), ('6', '9'), ('7', '8'), ('7', '9'), ('8', '9')]

The pythonic way ;)

Print all combinations:


from itertools import combinations

symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
          "abcdefghijklmnopqrstuvwxyz"
          "0123456789"
max_length = len(symbols)

for length in xrange(1, max_length + 1):
    for word in map(''.join, combinations(symbols, length)):
        print word

Even better, create an generator object which yields the combinations, so that one can decide later what to do with them without having to store 2 ** 62 strings (7.6040173890593902e+35 bytes) in memory.


from itertools import combinations, product

symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
          "abcdefghijklmnopqrstuvwxyz"
          "0123456789"
max_length = len(symbols)

# generator of all combinations
def words1(chars=symbols, max_len=max_length):
    for length in xrange(1, max_length + 1):
        for word in map(''.join, combinations(symbols, length)):
            yield word

# generator of all combinations allowing repetitions
def words1(chars=symbols, max_len=max_length):
    for length in xrange(1, max_length + 1):
        for word in map(''.join, product(*[symbols]*length)):
            yield word


for word in words1():
    #do something with word
    print word

Both combinations and product, as well as many other functions, return iterators instead of lists in order to save memory:


>>> print combinations('0123456789',2)
<itertools.combinations object at 0x13e34b0>
>>> print list(combinations('0123456789',2))
[('0', '1'), ('0', '2'), ('0', '3'), ('0', '4'), ('0', '5'), ('0', '6'), ('0', '7'), ('0', '8'), ('0', '9'), ('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('1', '6'), ('1', '7'), ('1', '8'), ('1', '9'), ('2', '3'), ('2', '4'), ('2', '5'), ('2', '6'), ('2', '7'), ('2', '8'), ('2', '9'), ('3', '4'), ('3', '5'), ('3', '6'), ('3', '7'), ('3', '8'), ('3', '9'), ('4', '5'), ('4', '6'), ('4', '7'), ('4', '8'), ('4', '9'), ('5', '6'), ('5', '7'), ('5', '8'), ('5', '9'), ('6', '7'), ('6', '8'), ('6', '9'), ('7', '8'), ('7', '9'), ('8', '9')]

公布 2024-10-19 05:36:03

看一下 itertools 模块中的函数组合 (http://docs.python.org/library/itertools.html#itertools.combinations)

import itertools
... setup all ...
for ilen in range(1, len(all)):
  for combo in itertools.combinations(all, ilen):
    print combo

Take a look at function combinations in the module itertools (http://docs.python.org/library/itertools.html#itertools.combinations)

import itertools
... setup all ...
for ilen in range(1, len(all)):
  for combo in itertools.combinations(all, ilen):
    print combo
过去的过去 2024-10-19 05:36:03

我还没有对此进行测试,但我认为基本思想应该成立。如果不起作用请评论,我会调试它:

L = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz', '0123456789']
def f(L, length, s=''):
    print s
    if len(s) == length:
        print s
    else:
        for word in L:
            for char in word:
                w = word.replace(char, '')
                l = L[:]
                l.remove(word)
                l.append(w)
                f(l, length, s+char)

I haven't tested this, but I think the basic idea should hold. Please comment if it doesn't work and I'll debug it:

L = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz', '0123456789']
def f(L, length, s=''):
    print s
    if len(s) == length:
        print s
    else:
        for word in L:
            for char in word:
                w = word.replace(char, '')
                l = L[:]
                l.remove(word)
                l.append(w)
                f(l, length, s+char)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文