#πŸ”’ Simple function

20 messages Β· Page 1 of 1 (latest)

hollow geode
#

Hello i have to do a function. I try something but it doesn't work so i ask for help please.
Here are the instructions :
Write a max_and_index function that takes a non-empty array tab
(Python type list) of integers and returns the value of the largest element of theand the index of its first appearance in the array.
Use of the native max function is not permitted.
Examples:

max_and_index([1, 5, 6, 9, 1, 2, 3, 7, 9, 8])
(9, 3)

max_and_index([-2])
(-2, 0)
max_and_index([-1, -1, 3, 3, 3])
(3, 2)
max_and_index([1, 1, 1, 1])
(1, 0)
Also i post what i tried.

lean spearBOT
#

@hollow geode

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

solid spear
#

it's tab[i] not i[tab]

#

and you didn't define valeur_maxi

#

as for some suggestions,
β€’ try looking into the enumerate() function.
β€’ Pass through all the elements,
don't stop at the first larger element.

turbid briar
#

If valeur maxi < tab[i]:
valeur maxi = tab[i]
indice max =i

turbid briar
#

That's how you make valeur maxi the largest value

#

Also if len(tab) == 0:
return None # according to your question

solid spear
#

@hollow geode utilizing the latter, you'd get something like this -

def max_index(tab):
   i_max, v_max = 0, tab[0]

   for i, v in enumerate(tab):
      if v > v_max:
          i_max, v_max = i, v

   return (i_max, v_max)
solid spear
hollow geode
#

if i want to enumerate i have to make a for i in ...

turbid briar
solid spear
turbid briar
#

Yes he is correct you need range

hollow geode
#

Finally i find the problem thank you

lean spearBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.