+ 3
(Python) find the maximum product of the 2 elements in a list
For example, List = [-4,-10,1,2,3,4 ] The max product of 2 elements in this list is “40”. How can I use the definition of a function to find the answer? Thank you...
6 Respostas
+ 2
Thanks @Louis; Python seems to have this weird privileged status where things that ought to be expensive aren't; I didn't remember offhand if Python's sort was significantly more expensive than a scan and appreciate the sample.
@Vicky: Just to adapt Louis's sample to your function need, you could indent it beneath a function definition and return the result:
def largest_product(list):
# Louis's code
# return instead of print()
+ 4
This code provides solution for your problem...
list = [-4,-10,1,2,3,4]
y = []
n = len(list)
for i in range(n):
for j in range(i):
prev = list[i]
y.append(prev*list[j])
print(max(y))
+ 4
For a general solution reducing calculations, you could sort the list (4+ elements) then take the largest of the bottom two's product vs. the top two's product.
(1 sort, two multiplies, 1 compare)
Someone let me know if I've missed the algorithm boat here; like if a scan for lowest, lastlow, highest, lasthigh is warranted.
+ 4
@Kirk, you are right
l=sorted(list)
print(max(l[0]*l[1],l[-1]*l[-2]))
+ 2
Solved!! I’m so grateful for you guys!!! You are so warm-hearted! :)