TI/Boxcar

Z Brain-wiki
Wersja z dnia 11:52, 7 maj 2019 autorstwa Tgub (dyskusja | edycje) (Utworzono nową stronę "<source lang="python"> #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 7 12:45:41 2019 @author: tgub """ #boxcar kompozycja class boxcar_com():...")
(różn.) ← poprzednia wersja | przejdź do aktualnej wersji (różn.) | następna wersja → (różn.)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May  7 12:45:41 2019

@author: tgub
"""
#boxcar kompozycja
class boxcar_com():
    def __init__(self,N):
        self.__sum=0
        self.__sum2=0
        self.__N=N
        self.__list=[]
    def __str__(self):return self.__list.__str__()
    def __repr__(self):return self.__list.__repr__()
            
    def __getitem__(self,index):
        print('tutaj blad index =',index)
        return self.__list[index]
    
    def append(self,elem):
        self.__sum+=elem
        self.__sum2+=elem*elem
        if len(self.__list)>=self.__N:
            self.__sum-=self.__list[0]
            self.__sum2-=self.__list[0]*self.__list[0]
            self.__list.pop(0)
        self.__list.append(elem)
        print('append com',elem)
    @property
    def mean(self):
        return self.__sum/len(self.__list)
    @property
    def var(self):
        return self.__sum2/(len(self.__list))-self.mean*self.mean
        
#boxcar dziedziczenie
class boxcar_inh(list):
    def __init__(self,N):
        super().__init__([])
        self.__sum=0
        self.__sum2=0
        self.__N=N
    def __setitem__(self,index,value):
        raise TypeError
    def append(self,elem):
        self.__sum+=elem
        self.__sum2+=elem*elem
        if len(self)>=self.__N:
            self.__sum-=self[0]
            self.__sum2-=self[0]*self[0]
            self.pop(0)
        super().append(elem)
        print('append inh',elem)
    @property
    def mean(self):
        return self.__sum/len(self)
    @property
    def var(self):
        return self.__sum2/(len(self))-self.mean*self.mean
 
       
ac=boxcar_com(5)
ai=boxcar_inh(5)

ac.append(1)
ai.append(1)
ac.append(2)
ai.append(2)
ac.append(3)
ai.append(3)
ac.append(4)
ai.append(4)
ac.append(5)
ai.append(5)
print('ac',ac.mean,ac.var,ac)
print('ai',ai.mean,ai.var,ai)
ac.append(6)
ai.append(6)
print('ac',ac.mean,ac.var,ac)
print('ai',ai.mean,ai.var,ai)
ac.append(7)
ai.append(7)
print('ac',ac.mean,ac.var,ac)
print('ai',ai.mean,ai.var,ai)