samedi 17 juillet 2021

Why My loop is not iterating over the 2nd same value in the Python list ?. Im Trying to multiple 2 maximum values in the list

I Will Try My Best to Explain the Problem I am creating a function to multiple 2 maximum values in the list

for Eg : nums = [5,2,5,4]

Here My Ideal result should be 25

Multiplying 5 (of Index 0) to Multiplying 5 (of Index 2)

But It is Giving 20

IDK Why But it is Not iterating or Considering Next 5 in this list i.e 5 of index 2

Can Someone help me with that ??

def max_pair_product_fast(nums):
    num1 = max(nums)
    print("Maximun = ", num1, "Index = ",nums.index(num1))
    num2 = 0
    for i in nums:
        if  nums.index(num1) != nums.index(i) and num2 < =  i :
            num2 = i
            print("Num 2 : ",num2)

    return num1 * num2

nums = [5,2,5,4]

print("Multiplication = ",max_pair_product_fast(nums))

Output :

PS D:\Code> & C:/Users/kshar/AppData/Local/Microsoft/WindowsApps/PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0/python.exe d:/Code/Algo/mppf.py


Maximun =  5 Index =  0

Num 2 :  2

Num 2 :  4

Multiplication =  20

If I somehow Remove the Condition of nums.index(num1) != nums.index(i) then It will just Multiply the maximum value (in this case 5) with itself Only.

Aucun commentaire:

Enregistrer un commentaire