0

I want to register my weight every day and calculate the average of the last 7 days.

Therefore, the average will have to be calculated with the following weights:

Day 0 = 80 [the weight today]
Day -1 = 79
Day -2 = 78.5
... 
Day -6 = 78

Therefore, what today is "Day 0", tomorrow will be "Day -1" and so on.

How would you deal with the name of the variables?

Thanks

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
dm18
  • 9
  • 5
    This is where you use a list. – rdas Oct 06 '22 at 14:53
  • you could also use a dict. have keys like `Day -1` so forth. it would work if you want to access a value like `d['Day -20']` - which you cannot with a list, afaik. – rv.kvetch Oct 06 '22 at 14:56

1 Answers1

0

Assuming the problem statement:

"""
Day 0 = 80 [the weight today]
Day -1 = 79
Day -2 = 78.5
...
Day -6 = 78
"""

You could use a custom list implementation as below:

class DaysList(list):
    def __getitem__(self, item, __get=list.__getitem__):
        if item > 0:
            raise ValueError(f'unexpected behavior ({item!r} > 0), '
                             'raising an error to be safe.')
        # noinspection PyArgumentList
        return __get(self, -item)

    def __str__(self):
        return f'{self.__class__.__qualname__}<{self!r}>'


days = DaysList([80, 79, 78.5])

print(days)

assert days[0] == 80
assert days[-2] == 78.5

Output:

DaysList<[80, 79, 78.5]>
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53