Skip to content

Instantly share code, notes, and snippets.

@aksiksi
Created December 28, 2011 23:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aksiksi/1530419 to your computer and use it in GitHub Desktop.
Save aksiksi/1530419 to your computer and use it in GitHub Desktop.
Finds all products of the digits of 5-digit numbers and creates two files: one contains the products and keys, ranked by products, while the other contains the number of occurrences of each product, ranked by occurrence, both in ascending order.
# Written by Assil Ksiksi
# Date: Thursday, December 29th, 3:12 am (GMT +4)
# I basically wrote this to determine whether or not a pattern exists in the products of the digits
# of all 5-digit numbers. Sadly, none exist, or at least I didn't see one.
# Runtime is fairly slow. It takes 1.05916786194s for all 5-digit numbers. I don't see how it
# can be optimized, so that should do the trick.
# References:
# http://coreygoldberg.blogspot.com/2008/07/python-counting-items-in-list.html
# http://drumcoder.co.uk/blog/2010/sep/11/find-key-value-python-dictionary/
# http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/
results = []
occurences = {}
for i in xrange(10000, 100000):
product = 1
if '0' not in str(i):
for j in [int(x) for x in str(i)]:
product *= j
results.append(product)
for i in set(results):
occurences[i] = results.count(i)
# Creates a file in script directory
f = open('keys.txt', 'w')
# Prints in order of magnitude of products by iterating through a sorted list of (key, value) pairs - the keys are also reversed (greatest to least)
for key, value in sorted(occurences.iteritems(), reverse=True):
f.write("Product: {0}, Occurences: {1}\n".format(key, value)) # Writes lines to file instead of terminal/command prompt
# Closes file
f.close()
g = open('values.txt', 'w')
# Prints in order of occurences by iterating through a list of sorted (key, value) pairs and using a lambda function to switch their places, making them (value, key). They are reversed as well.
for key, value in sorted(occurences.iteritems(), key=lambda (k, v): (v,k), reverse=True):
g.write("Product: {0}, Occurences: {1}\n".format(key, value))
g.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment