Skip to content

Commit d99d1d2

Browse files
author
Mia von Steinkirch
committed
easy as a piece of cake
1 parent 85ecba5 commit d99d1d2

File tree

2 files changed

+92
-0
lines changed

2 files changed

+92
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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"
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#!/bin/python
2+
3+
"""
4+
You have a list of integers, and for each index you want to find the product of every integer except the integer at that index.
5+
6+
Write a function get_products_of_all_ints_except_at_index() that takes a list of integers and returns a list of the products.
7+
8+
For example, given:
9+
10+
[1, 7, 3, 4]
11+
12+
your function would return:
13+
14+
[84, 12, 28, 21]
15+
16+
by calculating:
17+
18+
[7 * 3 * 4, 1 * 3 * 4, 1 * 7 * 4, 1 * 7 * 3]
19+
20+
Here's the catch: You can't use division in your solution!
21+
"""
22+
23+
def get_products_of_all_ints_except_at_index(array):
24+
prod_array = []
25+
26+
for i, num in enumerate(array):
27+
prod = 1
28+
for other_num in array[:i] + array[i+1:]:
29+
prod *= other_num
30+
31+
prod_array.append(prod)
32+
33+
return prod_array
34+
35+
36+
array = [1, 7, 3, 4]
37+
print get_products_of_all_ints_except_at_index(array)
38+
print "Should be [84, 12, 28, 21]"

0 commit comments

Comments
 (0)