Guest User

prime danish phone numbers

a guest
May 14th, 2013
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import re
  2.  
  3. #gen_primes is modified from http://stackoverflow.com/a/568618/203705
  4. def gen_primes(start, end):
  5.  
  6.     # Maps composites to primes witnessing their compositeness.
  7.     # This is memory efficient, as the sieve is not "run forward"
  8.     # indefinitely, but only as long as required by the current
  9.     # number being tested.
  10.     #
  11.     D = {}  
  12.  
  13.     # The running integer that's checked for primeness
  14.     q = 2  
  15.     primes = []
  16.  
  17.     while q != end:
  18.         if q not in D:
  19.             # q is a new prime.
  20.             # Yield it and mark its first multiple that isn't
  21.             # already marked in previous iterations
  22.             #
  23.             if q >= start:
  24.                 primes.append(q)
  25.             D[q * q] = [q]
  26.         else:
  27.             # q is composite. D[q] is the list of primes that
  28.             # divide it. Since we've reached q, we no longer
  29.             # need it in the map, but we'll mark the next
  30.             # multiples of its witnesses to prepare for larger
  31.             # numbers
  32.             #
  33.             for p in D[q]:
  34.                 D.setdefault(p + q, []).append(p)
  35.             del D[q]
  36.  
  37.         q += 1
  38.     return primes
  39.  
  40. def get_danish_nums(name):
  41.     nums = {}
  42.     with open(name, 'r') as f:
  43.         lines = f.readlines()
  44.  
  45.     for line in lines:
  46.         vals = line.split(',')
  47.         if vals[2].strip() != 'Reserve / Reserve':
  48.             if len(vals[0].strip()) == 8:
  49.                 start = int(re.sub(r'[a-z]','0',vals[0]))
  50.                 end = int(re.sub(r'[a-z]','9',vals[0]))
  51.                 if start == end:
  52.                     nums[start] = True
  53.                 else:
  54.                     for num in range(start, end+1):
  55.                         nums[num] = True
  56.     return nums
  57.  
  58.  
  59. if __name__ == '__main__':
  60.     print("Getting nums...")
  61.     #CSV built from spreadsheet found here:
  62.     #http://www.erhvervsstyrelsen.dk/numbering_lists
  63.     nums = get_danish_nums('danish_numberlist.csv')
  64.     start = min(nums)
  65.     end = max(nums)
  66.  
  67.     print("Getting primes...")
  68.     primes = gen_primes(start,end)
  69.     i = 0
  70.     print("Checking...")
  71.     for prime in primes:
  72.         if nums.get(prime, False):
  73.             print("%s is valid prime phone number!" % prime)
  74.             i+=1
  75.     print("%s of %s valid danish phone numbers are prime." % (i, len(nums)))
Advertisement
Add Comment
Please, Sign In to add comment