Create Python median class

Asked 2 years ago, Updated 2 years ago, 16 views

class Median:


    def __init__(self):
        pass

    def get_item(self, item):
        pass

    def clear(self):
        pass

    def show_result(self):
        pass


    for x in [0.5, 6.2, -0.4, 9.6, 0.4]:
       median.get_item(x)

    median.show_result()
    median.clear()

Complete the class that outputs the median of the input values. If the input value is even, output the mean of the two median values. (However, the clear method deletes all input history)

This is the code I wrote by me I didn't know because I was learning the class this time. I received it as a for statement, appended it, sorted it, and made a median, but I don't know the link between the functions, so I'd appreciate it if you could let me know.

class Median:

    def __init__(self):
        pass

    def get_item(self, item):
        item=[]
        self.item = item
        item.append(item)
        item.sort()

    def clear(self):
        pass

    def show_result(self):

        centerIndex = len(self.item) // 2 
        if len(self.item)% 2 == 1:
            result = self.item[centerIndex ]
        else:
            result = ((self.item[centerIndex - 1] + self.item[centerIndex ]) / 2)
        return result

        print(result)

python

2022-09-20 16:25

1 Answers

First of all, I will tell you the biggest problem.

In get_item, create an empty list of items, and then self.Assign to the item. This way, whenever get_item is called, self.The item will be initialized. I can't collect more than two items.

I guess so

You can initialize the item list once in init and again when you empty it in clear.


2022-09-20 16:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.