Harry Cotte Harry Cotte - 12 days ago 6
Python Question

Python result of a strange function, that I can't reproduce in another language

My python function :

def searchMAX(Dict):
v=list(Dict.values())
return list(Dict.keys())[v.index(max(v))]


I can't reproduce it in java to understand what's its output

If I do :

myDico ={0:0.0}
myDico.update({1:1.2})
myDico.update({2:11.2})
myDico.update({3:17.2})
myMax = searchMAX(myDico)
print(*myMax, sep='\n')


I have this error :

TypeError: print() argument after * must be an iterable, not int


With
print(myMax, sep'\n')
only retun 3 not a list :( ?

Answer

Assuming that Dict is a Python dict then:

v = list(Dict.values())

make a list of the iterator over the values of Dict and assings it to v

Then

return list(Dict.keys())[v.index(max(v))]

make a list of the keys of Dict and and returns the key that has the maximum value associated with it by finding the index of the maximum value (v.index(max(v))) and using that index on the list.

Thus searchMAX return a key which in your case is always an integer and you cannot pass that to print() with a *. You should do:

print(Max, sep='\n')