'Finding the middle of a list

So I am trying to find the median of the list "revenues" which will be named "base_revenue".

Comments:

#Assume that revenues always has an odd number of members

#Write code to set base_revenue = midpoint of the revenue list

#Hint: Use the int and len functions

revenues = [280.00, 382.50, 500.00, 632.50, 780.00]


 {def findMiddle(revenues):
    middle = float(len(revenues))/2
if middle % 2 != 0:
    return revenues[int(middle - .5)]
else:
    return (revenues[int(middle)], revenues[int(middle-1)])}

I'm getting invalid syntax. The median function itself works, but maybe there is a more efficient way to do it.



Solution 1:[1]

Hint: the answer to this is far simpler than you've made it. You can even do it in a single line, unless your instructor specifically requires you to define a function.

You're told the list will always have an odd number of items; all you need is the index of the middle item. Remember that in Python, indices start at 0. So, for instance, a list of length 5 will have its middle element at index 2. A list of length 7 will have its middle element at index 3. Notice a pattern?

Your assignment also reminds you about len(), which finds the length of something (such as a list), and int(), which turns things (if possible) into integers. Notably, it turns a floating-point number into the the closest integer at or below it (a "floor" function); for instance it turns 2.5 into 2.

Can you see how you might put those together to programmatically find the midpoint index?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CrazyChucky