Home > Enterprise >  How can I find the following from the functions under this class?
How can I find the following from the functions under this class?

Time:12-05

So I created a class Calculate where I will implement three functions, number(self,r), reoccurence(self) and var(self)....

number(self,r) will compute and return the value at the r -th percentile of the data in the collection, where r is an integer in [0, 100) (i.e., excluding 100 but including 0). For this problem, this is the value at the position (r/100)*len(list) the list is called self.items

As an example, for the data collection [4, 2, 8, 7, 3, 1, 5], the 98-th percentile value is 8 because the collection once sorted is

[1, 2, 3, 4, 5, 7, 8] and b [(98/100)*7] == 6, and the sixth variable in the list is 8.

reoccurence(self) will calculate the mode of the list called self.items

var(self) will return the standard deviation of the list self.items...

Here is my code so far, which doesn't fully work... what changes should I make to this?

class Calculate:
    def __init__(self, items):
        self.items = list(items)
    def number(self,r):
        return self.items[(r/100)*len(sorted(self.items))]
    def reoccurence(self):
        m = max([self.items.count(a) for a in self.items])
        return [x for x in self.items if self.items.count(x) == m][0] if m > 1 else None
    def var(self):
        n = len(self.items)
        mean = sum(self.items) / n
        var = sum((x - mean) ** 2 for x in self.items) / n
        std_dev = var ** 0.5
        return std_dev

What changes should I make to my code to make sure this works??

CodePudding user response:

I think that you should convert the percentile into int in the numbers function. It returns a error because the percentile is "float". And sort your list in the numbers function to get the expected answer. I tried your code and what exactly do you want the type of input to be?

CodePudding user response:

Your number method doesn't work as expected because (a) you need to make the percentile an integer otherwise it throws a TypeError, (b) you need to index the sorted self.items, otherwise 98th percentile will return the last item in the list, not the number at 98th percentile.

You can iterate over the set of self.items in reoccurrence for better performance.

def number(self,r):
    return sorted(self.items)[int(r/100*len(self.items))]
def reoccurence(self):
    return max((self.items.count(a), a) for a in set(self.items))[1] if self.items else None

Output:

c = Calculate([4, 2, 8, 7, 3, 1, 5, 2])
print(c.number(98))    # 8
print(c.reoccurence()) # 2
print(c.var())         # 2.345
  • Related