Created
March 25, 2014 07:09
-
-
Save mattkenn4545/9756523 to your computer and use it in GitHub Desktop.
Pythagorean Triplet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'''Pythagorean Triplet | |
dumb_triplet is dumb because it is... this is by design | |
''' | |
import random | |
from datetime import datetime | |
print '##############The Dumb way##############\nLets just randomly guess what a, b, and c are...' | |
def dumb_triplet(): | |
results = {} | |
found_it = False | |
tries = 0 | |
rechecks = 0 | |
early_out = 0 | |
while True: | |
tries += 1 | |
if tries % 1000000 == 0 or found_it: | |
print 'Tries: {0}' \ | |
' Guesses(misses/uniques): {1}/{2}={3}%'.format(tries, | |
len(results), | |
rechecks, | |
round(rechecks/float(len(results)), 4)*100) | |
print 'early_out: {0}%'.format(round(early_out/float(tries), 4) * 100) | |
if found_it: | |
break | |
a = random.randint(1, 498) | |
b = random.randint(a + 1, 499) | |
c = random.randint(b + 1, 500) | |
if a + b + c != 1000: | |
early_out += 1 | |
continue | |
key = '{0}{1}{2}'.format(a, b, c) | |
if key not in results: | |
if a**2 + b**2 == c**2: | |
found_it = True | |
else: | |
results[key] = None | |
else: | |
rechecks += 1 | |
print 'GOT IT!!!' | |
return a, b, c | |
start = datetime.now() | |
print dumb_triplet() | |
print '{0} elapsed time'.format(datetime.now() - start) | |
print '\n\n##############The less dumb, why cant I just import math, way##############' | |
loops = 0 | |
found = False | |
from cmath import sqrt | |
def listcom_triplet(): | |
def check_trip(a,b, num): | |
global loops | |
global found | |
loops += 1 | |
result = a + b + sqrt(a**2 + b**2) == num | |
found = result | |
return result | |
num = 1000 | |
start = datetime.now() | |
print [(a, b, a+b) for a in xrange(1, num) for b in xrange(a + 1, num/2) if not found and check_trip(a, b, num)][0] | |
print '{0} elapsed time'.format(datetime.now() - start) | |
print "Loops {0}".format(loops) | |
listcom_triplet() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment