(Python) find the maximum product of the 2 elements in a list | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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...

22nd Mar 2018, 2:21 PM
Vicky Kuo
Vicky Kuo - avatar
6 Answers
+ 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()
22nd Mar 2018, 7:01 PM
Kirk Schafer
Kirk Schafer - avatar
+ 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))
22nd Mar 2018, 2:35 PM
Dinesh Banjara
Dinesh Banjara - avatar
+ 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.
22nd Mar 2018, 4:42 PM
Kirk Schafer
Kirk Schafer - avatar
+ 4
@Kirk, you are right l=sorted(list) print(max(l[0]*l[1],l[-1]*l[-2]))
22nd Mar 2018, 5:02 PM
Louis
Louis - avatar
+ 2
Solved!! I’m so grateful for you guys!!! You are so warm-hearted! :)
23rd Mar 2018, 10:20 AM
Vicky Kuo
Vicky Kuo - avatar