-1

I'm trying to find the median in a list. The equation to find the median is N terms/2. The code i've tried is to find and index the number but when i index i get 0 or an error, why is this?

def Median():
#MedianList_Str = ""
MedianList = [2,4,6]
print("What number do you want to add to the array, enter 0 to exit")
try:
    Int = int(input())
    if Int == 0:
        QuitApp()
    else:
       MedianList.append(Int)
except:
    print("Please enter a number")

MedianT = math.floor(len(MedianList)/2) #finds the nth term 
MedianList.sort #sorts the list so you can find the median term
MedianList_Str.join(MedianList)

this is what i've done. I've also tried index

def Median():
MedianList_Str = ""
MedianList = [2,4,6]
print("What number do you want to add to the array, enter 0 to exit")
try:
    Int = int(input())
    if Int == 0:
        QuitApp()
    else:
       MedianList.append(Int)
except:
    print("Please enter a number")

MedianT = math.floor(len(MedianList)/2) #finds the nth term 
MedianList.sort #sorts the list so you can find the median term
print(MedianList.index(MedianT))

which gets me 0

what can i do to get me the median? I understand that there already exists such a question but i want to try a different way.

NeoJoker26
  • 49
  • 1
  • 8
  • 1
    You never call `sort`, (`sort()`), and you also never appear to call your `Median` function. – Carcigenicate Feb 21 '20 at 17:09
  • 2
    You have to call the sort function (`MedianList.sort()`). Also, you want to be running `MedianList[MedianT]` rather than `.index`, as `.index` *looks* for a value, while `[]` *accesses* a value. – rassar Feb 21 '20 at 17:09
  • 1
    Does this answer your question? [Finding median of list in Python](https://stackoverflow.com/questions/24101524/finding-median-of-list-in-python) – wjandrea Feb 21 '20 at 17:10
  • 2
    @wjandrea: If it's just "how to get it?" then yeah. But I suspect they're trying to write their own, and want to know why it's broken (which rassar explained in the above comment). – ShadowRanger Feb 21 '20 at 17:12
  • i tried to use the [] and i got this "'builtin_function_or_method' object is not subscriptable " @rassar and yes i saw that but im trying to create my own, however thanks for trying :) – NeoJoker26 Feb 21 '20 at 17:14
  • @ShadowRanger Yeah I thought that myself but based on the title I assumed they're just trying to find any solution. – wjandrea Feb 21 '20 at 17:17
  • I'm trying to add to the list then sort the list and find the middle term. Im still new to python and im trying to do what id do in VB. thanks for the tip though :) – NeoJoker26 Feb 21 '20 at 17:21
  • 1
    @rassar: The code fairly clearly doesn't reassign `MedianList`; you'd get a completely different error if it did. You *can't* say `MedianList = MedianList.sort()` without breaking everything, and it's weird to bring it up when they clearly didn't do it. – ShadowRanger Feb 21 '20 at 17:28

4 Answers4

2

Here's a nice trick to avoid using if/else to handle the odd and even length cases separately: the indices in the middle are (len(nums) - 1) // 2 and len(nums) // 2. If the length is odd, then these indices are equal, so adding the values and dividing by 2 has no effect.

Note that you should do floor-division with the // operator to get an integer to use as an index.

def median(nums):
    nums = sorted(nums)
    middle1 = (len(nums) - 1) // 2
    middle2 = len(nums) // 2
    return (nums[middle1] + nums[middle2]) / 2

Examples:

