import random
def rand_x_digit_num(x, leading_zeroes=True):
"""Return an X digit number, leading_zeroes returns a string, otherwise int"""
if not leading_zeroes:
# wrap with str() for uniform results
return random.randint(10**(x-1), 10**x-1)
else:
if x > 6000:
return ''.join([str(random.randint(0, 9)) for i in xrange(x)])
else:
return '{0:0{x}d}'.format(random.randint(0, 10**x-1), x=x)
def timer(x):
s1 = datetime.now()
a = ''.join([str(random.randint(0, 9)) for i in xrange(x)])
e1 = datetime.now()
s2 = datetime.now()
b = str("%0." + str(x) + "d") % random.randint(0, 10**x-1)
e2 = datetime.now()
print "a took %s, b took %s" % (e1-s1, e2-s2)
速度测试结果:
>>> timer(1000)
a took 0:00:00.002000, b took 0:00:00
>>> timer(10000)
a took 0:00:00.021000, b took 0:00:00.064000
>>> timer(100000)
a took 0:00:00.409000, b took 0:00:04.643000
>>> timer(6000)
a took 0:00:00.013000, b took 0:00:00.012000
>>> timer(2000)
a took 0:00:00.004000, b took 0:00:00.001000
randrange(self, start, stop=None, step=1, int=<type 'int'>, default=None, maxwidth=9007199254740992L) method of random.Random instance
Choose a random item from range(start, stop[, step]).
This fixes the problem with randint() which includes the
endpoint; in Python this is usually not what you want.
Do not supply the 'int', 'default', and 'maxwidth' arguments.
直截了当的方法有什么不对?
如果你想用前导零,你需要一个字符串。
编辑:
我自己解决这个问题的方法是这样的:
测试结果:
速度计时方法:
速度测试结果:
它告诉我们:
对于长度小于6000个字符的任何数字,我的方法都更快——有时更快,但对于较大的数字,arshajii建议的方法看起来更好。
做
random.randrange(10**11, 10**12)
。它的工作方式就像randint
遇到range
从文档中:
这实际上就像做
random.choice(range(10**11, 10**12))
或random.randint(10**1, 10**12-1)
。因为它符合与range()
相同的语法,所以它比这两个选项更直观、更干净如果允许前导零:
由于允许前导零(通过您的注释),您还可以使用:
编辑:当然,如果您想要一个字符串,您可以省略
int
部分:在我看来,这似乎是最直接的方法。
相关问题 更多 >
编程相关推荐