制作随机电话号码xxx-xxx-xxxx

Tun*_*chi 0 python python-2.7

它将返回一个随机电话号码xxx-xxx-xxxx,但有以下限制:

  • 区号不能以零开头,
  • 中间三位数都不能是9,
  • 中三位数不能为000,
  • 最后4位数不能全部相同.

Kyl*_*ion 5

稍微简单的解决方案。

import random

def phn():
    n = '0000000000'
    while '9' in n[3:6] or n[3:6]=='000' or n[6]==n[7]==n[8]==n[9]:
        n = str(random.randint(10**9, 10**10-1))
    return n[:3] + '-' + n[3:6] + '-' + n[6:]
Run Code Online (Sandbox Code Playgroud)

以及每次都第一次返回的解决方案(没有 while 循环)。

import random

def phn():
    p=list('0000000000')
    p[0] = str(random.randint(1,9))
    for i in [1,2,6,7,8]:
        p[i] = str(random.randint(0,9))
    for i in [3,4]:
        p[i] = str(random.randint(0,8))
    if p[3]==p[4]==0:
        p[5]=str(random.randint(1,8))
    else:
        p[5]=str(random.randint(0,8))
    n = range(10)
    if p[6]==p[7]==p[8]:
        n = (i for i in n if i!=p[6])
    p[9] = str(random.choice(n))
    p = ''.join(p)
    return p[:3] + '-' + p[3:6] + '-' + p[6:]
Run Code Online (Sandbox Code Playgroud)

  • 有不确定时间的缺点(根据 [墨菲定律](https://en.wikipedia.org/wiki/Murphy%27s_law),它有时会窒息)。 (2认同)

小智 5

我试图结合OP,@ kgull,@ Cyber​​的代码和@ ivan_pozdeev的关注,也满足OP的要求:

>>> def gen_phone():
    first = str(random.randint(100,999))
    second = str(random.randint(1,888)).zfill(3)

    last = (str(random.randint(1,9998)).zfill(4))
    while last in ['1111','2222','3333','4444','5555','6666','7777','8888']:
        last = (str(random.randint(1,9998)).zfill(4))

    return '{}-{}-{}'.format(first,second, last)

>>> for _ in xrange(10):
    gen_phone()

'496-251-8419'
'102-665-1932'
'262-624-5025'
'230-459-3242'
'355-131-0243'
'488-001-6828'
'244-539-2369'
'896-547-4539'
'522-406-8256'
'789-373-4240'
Run Code Online (Sandbox Code Playgroud)