>>> median([1, 2, 3, 4])
2.5
>>> median([1, 2, 3, 4, 5])
3.0
kaya3
  • 47,440
  • 4
  • 68
  • 97
  • Could you explain why you wrote "def median(nums):" (the nums part), but the rest of the code does seem a lot more efficient, thanks :D – NeoJoker26 Feb 21 '20 at 17:23
  • 1
    That is how you define a function in Python. See the tutorial if this is a new concept: [Defining Functions](https://docs.python.org/3/tutorial/controlflow.html#defining-functions) – kaya3 Feb 21 '20 at 17:25
  • could you edit that into my code? I somewhat understood it but when i put it into my own code i keep getting an error. i did this def Median(MedianList): MedianList = [2,4,6] print("What number do you want to add to the array, enter 0 to get the average") try: Int = int(input()) if Int == 0: QuitApp() else: MedianList.append(Int) except: print("Please enter a number") middle1 = (len(MedianList) - 1) // 2 middle2 = len(MedianList) // 2 return (MedianList[middle1] + MedianList[middle2]) / 2 – NeoJoker26 Feb 21 '20 at 17:29
  • No, I cannot write your code for you, especially since it is your homework. Stack Overflow is a question & answer site, not a code-writing service. – kaya3 Feb 21 '20 at 17:32
2

As others have mentioned, I would used sorted(MedianT) instead of MeadianT.sort().

In addition, use array based indexing instead of the .index() function.
For example, this:

print(MedianList[MedianT])

Instead of this:

print(MedianList.index(MedianT))

I have included below with comments the logic and thought process of finding median value of an array in Python.

def median(array):
    length = len(array)
    sorted_arr = sorted(array) # sorting in O(n) time or linear complexity
    # we are subtracting 1 from overall 
    # length because indexing is 0-based
    # essentially indexes of arrays start at 0
    # while counting length starts at 1
    # idx_norm = (length-1) / 2 # using only single division operator yields a float
    idx = (length-1) // 2 # using floor division operator // yields an Int which can be used for index

    # we run a simple condition to see 
    # whether if the overall length of array
    # is even or odd.
    # If odd then we can use index value (idx) to find median
    # we use modulus operator to see if if there is any remainder
    # for a division operation by 2. If remainder equals 0 then
    # array is even. If not array is odd.
    if length % 2 == 0:
        return (sorted_arr[idx] + sorted_arr[idx + 1]) / 2.0 # if you need an Int returned, then wrap this operation in int() conversion method
    else:
        return sorted_arr[idx]
    # If even we have to use index value (idx) and the next index value (idx + 1)
    # to create total and then divide for average

a = [1, 2, 3, 4, 12, 1, 9] # 7 elements, odd length --> return 3
b = [2, 3, 7, 6, 8, 9] # 6 elements, even length --> return 6.5

median(a)
median(b)

Please let me know if you have any questions and hope this helps. Cheers!

Azametzin
  • 5,223
  • 12
  • 28
  • 46
Kevin Carr
  • 56
  • 3
1

The median is either the middle element by value, or the average of the middle two if the length of the array is even.

So first we must sort the array, and then apply our logic.

def median(l):
    l = sorted(l)
    middle = len(l) // 2
    return l[middle] if len(l) % 2 == 1 else (l[middle - 1] + l[middle]) / 2

Note that there exist more efficient algorithms to find the median, that take O(n) instead of O(n log n) time, however they're not trivial to implement and are not available in Python's standard library.

orlp
  • 112,504
  • 36
  • 218
  • 315
  • why did you do l[Middle]? What does that do? but thank you very much :D – NeoJoker26 Feb 21 '20 at 17:15
  • @NeoJoker26 I calculated `middle` as the index of the middle element (or the one right after the middle for even length arrays). `l[idx]` gets the element at index `idx` in Python. – orlp Feb 21 '20 at 17:16
0

I created a class. You can add elements to your list with the addNum method. The findMedian method will check if the length of the list is odd or even and will give you the median depending on the situation.

class MedianFinder:
    def __init__(self):
        num_list = []
        self.num_list = num_list

    def addNum(self, num):
        self.num_list.append(num)
        return self.num_list

    def findMedian(self):
        # Check len of list
        if len(self.num_list) % 2 == 0:
            l = int(len(self.num_list) / 2)
            return (self.num_list[l - 1] + self.num_list[l]) / 2

        else:
            l = math.floor(len(li) / 2)
            return self.num_list[l]

Example usage;

s.addNum(2)
s.addNum(4)
s.addNum(6)
s.addNum(8)
print(s.findMedian())

Output: 5.0

hasangzc
  • 63
  • 7