Tunechi Tunechi - 9 months ago 40
Python Question

Making random phone number xxx-xxx-xxxx

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


  • The area code cannot start with a zero,

  • None of the middle three digits can be a 9,

  • Middle three digits cannot be 000,

  • Last 4 digits cannot all be the same.


Answer Source

Slightly simpler solution.

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

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