1+ #!/bin/python
2+
3+ """
4+ Given a list of integers, find the highest product you can get from three of the integers.
5+
6+ The input list_of_ints will always have at least three integers.
7+ """
8+
9+ def highest_num (list_of_ints ):
10+
11+ if len (list_of_ints ) == 3 :
12+ return list_of_ints [0 ]* list_of_ints [1 ]* list_of_ints [2 ]
13+
14+ sorted_list = sorted (list_of_ints )
15+
16+ return sorted_list [- 3 ]* sorted_list [- 2 ]* sorted_list [- 1 ]
17+
18+
19+ def highest_product_of_3_On (list_of_ints ):
20+
21+ highest = max (list_of_ints [0 ], list_of_ints [1 ])
22+ lowest = min (list_of_ints [0 ], list_of_ints [1 ])
23+ highest_product_of_2 = list_of_ints [0 ] * list_of_ints [1 ]
24+ lowest_product_of_2 = list_of_ints [0 ] * list_of_ints [1 ]
25+
26+ highest_product_of_3 = list_of_ints [0 ] * list_of_ints [1 ] * list_of_ints [2 ]
27+
28+ for i in range (2 , len (list_of_ints )):
29+ current = list_of_ints [i ]
30+
31+ highest_product_of_3 = max (highest_product_of_3 ,
32+ current * highest_product_of_2 ,
33+ current * lowest_product_of_2 )
34+
35+ highest_product_of_2 = max (highest_product_of_2 ,
36+ current * highest ,
37+ current * lowest )
38+
39+ lowest_product_of_2 = min (lowest_product_of_2 ,
40+ current * highest ,
41+ current * lowest )
42+
43+ highest = max (highest , current )
44+
45+ lowest = min (lowest , current )
46+
47+ return highest_product_of_3
48+
49+ list_of_ints = [4 , 2 , 5 , 6 ]
50+ print highest_num (list_of_ints )
51+ print "Should be 120"
52+
53+ print highest_product_of_3_On (list_of_ints )
54+ print "Should be 120"
0 commit comments