0

我用 Python 编写了一个简单的程序来生成一个包含 5 个数字的随机字符串:

import random

numcount = 5
fstring = ""

for num in range(19): #strings are 19 characters long
    if random.randint(0, 1) == 1:
        x = random.randint(1, 26)
        x += 96
        fstring += (chr(x).upper())
    elif not numcount == 0:
        x = random.randint(0, 9)
        fstring += str(x)
        numcount -= 1

print(fstring)

不太难,对吧?除了一件非常奇怪的事情:它返回的字符串是随机长度的。我已经多次运行代码,以下是我的一些结果:

>>> ================================ RESTART ================================
>>> 
VQZ99HA5DER0CES4
>>> ================================ RESTART ================================
>>> 
05PS0T86LOZS
>>> ================================ RESTART ================================
>>> 
E2QX8296XK
>>> ================================ RESTART ================================
>>> 
M5X9K457QDNBPX

我不知道发生了什么......谁能指出我正确的方向?

4

2 回答 2

8

你掷硬币 19 次;50% 的时间你选择一个字母,另外 50% 的时间你选择一个数字,但最多只有 5 次。如果您更频繁地点击数字选项,则不会添加任何内容

因此,您构建了一个最多19 个字符的字符串,但它可以更短。平均而言,它将是 9.5 个字母和 5 个数字。

仅当您仍有要选择的数字时才选择数字:

import string
import random

numcount = 5
chars = []

for num in range(19): #strings are 19 characters long
    if numcount and random.random() < 0.5:
        chars.append(str(random.randint(0, 9)))
        numcount -= 1
    else:
        chars.append(random.choice(string.ascii_uppercase))

fchars = ''.join(chars)

演示:

>>> import string
>>> import random
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> numcount = 5
>>> chars = []
>>> for num in range(19): #strings are 19 characters long
...     if numcount and random.random() < 0.5:
...         chars.append(str(random.randint(0, 9)))
...         numcount -= 1
...     else:
...         chars.append(random.choice(string.ascii_uppercase))
... 
>>> ''.join(chars)
'3M6G97OEHP6TGYRONPV'
>>> len(chars)
19
于 2014-06-19T22:01:33.670 回答
0
import random

numcount = 5
fstring = ""


while numcount > 0:
    if random.randint(0, 1) == 1:
        x = random.randint(1, 26)
        x += 96
        fstring += (chr(x).upper())
    elif not numcount == 0:
        x = random.randint(0, 9)
        fstring += str(x)
    numcount -= 1

print(fstring)
于 2014-06-19T22:04:26.923 回答