制作随机电话号码 xxx-xxx-xxxx [英] Making random phone number xxx-xxx-xxxx

查看:48
本文介绍了制作随机电话号码 xxx-xxx-xxxx的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

It will return a random phone number xxx-xxx-xxxx with the following restrictions:

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

推荐答案

稍微简单的解决方案.

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:]

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

And a solution that returns the first time, every time (no while loops).

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:]

这篇关于制作随机电话号码 xxx-xxx-xxxx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