Home > front end >  How can I modify my class to input stuff into my lists and find the mean of the class?
How can I modify my class to input stuff into my lists and find the mean of the class?

Time:12-04

So I have created a class Calculate where I will define two functions plus(self,x) and avg_over_totalnum(self) that will modify a list __init__(self, items).

plus(self, x) will add either x or the members of x to the list self.items. Here x is one of the following: (1) a number, (2) a list, or (3) a tuple. If x is a number, it is added to the list directly. If x is a list or a tuple, its members are individually added to the list.

For instance if self.items == [5]

if x == 45, plus(self, x) will return [5,45] if x == [4,5], the output will be [5,4,5]

avg_over_totalnum(self) will compute and return the mean of the data maintained in the collection

Here is my attempt at the code so far, which doesn't work at all...

class Calculate:
    def __init__(self, items):
        self.items = list(items)
    def plus(self,x):
        if x in 123456789:
            return self.items   x
        else:
            return self.items.append(x)
    def avg_over_totalnum(self):
        return (sum(self.items))/(len(self.items))

What changes should I make in my code??

CodePudding user response:

Your plus method is a bit weird. It doesn't modify self.items in-place, so self.items don't get updated with x. Also, your if-statement is checking if x is in an integer, which doesn't make sense. Change plus with the function below:

def plus(self,x):
    if isinstance(x,(list,tuple)):
        self.items.extend(list(x))
    else:
        self.items.append(x)
    return self.items

Also to avoid ZeroDivisionError:

def avg_over_totalnum(self):
    return (sum(self.items))/(len(self.items)) if self.items else 0

Then it works fine.

c = Calculate([5])
print(c.plus(4))             # [5, 4]
print(c.plus([3,2]))         # [5, 4, 3, 2]
print(c.avg_over_totalnum()) # 3.5
  • Related