princeofsudan

Project Euler #32 Pandigital products

Mar 31st, 2013
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.37 KB | None | 0 0
  1. #We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once;
  2. # for example, the 5-digit number, 15234, is 1 through 5 pandigital.
  3.  
  4. #The product 7254 is unusual, as the identity, 39 x 186 = 7254, containing multiplicand, multiplier, and product
  5. #is 1 through 9 pandigital.
  6.  
  7. #Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9
  8. # pandigital.
  9. #HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.
  10.  
  11.  
  12. def is1To9Pandigital(nStr):
  13.     if '0' in nStr or len(nStr) != 9:
  14.         return False
  15.     count = 0
  16.     for i in range(1,10):
  17.         if str(i) in nStr:
  18.             count +=1
  19.     if count == 9:
  20.         return True
  21.     else:
  22.         return False
  23.  
  24. products = []
  25. for i in range(1,10): # 1 digit x 4 digits = min 4 digits, max 5 gigits
  26.     for j in range(1,10000):
  27.         product = i*j
  28.         if is1To9Pandigital(str(i)+str(j)+str(product)):
  29.             products.append(product)
  30.  
  31. for i in range(1,100): # 2 digit x 3 digits = min 4 digits, max 5 gigits
  32.     for j in range(1,1000):
  33.         product = i*j
  34.         if is1To9Pandigital(str(i)+str(j)+str(product)):
  35.             products.append(product)
  36.  
  37. products = set(products) #remove duplicates
  38. count = 0
  39. for i in products: #sum products
  40.     count += i
  41. print count
Advertisement
Add Comment
Please, Sign In to add comment