Explanation for solution to problem


#1

Here is the link to the problem: https://www.codecademy.com/paths/computer-science/tracks/cspath-flow-data-iteration/modules/dspath-lists/lessons/python-functions-lists-cc/exercises/middle-item

Hey everyone,

I was absolutely dumbfounded by this problem. Other than initializing the function in the beginning, I had no idea how to proceed and revealing the solution doesn’t help me because I need to know how each step was worked out.

  • Why is a “%” used in line 3 instead of a “/” and why is it set equal to 0?
  • Why do I have to add sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2) - 1] *? What is the difference between the two?
  • Why is the return set the way it is?

I apologize for it but, I think I may need nothing short of a walkthrough with this problem. Thank you.


#2

well, there are two kind of lists. Lists with uneven and even length

now, uneven (for example [4, 6, 8]) is easy, the middle value is 6.

but what about: [4, 4, 5, 5]? Now we need the left (4) and right (5) middle value, add them together (9) and divide by two (result: 4.5)

to determine if the list has an even or uneven length. For which we use the modulo operator (%), which gives us the remainder, then we check if the remainder equals zero

left and right middle value for lists with even length.


#3

Thank you for your help!