~ryan-smith/+junk/ProjectEuler

« back to all changes in this revision

Viewing changes to Problem9.py

  • Committer: ryan_smith at operamail
  • Date: 2013-12-02 22:24:48 UTC
  • Revision ID: ryan_smith@operamail.com-20131202222448-pjasa066in0b7owl
Two more

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
def find_triplet(total):
 
2
    '''
 
3
    (int) -> list of list of ints
 
4
 
 
5
    Returns the list of ints that are pythagorean triplets and whose sum
 
6
    is total.
 
7
 
 
8
    >>>find_triplet(12)
 
9
    [3, 4, 5]
 
10
    '''
 
11
    c = total - 2 #highest possible value of c
 
12
    a = 1
 
13
    b = total - (c + a) #the sum will always be total
 
14
    n = total // 3 #save yourself from doing the same calculation hundreds of times
 
15
    triples = [] #a place to store the triples
 
16
 
 
17
    while(c >= n): #c must be greater than both a and b
 
18
        while(b >= a): #a will always be higher in this algorithm
 
19
            if(a**2 + b**2 == c**2): #test for pythagorean triples
 
20
                found = [a, b, c]
 
21
                triples.append(found)
 
22
            a += 1
 
23
            b = total - (c + a)
 
24
        c -= 1
 
25
        a = 1
 
26
        b = total - (c + a)
 
27
 
 
28
    return triples
 
29
 
 
30
def multiples(lists):
 
31
    '''
 
32
    (list of list of ints) -> list of ints
 
33
 
 
34
    Returns a list of the products of each list of ints
 
35
 
 
36
    >>>multiples([[3, 4, 5]])
 
37
    60
 
38
    '''
 
39
    product = 1
 
40
    final = []
 
41
    for a in lists:
 
42
        for b in a:
 
43
            product *= b
 
44
        final.append(product)
 
45
        product = 1
 
46
 
 
47
    return final
 
48
 
 
49
if __name__ == '__main__':
 
50
    print("You are looking for the products of pythagorean triples whose sum is P.\n")
 
51
    target = input("What value would you like to use for P?")
 
52
    answer = multiples(find_triplet(target))
 
53
    print("The products of pythagorean triples whose sum is {0} is {1}.\n".format(target, answer))
 
54
    
 
55
    
 
56
            
 
57