Skip to content

Instantly share code, notes, and snippets.

@pschanely
Created February 9, 2020 19:52
Show Gist options
  • Save pschanely/8579e7cc70d4736c6cd921009ee20ec7 to your computer and use it in GitHub Desktop.
Save pschanely/8579e7cc70d4736c6cd921009ee20ec7 to your computer and use it in GitHub Desktop.
Shared via CrossHair Playground
import dataclasses
from typing import List
@dataclasses.dataclass
class AverageableStack:
'''
A stack of numbers with a O(1) average() operation.
inv: self._total == sum(self._values)
'''
_values: List[int]
_total: int
def __init__(self):
self._values = []
self._total = 0
def push(self, val: int):
self._values.append(val)
self._total += val
def pop(self) -> int:
''' pre: len(self._values) > 0 '''
val = self._values.pop()
# Oops. We are forgetting to do something here.
return val
def average(self) -> float:
''' pre: self._values '''
return self._total / len(self._values)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment